exlo 0.0.11 → 0.0.13
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/dist/cli/index.mjs +1 -1
- package/dist/defineConfig.mjs +1 -1
- package/dist/standalone.js +10 -10
- package/dist/standalone.mjs +9 -9
- package/dist/standalone_types.d.ts +9 -8
- package/package.json +1 -1
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFile as I}from"node:fs/promises";import p from"node:path";import{pathToFileURL as O}from"node:url";import{parseArgs as Y}from"node:util";var j="exlo",b="0.0.
|
|
2
|
+
import{readFile as I}from"node:fs/promises";import p from"node:path";import{pathToFileURL as O}from"node:url";import{parseArgs as Y}from"node:util";var j="exlo",b="0.0.13";var g=!1,R=e=>{g=e},A=()=>g,l=(e,t)=>{g&&console.log(`\x1B[${e}m${t}\x1B[0m`)},C=e=>console.log(`\x1B[31m${e}\x1B[0m`),$=e=>l("32",e),q=e=>l("33",e),L=e=>l("36",e),S=e=>l("90",e),F=e=>l("94",e),_=e=>l("95",e),D=e=>g?console.log(e):void 0,n={GREEN:$,YELLOW:q,CYAN:L,BR_BLUE:F,RED:C,GREY:S,PINK:_,setDebug:R,getDebug:A,info:D};var y={config:{type:"string",short:"c",default:"exlo.config.ts",description:"Path to exlo 'defineConfig' file."},debug:{type:"boolean",default:!1,description:"Enable debug mode. When enabled exlo will print usefull informations."},create:{type:"boolean",default:!1,description:"Create exlo 'defineConfig' file based on passed options."},runtime:{type:"string",short:"r",description:"Lambda default runtime (ex: nodejs22.x, python3.7, ruby2.7 etc.)."},timeout:{type:"string",short:"t",default:"3",description:"Lambda default timeout."},port:{type:"string",short:"p",default:"0",description:"Lambda server port."},definitions:{type:"string",short:"d",description:"Path to .json, .mjs, .cjs file with Lambda function definitions."},functions:{type:"string",short:"f",multiple:!0,description:"Glob pattern to automatically find and define Lambda handlers."},exclude:{type:"string",short:"X",multiple:!0,default:[".(test|spec)."],description:"RegExp string to exclude found enteries from --functions."},"handler-name":{type:"string",default:"handler",description:"Handler function name. To be used with --functions."},env:{type:"string",short:"e",multiple:!0,default:[],description:"Environment variables to be injected into Lambdas. All existing AWS_* are automatically injected.",example:"-e API_KEY=supersecret -e API_URL=https://website.com"},"optimize-build":{type:"boolean",default:!1,description:"externalize dependencies and other stuff"},"shim-require":{type:"boolean",default:!1,description:"shim 'require()', '__dirname' and '__filename' when bundeling Lambdas with ESM format"},help:{type:"boolean",short:"h",skipFullPrint:!0},version:{type:"boolean",short:"v",skipFullPrint:!0},"esbuild-external":{type:"string",multiple:!0,skip:!0},"esbuild-resolveExtensions":{type:"string",multiple:!0,skip:!0},"esbuild-mainFields":{type:"string",multiple:!0,skip:!0},"esbuild-conditions":{type:"string",multiple:!0,skip:!0},"esbuild-entryPoints":{type:"string",multiple:!0,skip:!0},"esbuild-inject":{type:"string",multiple:!0,skip:!0},"esbuild-nodePaths":{type:"string",multiple:!0,skip:!0}};function M(){n.setDebug(!0),n.GREY("Usage examples:"),console.log("exlo -c exlo.config.ts"),console.log(`exlo -p 3000 --debug --functions "src/lambdas/**/*.ts"
|
|
3
3
|
`),n.BR_BLUE("Options:");for(let[e,t]of Object.entries(y)){let i=e;if(t.skip)continue;if(t.short&&(i+=`, -${t.short}`),t.skipFullPrint){n.CYAN(` --${i}
|
|
4
4
|
`);continue}let s=` type: ${t.type}`;t.description&&(s+=`
|
|
5
5
|
description: ${t.description}`),"default"in t&&(s+=`
|
package/dist/defineConfig.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var h="0.0.
|
|
1
|
+
var h="0.0.13";function k(e){let c=new Set;e.plugins&&(e.plugins=e.plugins.filter((i,a)=>typeof i!="object"||!i||!("name"in i)?!1:((!i.name||!i.name.length||typeof i.name!="string")&&(i.name=`plugin-${a}`,console.warn(`No Plugin name provided at index ${a}`)),c.has(i.name)?i.name=i.name+a:c.add(i.name),!0)));async function f({stop:i,lambdas:a,region:g,esbuild:v,getServices:y,setService:d,addLambda:p,log:l,setEndpoint:b,getEndpoint:x,getAwsProviderDefaults:C,setAwsProviderDefaults:S}){let r={build:{esbuild:e?.build?.esbuild??{},shimRequire:e?.build?.shimRequire,optimizeBuild:e?.build?.optimizeBuild},server:{port:e.server?.port,setEndpointEnvVar:e.server?.setEndpointEnvVar},onKill:[]};if(e.defaults&&typeof e.defaults=="object"&&!Array.isArray(e.defaults)&&S(e.defaults),e.functions&&typeof e.functions=="object"&&!Array.isArray(e.functions))for(let[m,s]of Object.entries(e.functions))p(m,s);e.services&&(e.services.sqs&&d("sqs",e.services.sqs),e.services.sns&&d("sns",e.services.sns),e.services.dynamodb&&d("dynamodb",e.services.dynamodb));let o={stop:i,lambdas:a,region:g,esbuild:v,options:e,config:r,getServices:y,setService:d,addLambda:p,log:l,setEndpoint:b,getEndpoint:x,getAwsProviderDefaults:C};if(e.plugins){r.server.onReady=async(s,n)=>{for(let t of e.plugins)if(t.server?.onReady)try{await t.server.onReady.call(o,s,n)}catch(u){l.RED(t.name),console.error(u)}},r.buildCallback=async(s,n)=>{for(let t of e.plugins)if(t.buildCallback)try{await t.buildCallback.call(o,s,n)}catch(u){l.RED(t.name),console.error(u),n||process.exit(1)}};let m=e.plugins.reduce((s,n)=>(n.server?.request?.length&&s.push(...n.server.request),s),[]);m?.length&&(r.server.request=m.map(s=>(s.callback=s.callback.bind(o),s)));for(let s of e.plugins)if(s.onKill&&r.onKill.push(s.onKill.bind(o)),s.onInit)try{await s.onInit.call(o)}catch(n){throw l.RED(s.name),n}}return r}return f.plugins=e.plugins??[],f}export{k as defineConfig,h as exloVersion};
|
package/dist/standalone.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var Mt=Object.create;var U=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Ht=Object.prototype.hasOwnProperty;var _t=(t,e)=>{for(var n in e)U(t,n,{get:e[n],enumerable:!0})},Re=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!Ht.call(t,s)&&s!==n&&U(t,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return t};var P=(t,e,n)=>(n=t!=null?Mt(Ft(t)):{},Re(e||!t||!t.__esModule?U(n,"default",{value:t,enumerable:!0}):n,t))
|
|
2
|
-
`,ke=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let l of s())l.writable&&l.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(l){console.log(l)}o=!0}),n&&(i.initialOptions.external.push(...Ae),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=Ut(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var Pe=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var Oe=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),e};var Le=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var Wt=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},Ne=t=>{let e={},n=Wt(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var De=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let l=n.split(":");l.length&&(e.name=l[l.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var z=["lambda","sns","sqs"],Te=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=De(o);a&&r.push(a)}continue;case"dynamodb":{let a=Ne(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},V=t=>{if(!(!t||t.type&&!z.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if(z.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,z.includes(n)&&(e.kind=n)}else if(z.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};var dt=require("node:crypto"),pt=P(require("node:http")),mt=P(require("node:inspector")),ye=require("node:os");var Fe=require("node:crypto");var B=!1,zt=t=>{B=t},Vt=()=>B,j=(t,e)=>{B&&console.log(`\x1B[${t}m${e}\x1B[0m`)},Bt=t=>console.log(`\x1B[31m${t}\x1B[0m`),Jt=t=>j("32",t),Qt=t=>j("33",t),Kt=t=>j("36",t),Gt=t=>j("90",t),Yt=t=>j("94",t),Xt=t=>j("95",t),Zt=t=>B?console.log(t):void 0,b={GREEN:Jt,YELLOW:Qt,CYAN:Kt,BR_BLUE:Yt,RED:Bt,GREY:Gt,PINK:Xt,setDebug:zt,getDebug:Vt,info:Zt};var Me="application/vnd.awslambda.http-integration-response",A=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==Me&&(!this._ct||this._ct==Me),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var qe="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",je="<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>";var en=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],tn=JSON.stringify({Message:null}),J=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},He=(t,e)=>{if(!en.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(tn),!0},D=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},Q=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},K=t=>t instanceof A,_e=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},F=t=>{let e=(0,Fe.randomUUID)();return t.setHeader("x-amzn-RequestId",e),e},G=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Y=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),X=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),Z=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},$e=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var dr=new Error(je);var Ce=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(Ce).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];i[d]=h,m=="x-api-key"&&(s=h),c=c+2}let o={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[c]=i[c];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];a[d]?a[d].push(h):a[d]=[h],c=c+2}let l={};for(let c of Object.keys(a).sort((d,m)=>d.localeCompare(m)))l[c]=a[c];return{headers:o,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(c=>c.toLowerCase()),l=o.toLowerCase();a?r[l]?r[l].push(...a):r[l]=a:r[l]||(r[l]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};var Qe=require("exlo/internal/esm");var We=require("exlo/internal/esm");var ee=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,r=await this.handlers.find(s=>s.name==this.lambdaName).invoke({Records:this.#e});await this.onInvokeFinished(e,r)}};var ze=10,Ve=0,nn=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),rn=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),Ue=async(t,e,n)=>{for(let r of Je(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},sn=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},on=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:l}=t,c={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:sn(a)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},an=(t,e)=>t.map(n=>on(n,e)),te=class extends We.EventSourceMapping{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Be(n,r)),await Ue(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new ee(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#c(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await rn(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await nn(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=an(s,this.config.EventSourceArn),o=await this.#l(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#c(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(n){let r=n.map(a=>{let l={...a};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(r);await Ue(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(l=>l.messageId==a.messageId));return o}};var Ke=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let l;if(Array.isArray(o.filterPatterns)){l=[];for(let d of o.filterPatterns)l.push({Pattern:JSON.stringify(d)});l.length||(l=void 0)}let c=new te({BatchSize:typeof o.batchSize=="number"?o.batchSize:ze,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:l?{Filters:l}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Ve},t,s.sqs);if(Qe.EventSourceMapping.SOURCES.push(c),c.config.Enabled)try{await c.init()}catch(d){b.RED(`Failed to start EventSourceMapping ${c.config.EventSourceArn}
|
|
3
|
-
Please verify provided SQS Client validity.`),console.error(d)}}},cn=/(-|\w+)/g,ln=t=>t.length<81&&t.replace(cn,"")=="",Be=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!ln(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},Je=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};var nt=require("node:crypto");var Ge=P(require("node:http")),dn=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},Ye=(t,e)=>{let n=dn(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Ge.default.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},Xe=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},pn=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=Xe({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(l){console.log(l)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},mn=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},Ze=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return pn({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return Xe({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return mn({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},ue=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},et=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var un=1080*1e3,fn=new Set(["async","ddb","kinesis","s3","sns","sqs"]),tt=t=>typeof t?.kind=="string"?fn.has(t.kind)||t.async:!1,$=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:l,esOutputPath:c,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:S,onSuccess:u,onFailure:v,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=l,this.esOutputPath=c,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=S,this.onSuccess=u,this.onFailure=v,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),tt(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&ue({...i,destination:this.onError}),this.onFailure&&ue({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&tt(n)&&et({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=(0,nt.randomUUID)();this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let l=await a(e,n);typeof l!="function"&&(e=l)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(l,c)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.name}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),l(m)}catch(m){clearTimeout(d),c(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},un)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;b.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),b.GREY(this.entryPoint);let l="";return typeof r?.kind=="string"&&(l=` (${r.kind.toUpperCase()})`),b.YELLOW(`\u03BB payload${l}:`),b.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}};var ne=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};var rt=require("node:events"),st=P(require("node:path")),it=require("node:worker_threads");var hn=st.default.resolve(q("exlo"),"./dist/lib/runtime/runners/node/index.js"),re=class extends rt.EventEmitter{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((l,c)=>{this.once("loaded",d=>{d?l(void 0):c()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",l=>{let{channel:c,data:d,awsRequestId:m,type:h,encoding:p}=l;c=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(b.BR_BLUE("Solution:"),console.log(d.solution))):c=="fail"?(this.emit(m,c,d,h,p),this.unmount()):this.emit(m,c,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:l,info:c,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:l,clientContext:d},awsRequestId:h});let y=m??new A(c);function f(S,u,v,w){switch(S){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":v=="write"?y.write(u,w):v=="ct"?y.setHeader("Content-Type",u):v=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof A?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={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:b.getDebug()}};this._worker=new it.Worker(hn,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};var ie=require("node:child_process"),at=require("node:fs"),fe=require("node:fs/promises"),H=P(require("node:path"));var yn=process.cwd();function ot(t){let e="";try{e=(0,ie.execSync)(t,{encoding:"utf-8"})}catch{}return e}var se=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=H.default.resolve(q("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=H.default.resolve(i);this.handlerDir=H.default.dirname(c),this.handlerPath=H.default.basename(c,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(yn,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=c.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await(0,fe.access)(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),S="",u=w=>{let E=null,R=w.toString();try{let L=R.includes(t.WATCH);if(L&&this.setWatchFiles(R),R.startsWith(t.DELIMITER)&&R.includes(t.DELIMITEREND)){let I=R.split(t.DELIMITER),T=I[I.length-1].split(t.DELIMITEREND)[0];if(I.length>1){let M;L?M=I[0].split(t.WATCHEND)[1]:M=I.slice(0,-1).join(`
|
|
4
|
-
`),M.trim()&&console.log(M)}T&&(E=JSON.parse(T)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",
|
|
1
|
+
"use strict";var Mt=Object.create;var U=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Ht=Object.prototype.hasOwnProperty;var _t=(t,e)=>{for(var n in e)U(t,n,{get:e[n],enumerable:!0})},Re=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!Ht.call(t,s)&&s!==n&&U(t,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return t};var P=(t,e,n)=>(n=t!=null?Mt(Ft(t)):{},Re(e||!t||!t.__esModule?U(n,"default",{value:t,enumerable:!0}):n,t)),Ct=t=>Re(U({},"__esModule",{value:!0}),t);var Cn={};_t(Cn,{createAppRunner:()=>Dt,exloVersion:()=>ut,run:()=>_n});module.exports=Ct(Cn);var O=P(require("node:path")),xe=P(require("esbuild")),Nt=require("exlo/internal/esm");var me=P(require("node:path")),Ie=require("node:module"),$t={},_=require,W={};function q(t){if(W[t])return W[t];if(typeof _=="function"&&typeof _.resolve=="function"){let n=me.default.resolve(_.resolve(t),"../../");return W[t]=n,n}_=(0,Ie.createRequire)(new URL(".",$t.url));let e=me.default.resolve(_.resolve(t),"../../");return W[t]=e,e}var Ae=["aws-sdk","@aws-sdk/*","@angular/core","@angular/platform-browser","@aws-sdk/*","@elastic/elasticsearch","@hapi/joi","@opensearch-project/opensearch","@smithy/*","axios","axios-retry","axios-cache-interceptor","aws-serverless-express","aws-sdk","body-parser","classnames","clsx","cookie-parser","cors","core-js","date-fns","dayjs","express","helmet","joi","koa","leaflet","lodash","mysql","mysql2","mongodb","mongoose","moment","http-proxy","http-proxy-middleware","react","react/*","react-dom","react-dom/*","react-hook-form","react-infinite-scroll-component","react-modal","react-rangeslider","react-responsive","react-select","react-scroll","react-slick","react-lazy-load","react-lazyload","react-redux","react-router","react-router-dom","redux","redux-persist","regenerator-runtime","serve-static","express-session","exlo/*","serverless-http","sequelize","svelte","svelte/*","typeorm","pg","pg-hstore","prop-types","underscore","uuid","vue","xmlbuilder","yup","zod","sharp"];var Ut=t=>`import { createRequire as __crE_ } from "${t}module";import { fileURLToPath as __futP_ } from "${t}url";import { dirname as __dN_ } from "${t}path";global.__filename = __futP_(import.meta.url);global.__dirname = __dN_(__filename);global.require = __crE_(__filename);
|
|
2
|
+
`,ke=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let l of s())l.writable&&l.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(l){console.log(l)}o=!0}),n&&(i.initialOptions.external.push(...Ae),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=Ut(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var Pe=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var Oe=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),e};var Le=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var Wt=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},Ne=t=>{let e={},n=Wt(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var De=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let l=n.split(":");l.length&&(e.name=l[l.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var z=["lambda","sns","sqs"],Te=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=De(o);a&&r.push(a)}continue;case"dynamodb":{let a=Ne(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},V=t=>{if(!(!t||t.type&&!z.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if(z.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,z.includes(n)&&(e.kind=n)}else if(z.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};var dt=require("node:crypto"),pt=P(require("node:http")),mt=P(require("node:inspector")),ye=require("node:os");var Fe=require("node:crypto");var B=!1,zt=t=>{B=t},Vt=()=>B,j=(t,e)=>{B&&console.log(`\x1B[${t}m${e}\x1B[0m`)},Bt=t=>console.log(`\x1B[31m${t}\x1B[0m`),Jt=t=>j("32",t),Qt=t=>j("33",t),Kt=t=>j("36",t),Gt=t=>j("90",t),Yt=t=>j("94",t),Xt=t=>j("95",t),Zt=t=>B?console.log(t):void 0,b={GREEN:Jt,YELLOW:Qt,CYAN:Kt,BR_BLUE:Yt,RED:Bt,GREY:Gt,PINK:Xt,setDebug:zt,getDebug:Vt,info:Zt};var Me="application/vnd.awslambda.http-integration-response",A=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==Me&&(!this._ct||this._ct==Me),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var qe="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",je="<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>";var en=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],tn=JSON.stringify({Message:null}),J=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},He=(t,e)=>{if(!en.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(tn),!0},D=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},Q=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},K=t=>t instanceof A,_e=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},F=t=>{let e=(0,Fe.randomUUID)();return t.setHeader("x-amzn-RequestId",e),e},G=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Y=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),X=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),Z=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},Ce=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var dr=new Error(je);var $e=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map($e).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];i[d]=h,m=="x-api-key"&&(s=h),c=c+2}let o={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[c]=i[c];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];a[d]?a[d].push(h):a[d]=[h],c=c+2}let l={};for(let c of Object.keys(a).sort((d,m)=>d.localeCompare(m)))l[c]=a[c];return{headers:o,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(c=>c.toLowerCase()),l=o.toLowerCase();a?r[l]?r[l].push(...a):r[l]=a:r[l]||(r[l]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};var Qe=require("exlo/internal/esm");var We=require("exlo/internal/esm");var ee=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,r=await this.handlers.find(s=>s.name==this.lambdaName).invoke({Records:this.#e});await this.onInvokeFinished(e,r)}};var ze=10,Ve=0,nn=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),rn=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),Ue=async(t,e,n)=>{for(let r of Je(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},sn=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},on=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:l}=t,c={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:sn(a)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},an=(t,e)=>t.map(n=>on(n,e)),te=class extends We.EventSourceMapping{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Be(n,r)),await Ue(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new ee(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#c(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await rn(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await nn(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=an(s,this.config.EventSourceArn),o=await this.#l(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#c(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(n){let r=n.map(a=>{let l={...a};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(r);await Ue(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(l=>l.messageId==a.messageId));return o}};var Ke=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let l;if(Array.isArray(o.filterPatterns)){l=[];for(let d of o.filterPatterns)l.push({Pattern:JSON.stringify(d)});l.length||(l=void 0)}let c=new te({BatchSize:typeof o.batchSize=="number"?o.batchSize:ze,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:l?{Filters:l}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Ve},t,s.sqs);if(Qe.EventSourceMapping.SOURCES.push(c),c.config.Enabled)try{await c.init()}catch(d){b.RED(`Failed to start EventSourceMapping ${c.config.EventSourceArn}
|
|
3
|
+
Please verify provided SQS Client validity.`),console.error(d)}}},cn=/(-|\w+)/g,ln=t=>t.length<81&&t.replace(cn,"")=="",Be=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!ln(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},Je=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};var nt=require("node:crypto");var Ge=P(require("node:http")),dn=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},Ye=(t,e)=>{let n=dn(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Ge.default.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},Xe=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},pn=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=Xe({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(l){console.log(l)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},mn=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},Ze=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return pn({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return Xe({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return mn({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},ue=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},et=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var un=1080*1e3,fn=new Set(["async","ddb","kinesis","s3","sns","sqs"]),tt=t=>typeof t?.kind=="string"?fn.has(t.kind)||t.async:!1,C=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:l,esOutputPath:c,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:v,onSuccess:u,onFailure:S,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=l,this.esOutputPath=c,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=v,this.onSuccess=u,this.onFailure=S,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),tt(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&ue({...i,destination:this.onError}),this.onFailure&&ue({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&tt(n)&&et({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=(0,nt.randomUUID)();this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let l=await a(e,n);typeof l!="function"&&(e=l)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(l,c)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.name}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),l(m)}catch(m){clearTimeout(d),c(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},un)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;b.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),b.GREY(this.entryPoint);let l="";return typeof r?.kind=="string"&&(l=` (${r.kind.toUpperCase()})`),b.YELLOW(`\u03BB payload${l}:`),b.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}};var ne=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};var rt=require("node:events"),st=P(require("node:path")),it=require("node:worker_threads");var hn=st.default.resolve(q("exlo"),"./dist/lib/runtime/runners/node/index.js"),re=class extends rt.EventEmitter{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((l,c)=>{this.once("loaded",d=>{d?l(void 0):c()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",l=>{let{channel:c,data:d,awsRequestId:m,type:h,encoding:p}=l;c=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(b.BR_BLUE("Solution:"),console.log(d.solution))):c=="fail"?(this.emit(m,c,d,h,p),this.unmount()):this.emit(m,c,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:l,info:c,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:l,clientContext:d},awsRequestId:h});let y=m??new A(c);function f(v,u,S,w){switch(v){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":S=="write"?y.write(u,w):S=="ct"?y.setHeader("Content-Type",u):S=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof A?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={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:b.getDebug()}};this._worker=new it.Worker(hn,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};var ie=require("node:child_process"),at=require("node:fs"),fe=require("node:fs/promises"),H=P(require("node:path"));var yn=process.cwd();function ot(t){let e="";try{e=(0,ie.execSync)(t,{encoding:"utf-8"})}catch{}return e}var se=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=H.default.resolve(q("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=H.default.resolve(i);this.handlerDir=H.default.dirname(c),this.handlerPath=H.default.basename(c,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(yn,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=c.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await(0,fe.access)(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),v="",u=w=>{let E=null,R=w.toString();try{let L=R.includes(t.WATCH);if(L&&this.setWatchFiles(R),R.startsWith(t.DELIMITER)&&R.includes(t.DELIMITEREND)){let I=R.split(t.DELIMITER),T=I[I.length-1].split(t.DELIMITEREND)[0];if(I.length>1){let M;L?M=I[0].split(t.WATCHEND)[1]:M=I.slice(0,-1).join(`
|
|
4
|
+
`),M.trim()&&console.log(M)}T&&(E=JSON.parse(T)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),g(E)}else if(R.startsWith(t.DELIMITER))v=R.slice(t.DELIMITER.length);else if(R.includes(t.DELIMITEREND)){let I=R.slice(0,R.indexOf(t.DELIMITEREND)),T=JSON.parse(`${v}${I}`);this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),g(T)}else if(v)v+=R;else if(!v&&R.trim()){let I;if(L){let T=R.split(`
|
|
5
5
|
`),M=T.findIndex(Tt=>Tt.startsWith(t.WATCH));I=T.slice(0,M).join(`
|
|
6
|
-
`)}else I=R;I.trim()&&console.log(I)}}catch(L){console.log("err",L),y(L)}};this.python.stdout.on("data",u);let
|
|
7
|
-
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,H.default.sep)}.py`);for(let o of i)try{await(0,fe.access)(o),this.watchers.push((0,at.watch)(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(ot(`${e} --version`))return e;let r=ot("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&b.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=(0,ie.spawn)(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,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};onComplete=e=>{}};var ct=require("node:child_process"),lt=require("node:fs"),he=require("node:fs/promises")
|
|
8
|
-
`);I.trim()&&console.log(I)}L&&(w=JSON.parse(L)),this.ruby.stdout.removeListener("data",
|
|
9
|
-
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await(0,he.access)(i),this.watchers.push((0,lt.watch)(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=(0,ct.spawn)(this.bin,[t.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};onComplete=e=>{}};var gn=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=gn.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var ae;ye.networkInterfaces&&(ae=Object.values((0,ye.networkInterfaces)()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var bn=mt.default?.url()!=null;bn&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),$.ENABLE_TIMEOUT=!1);var Sn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},ce=class extends k{#e;runtimeConfig={};#t;sco=[];aws;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),b.setDebug(n.debug),this.aws=e.aws,this.sco=[],this.#e=pt.default.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=(0,dt.randomUUID)();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(b.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),ae&&(k.ip=ae),typeof n=="function"&&await n(r,ae);try{await this.onReady?.(r,k.ip),await Ke(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",l=>{console.error(l.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end(qe)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(Sn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){let r=n.runtime.charAt(0);n.runner=r=="n"?new re(n):r=="p"?new se(n,this.fakeRebuildEmitter):r=="r"?new oe(n,this.fakeRebuildEmitter):new ne(n.runtime);let s=new $(n);this.addHandler(s)}}};var ht=require("node:fs/promises"),N=P(require("node:path")),yt=require("node:url"),gt=P(require("esbuild"));var ut="0.0.11";function ft(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[]};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[S,u]of Object.entries(t.functions))c(S,u);t.services&&(t.services.sqs&&l("sqs",t.services.sqs),t.services.sns&&l("sns",t.services.sns),t.services.dynamodb&&l("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,v)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,v)}catch(E){d.RED(w.name),console.error(E)}},y.buildCallback=async(u,v)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,v)}catch(E){d.RED(w.name),console.error(E),v||process.exit(1)}};let S=t.plugins.reduce((u,v)=>(v.server?.request?.length&&u.push(...v.server.request),u),[]);S?.length&&(y.server.request=S.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(v){throw d.RED(u.name),v}}return y}return n.plugins=t.plugins??[],n}var xn=["js","mjs","cjs","ts","cts","mts"],wn=async t=>{let e=N.default.dirname(N.default.toNamespacedPath(t)),n=N.default.basename(t,N.default.extname(t)),r=N.default.join(e,`__${n}.mjs`);await gt.default.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import((0,yt.pathToFileURL)(r).href)}catch(s){throw s}finally{await(0,ht.rm)(r)}},bt=async t=>{if(t){if(typeof t=="string"){let e=N.default.posix.parse(t),n=N.default.posix.join(e.dir,e.name),r=e.ext.slice(1),s=N.default.posix.resolve(n);xn.includes(r)&&(s+=`.${r}`);let i;try{i=await wn(s)}catch(o){b.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:ft(t)}}};var En=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},ge=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(En),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};var be=require("node:crypto");var le=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:l,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:c,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:l}=e,c=t.getPathParameters(n,r),d,m=n.methods.find(v=>v==a)??"ANY",h={},p="";for(let v of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(v);p+=`&${w.map(E=>encodeURI(`${v}=${E}`)).join("&")}`,h[v]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",S=l.host?.startsWith("localhost")?f:l.host?l.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:S,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(c).length&&(u.pathParameters=c),l.cookie&&(u.cookies=l.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:l}=e,c={};n.proxy=="httpApi"&&(c.version="1.0");let d=n.paths[0];c.resource=d,c.path=r.pathname,c.httpMethod=l;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);c.headers=m,c.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);c.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);c.multiValueQueryStringParameters=Object.keys(f).length?f:null;let S=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:S.toISOString(),requestTimeEpoch:S.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),c.requestContext=u;let v=t.getPathParameters(n,r);return c.pathParameters=Object.keys(v).length?v:null,c.stageVariables=null,c.body=a??null,c.isBase64Encoded=a?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from((0,be.randomUUID)()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
|
|
6
|
+
`)}else I=R;I.trim()&&console.log(I)}}catch(L){console.log("err",L),y(L)}};this.python.stdout.on("data",u);let S=w=>{let E=w.toString();if(E.includes(t.ERR_RESPONSE))try{E=JSON.parse(E.split(t.ERR_RESPONSE)[1]),E.requestId=p}catch{}finally{this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),y(E)}else console.log(E)};this.python.stderr.on("data",S),this.python.stdin.write(`${f}
|
|
7
|
+
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,H.default.sep)}.py`);for(let o of i)try{await(0,fe.access)(o),this.watchers.push((0,at.watch)(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(ot(`${e} --version`))return e;let r=ot("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&b.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=(0,ie.spawn)(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,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};onComplete=e=>{}};var ct=require("node:child_process"),lt=require("node:fs"),he=require("node:fs/promises"),$=P(require("node:path"));var oe=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=$.default.resolve(q("exlo"),"./src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=$.default.resolve(i);this.handlerDir=$.default.dirname(c),this.handlerPath=$.default.basename(c,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await(0,he.access)(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),v=S=>{let w=null,E=S.toString();try{if(E.includes(t.WATCH))this.setWatchFiles(E);else if(E.includes(t.DELIMITER)){let R=E.split(t.DELIMITER),L=R[R.length-1];if(R.length>1){let I=R.slice(0,-1).join(`
|
|
8
|
+
`);I.trim()&&console.log(I)}L&&(w=JSON.parse(L)),this.ruby.stdout.removeListener("data",v),this.ruby.stderr.removeListener("data",u),g(w)}else E.trim()&&console.log(E)}catch(R){y(R)}};this.ruby.stdout.on("data",v);let u=S=>{let w=S.toString();if(w.includes(t.ERR_RESPONSE))try{w=JSON.parse(w.split(t.ERR_RESPONSE)[1]),w.requestId=p}catch{}finally{this.ruby.stdout.removeListener("data",v),this.ruby.stderr.removeListener("data",u),y(w)}else console.log(w)};this.ruby.stderr.on("data",u),this.ruby.stdin.write(`${f}
|
|
9
|
+
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await(0,he.access)(i),this.watchers.push((0,lt.watch)(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=(0,ct.spawn)(this.bin,[t.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};onComplete=e=>{}};var gn=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=gn.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var ae;ye.networkInterfaces&&(ae=Object.values((0,ye.networkInterfaces)()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var bn=mt.default?.url()!=null;bn&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),C.ENABLE_TIMEOUT=!1);var Sn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},ce=class extends k{#e;runtimeConfig={};#t;sco=[];aws;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),b.setDebug(n.debug),this.aws=e.aws,this.sco=[],this.#e=pt.default.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=(0,dt.randomUUID)();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(b.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),ae&&(k.ip=ae),typeof n=="function"&&await n(r,ae);try{await this.onReady?.(r,k.ip),await Ke(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",l=>{console.error(l.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end(qe)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(Sn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){let r=n.runtime.charAt(0);n.runner=r=="n"?new re(n):r=="p"?new se(n,this.fakeRebuildEmitter):r=="r"?new oe(n,this.fakeRebuildEmitter):new ne(n.runtime);let s=new C(n);this.addHandler(s)}}};var ht=require("node:fs/promises"),N=P(require("node:path")),yt=require("node:url"),gt=P(require("esbuild"));var ut="0.0.13";function ft(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[]};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[v,u]of Object.entries(t.functions))c(v,u);t.services&&(t.services.sqs&&l("sqs",t.services.sqs),t.services.sns&&l("sns",t.services.sns),t.services.dynamodb&&l("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,S)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,S)}catch(E){d.RED(w.name),console.error(E)}},y.buildCallback=async(u,S)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,S)}catch(E){d.RED(w.name),console.error(E),S||process.exit(1)}};let v=t.plugins.reduce((u,S)=>(S.server?.request?.length&&u.push(...S.server.request),u),[]);v?.length&&(y.server.request=v.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(S){throw d.RED(u.name),S}}return y}return n.plugins=t.plugins??[],n}var xn=["js","mjs","cjs","ts","cts","mts"],wn=async t=>{let e=N.default.dirname(N.default.toNamespacedPath(t)),n=N.default.basename(t,N.default.extname(t)),r=N.default.join(e,`__${n}.mjs`);await gt.default.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import((0,yt.pathToFileURL)(r).href)}catch(s){throw s}finally{await(0,ht.rm)(r)}},bt=async t=>{if(t){if(typeof t=="string"){let e=N.default.posix.parse(t),n=N.default.posix.join(e.dir,e.name),r=e.ext.slice(1),s=N.default.posix.resolve(n);xn.includes(r)&&(s+=`.${r}`);let i;try{i=await wn(s)}catch(o){b.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:ft(t)}}};var En=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},ge=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(En),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};var be=require("node:crypto");var le=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:l,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:c,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:l}=e,c=t.getPathParameters(n,r),d,m=n.methods.find(S=>S==a)??"ANY",h={},p="";for(let S of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(S);p+=`&${w.map(E=>encodeURI(`${S}=${E}`)).join("&")}`,h[S]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",v=l.host?.startsWith("localhost")?f:l.host?l.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:v,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(c).length&&(u.pathParameters=c),l.cookie&&(u.cookies=l.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:l}=e,c={};n.proxy=="httpApi"&&(c.version="1.0");let d=n.paths[0];c.resource=d,c.path=r.pathname,c.httpMethod=l;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);c.headers=m,c.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);c.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);c.multiValueQueryStringParameters=Object.keys(f).length?f:null;let v=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:v.toISOString(),requestTimeEpoch:v.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),c.requestContext=u;let S=t.getPathParameters(n,r);return c.pathParameters=Object.keys(S).length?S:null,c.stageVariables=null,c.body=a??null,c.isBase64Encoded=a?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from((0,be.randomUUID)()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
|
|
10
10
|
Received:`),console.log(e),new Error;r=e.statusCode,e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.entries(e.headers).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c),h=this.#e(d);n.push([m,h])}),e.multiValueHeaders&&typeof e.multiValueHeaders=="object"&&!Array.isArray(e.multiValueHeaders)&&Object.entries(e.multiValueHeaders).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c);if(!Array.isArray(d))throw new Error;d.map(p=>this.#e(p)).forEach(p=>{n.push([m,p])})});let s=e.body;if(e.isBase64Encoded&&s){if(typeof s!="string")throw new Error;let c=Buffer.from(s,"base64").toString();if(Buffer.from(c).toString("base64")!=s)throw b.RED("response body is not properly base64 encoded"),new Error;s=c}n.findIndex(c=>c[0].toLowerCase()=="content-type")==-1&&n.push(["Content-Type",t.contentType.json]);let o=n.findIndex(c=>c[0].toLowerCase()=="content-length");o!=-1&&n.splice(o,1);let a=typeof s;a=="number"||a=="boolean"?s=String(s):s&&a!="string"&&b.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let l=r==204?"0":s?String(Buffer.from(s).byteLength):"0";n.push(["Content-Length",l]),this.res.shouldKeepAlive=!1,this.res.writeHead(r,n),this.res.end(s)};sendV2Response=e=>{this.res.setHeader("Apigw-Requestid",Buffer.from((0,be.randomUUID)()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),e?(typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.keys(e.headers).filter(s=>s!=="Apigw-Requestid"&&s!=="Date").forEach(s=>{this.res.setHeader(s,e.headers[s])}),e.statusCode?(this.res.statusCode=e.statusCode,e.cookies?.length&&this.res.setHeader("Set-Cookie",e.cookies)):this.res.statusCode=200):this.res.statusCode=200;let n="";if(!e)return this.res.end();if(typeof e=="object"&&typeof e.body=="string"&&(n=e.body,e.isBase64Encoded)){let r=Buffer.from(n,"base64").toString();if(Buffer.from(r).toString("base64")!=n)throw b.RED("response body is not properly base64 encoded"),new Error;n=r}typeof e=="string"?(this.res.setHeader("Content-Type",t.contentType.json),n=e):typeof e=="object"&&!e.statusCode&&(this.res.setHeader("Content-Type",t.contentType.json),n=JSON.stringify(e)),this.res.end(n)};sendResponse=e=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(e):this.sendV2Response(e)}};var Rn=(t,e)=>{let n=e.url.stream?t:void 0;if(n){let r=!1,s=t.write.bind(t),i=t.setHeader.bind(t),o,a,l=m=>{a=a?Buffer.concat([a,m]):m},c=()=>{if(a){let m=_e(a),h=m.statusCode??200;try{let p=ge(m.headers,m.cookies);t.writeHead(h,p)}catch(p){t.writeHead(500,p.headers),t.end?.(x.amzMsgNull),delete p.headers}}else t.writeHead(200)};n.setHeader=(m,h)=>{if(m.toLowerCase()=="content-type"){if(h=="application/vnd.awslambda.http-integration-response")return r=!0,i("Content-Type",x.contentType.json);o=h}return i(m,h)};let d=!1;return n.write=(m,h,p)=>{if(n.headersSent)return s(m,h,p);if(d)try{let g=A.codec.decode(m),y=JSON.parse(g);if(Array.isArray(y))throw new Error("Invalid stream response");return y&&typeof y=="object"?(c(),s(m,h,p)):(t.writeHead(200,{"Content-Type":x.contentType.octet}),t.end())}catch(g){let y=new Error(`When using HttpResponseStream first chunk of .write() must be valid JSON and not be Array. Number and null will respones with 200.
|
|
11
|
-
'${e.name}'`);return y.cause=g.message,console.error(y),Z(t)}else if(r)
|
|
12
|
-
'${e.name}'`);return f.cause=y.message,console.error(f),Z(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},In=(t,e,n,r)=>{let s=K(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let l=isNaN(i.statusCode),c=l?500:i.statusCode;if(a=!l&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=ge(i.headers,i.cookies,r);e.writeHead(c,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(c,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function An(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function St(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function kn(t,e){if(!t.allowMethods)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function Pn(t,e){if(!kn(t,e)||!St(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var vt=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(He(n,s))return;let o=new URL(r,x.dummyHost),a=F(n),l=k.parseNameFromUrl(o.pathname),c=t.handlers.find(f=>f.name==l);if(!c?.url)return n.statusCode=404,n.end("Not Found");let d;if(c.url.cors){if(An(i,s)){let S=Pn(c.url.cors,i),u={"Content-Type":x.contentType.json};return S&&(u["access-control-allow-origin"]=i.origin,u["access-control-allow-methods"]=c.url.cors.allowMethods.join(","),c.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=c.url.cors.allowHeaders.join(",")),typeof c.url.cors.maxAge=="number"&&c.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${c.url.cors.maxAge}`),c.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}St(c.url.cors,i)&&(d={"access-control-allow-origin":i.origin},c.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=c.url.cors.exposeHeaders.join(",")),c.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await D(e,m),p=le.createApgV2Event({req:e,mockEvent:c.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${c.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=Rn(n,c),S=await c.invoke(p,c.url,void 0,f);if(!S)return n.end();In(S,n,f,d)}catch(f){console.error(f),Z(n,d)}}});var xt=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),l=F(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:S}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(X(o,f,S))}let c=s["x-amz-invocation-type"],d=J(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let m=c=="DryRun"?204:c=="Event"?202:200,h=await D(e),p=Q(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let S=K(f),u=S?f.buffer:f;S?u=A.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){n.writableFinished||(n.setHeader("X-Amz-Function-Error",f.errorType??f.message??""),n.statusCode=200,n.end(JSON.stringify(f)))}}});var Se=require("node:crypto"),wt=require("node:timers/promises");var Et=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await D(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:l,Timeout:c,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:l,timeout:c,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await(0,wt.setTimeout)(100),n.statusCode=201,n.end(r)}}),Rt=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,Se.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),Ln=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function It(t){let e={};for(let[n,r]of Object.entries(t))Ln.includes(n)||(e[n]=String(r));return e}var At=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,Se.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),kt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});var Pt=require("@smithy/eventstream-codec");var Nn=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Dn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),ve=new Pt.EventStreamCodec(Dn,Nn),de=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(ve.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(ve.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(ve.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var Ot=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=F(n),a=k.parseNameFromUrl(i.pathname),l=t.handlers.find(p=>p.name==a),c=await D(e),d=Q(c);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(d.message));let m=J(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let h=new de(n);if(l){let p=l.url?.stream??{};try{let g=await l.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(X(a,p,g))}}});var Lt=t=>[Et(t),At(t),kt(t),xt(t),Ot(t),vt(t),Rt(t)];var we=process.cwd(),Tn=3,Mn=1024,qn={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},jn=we.split(O.default.sep)[0],Fn=new RegExp(`^.*:${jn}`),Hn=t=>Fn.test(t);process.title="node (exlo)";var pe=class extends ce{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",b.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")).map(r=>r.esEntryPoint),outdir:O.default.join(we,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&b.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(ke({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=Pe(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await xe.default.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,l)=>{let c=`http://localhost:${a}`;b.PINK(`Lambda endpoint: ${c}`),this.endpoints.lambda=c,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=c),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",c);o({url:c,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)b.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,l=O.default.extname(a),c=l.slice(1),d=O.default.resolve(a.replace(l,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:c,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??Mn,timeout:o.timeout??this.runtimeConfig.timeout??Tn,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:O.default.basename(a),...this.runtimeConfig.environment,...o.environment,...qn},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);b.RED(`'${e}' is not mounted yet.
|
|
11
|
+
'${e.name}'`);return y.cause=g.message,console.error(y),Z(t)}else if(r)Ce(m)?d=!0:l(m);else{if(o==x.contentType.json)try{let y=A.codec.decode(m),f=JSON.parse(y);if(f===null||typeof f=="number")throw new Error(y)}catch(y){let f=new Error(`When 'Content-Type' is 'application/json' first chunk of .write() must be parsable JSON and not be null or number.
|
|
12
|
+
'${e.name}'`);return f.cause=y.message,console.error(f),Z(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},In=(t,e,n,r)=>{let s=K(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let l=isNaN(i.statusCode),c=l?500:i.statusCode;if(a=!l&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=ge(i.headers,i.cookies,r);e.writeHead(c,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(c,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function An(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function St(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function kn(t,e){if(!t.allowMethods?.length)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function Pn(t,e){if(!kn(t,e)||!St(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var vt=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(He(n,s))return;let o=new URL(r,x.dummyHost),a=F(n),l=k.parseNameFromUrl(o.pathname),c=t.handlers.find(f=>f.name==l);if(!c?.url)return n.statusCode=404,n.end("Not Found");let d;if(c.url.cors){if(An(i,s)){let v=Pn(c.url.cors,i),u={"Content-Type":x.contentType.json};return v&&(u["access-control-allow-origin"]=i.origin,c.url.cors.allowMethods.find(S=>S=="*")?u["access-control-allow-methods"]=i["access-control-request-method"]:u["access-control-allow-methods"]=c.url.cors.allowMethods.join(","),c.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=c.url.cors.allowHeaders.join(",")),typeof c.url.cors.maxAge=="number"&&c.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${c.url.cors.maxAge}`),c.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}St(c.url.cors,i)&&(d={"access-control-allow-origin":i.origin},c.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=c.url.cors.exposeHeaders.join(",")),c.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await D(e,m),p=le.createApgV2Event({req:e,mockEvent:c.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${c.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=Rn(n,c),v=await c.invoke(p,c.url,void 0,f);if(!v)return n.end();In(v,n,f,d)}catch(f){console.error(f),Z(n,d)}}});var xt=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),l=F(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:v}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(X(o,f,v))}let c=s["x-amz-invocation-type"],d=J(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let m=c=="DryRun"?204:c=="Event"?202:200,h=await D(e),p=Q(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let v=K(f),u=v?f.buffer:f;v?u=A.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){n.writableFinished||(n.setHeader("X-Amz-Function-Error",f.errorType??f.message??""),n.statusCode=200,n.end(JSON.stringify(f)))}}});var Se=require("node:crypto"),wt=require("node:timers/promises");var Et=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await D(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:l,Timeout:c,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:l,timeout:c,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await(0,wt.setTimeout)(100),n.statusCode=201,n.end(r)}}),Rt=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,Se.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),Ln=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function It(t){let e={};for(let[n,r]of Object.entries(t))Ln.includes(n)||(e[n]=String(r));return e}var At=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,Se.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),kt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});var Pt=require("@smithy/eventstream-codec");var Nn=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Dn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),ve=new Pt.EventStreamCodec(Dn,Nn),de=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(ve.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(ve.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(ve.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var Ot=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=F(n),a=k.parseNameFromUrl(i.pathname),l=t.handlers.find(p=>p.name==a),c=await D(e),d=Q(c);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(d.message));let m=J(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let h=new de(n);if(l){let p=l.url?.stream??{};try{let g=await l.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(X(a,p,g))}}});var Lt=t=>[Et(t),At(t),kt(t),xt(t),Ot(t),vt(t),Rt(t)];var we=process.cwd(),Tn=3,Mn=1024,qn={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},jn=we.split(O.default.sep)[0],Fn=new RegExp(`^.*:${jn}`),Hn=t=>Fn.test(t);process.title="node (exlo)";var pe=class extends ce{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",b.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")).map(r=>r.esEntryPoint),outdir:O.default.join(we,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&b.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(ke({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=Pe(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await xe.default.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,l)=>{let c=`http://localhost:${a}`;b.PINK(`Lambda endpoint: ${c}`),this.endpoints.lambda=c,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=c),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",c);o({url:c,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)b.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,l=O.default.extname(a),c=l.slice(1),d=O.default.resolve(a.replace(l,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:c,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??Mn,timeout:o.timeout??this.runtimeConfig.timeout??Tn,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:O.default.basename(a),...this.runtimeConfig.environment,...o.environment,...qn},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);b.RED(`'${e}' is not mounted yet.
|
|
13
13
|
Please invoke it after the initial build is completed.`)},invokeSub:[],invokeSuccessSub:[],invokeErrorSub:[],setEnv:(g,y)=>{this.setEnv(e,g,y)},shutdown:async()=>{let g=this.getHandlerByName(`/@invoke/${e}`);g&&await g.shutdown()}};if(p.onError=V(o.onError),p.onError?.kind=="lambda"&&(b.YELLOW("Dead-Letter queue could only be a SNS or SQS service"),delete p.onError),o.destinations&&typeof o.destinations=="object"&&(p.onFailure=V(o.destinations.onFailure),p.onSuccess=V(o.destinations.onSuccess)),p.onInvoke=g=>{p.invokeSub.push(g)},p.onInvokeSuccess=g=>{p.invokeSuccessSub.push(g)},p.onInvokeError=g=>{p.invokeErrorSub.push(g)},process.env.NODE_ENV&&(p.environment.NODE_ENV=process.env.NODE_ENV),s&&(p.environment.AWS_REGION=s,p.environment.AWS_DEFAULT_REGION=s),p.environment.AWS_LAMBDA_FUNCTION_MEMORY_SIZE=p.memorySize,p.url=Le(o),o.triggers?.length){let{sqs:g,ddb:y}=Te({triggers:o.triggers});p.sqs=g,p.ddb=y}return p}#r(){let e=this.aws.functions;return Object.keys(e).reduce((s,i)=>{let o=this.#n(i);return s.push(o),s},[])}#i(e){let n=Object.keys(e).filter(r=>!r.endsWith(".map")&&e[r].entryPoint).map(r=>{let i=e[r].entryPoint,o="";Hn(i)&&(i=i.split(":").slice(1).join(":")),O.default.isAbsolute(i)||(i=O.default.resolve(i));let a=i.lastIndexOf(".");return a!=-1&&(o=O.default.extname(i),i=i.slice(0,a)),{esOutputPath:O.default.join(we,r),entryPoint:i,ext:o}});for(let r of this.#e){let s=n.find(i=>i?.entryPoint==r.esEntryPoint);s&&(r.esOutputPath=s.esOutputPath,r.entryPoint=`${s.entryPoint}${s.ext}`)}}#s(){let{environment:e,memorySize:n,timeout:r}=this.aws;this.runtimeConfig.memorySize=n,this.runtimeConfig.timeout=r,this.runtimeConfig.environment=e?{...e}:{};let s=Object.keys(process.env).filter(i=>i.startsWith("AWS_"));for(let i of s)this.runtimeConfig.environment[i]=process.env[i];"FORCE_COLOR"in this.runtimeConfig.environment||process.env.FORCE_COLOR?.toLowerCase()==="false"||process.env.FORCE_COLOR?.toLowerCase()==="no"||process.env.FORCE_COLOR==="0"||("COLORTERM"in process.env||process.env.TERM?.includes("256"))&&(this.runtimeConfig.environment.FORCE_COLOR="true")}setEnv(e,n,r){let s=this.#e.findIndex(i=>i.name==e);if(s>-1){this.#e[s].environment[n]=r;let i=this.aws.getFunction(e);i&&(i.environment||(i.environment={}),i.environment[n]=r)}else b.RED(`Can not set env variable '${n}' on '${e}'`)}addLambda(e,n){if(!n.triggers)n.triggers=[];else if(!Array.isArray(n.triggers))throw new Error("Lambda 'triggers' must be an array when defined.");this.#s(),this.aws.functions[e]=n;let r=this.#n(e);this.#e.push(r)}getLambdaByName(e){return this.#e.find(n=>n.name==e)}buildDefineConfigParam(){let e=this;return{stop:async r=>{await this.kill(r)},lambdas:this.#e,addLambda:(r,s)=>{this.addLambda(r,s)},esbuild:xe.default,getServices(){return{s3:e.aws.services.s3,sqs:e.aws.services.sqs,sns:e.aws.services.sns,dynamodb:e.aws.services.dynamodb}},setService(r,s){switch(r){case"s3":e.aws.services.s3=s;break;case"sns":e.aws.services.sns=s;break;case"sqs":e.aws.services.sqs=s;break;case"dynamodb":e.aws.services.dynamodb=s;break;default:break}},setEndpoint:(r,s,i)=>{if(this.endpoints[r]=s,typeof i=="string"){this.aws.environment[i]=s;for(let o of this.#e)this.setEnv(o.name,i,s)}},getEndpoint:r=>this.endpoints[r],getAwsProviderDefaults:()=>({accountId:e.aws.accountId,region:e.aws.region,runtime:e.aws.runtime,memorySize:e.aws.memorySize,timeout:e.aws.timeout,environment:{...e.aws.environment}}),setAwsProviderDefaults:({accountId:r,environment:s,memorySize:i,region:o,runtime:a,timeout:l})=>{r&&(e.aws.accountId=r),s&&(e.aws.environment=s),i&&(e.aws.memorySize=i),o&&(e.aws.region=o),a&&(e.aws.runtime=a),l&&(e.aws.timeout=l)},log:b}}async resolveConfig(){let e=await bt(this.config);if(e?.exportedFunc){let n,{exportedFunc:r,configObjectName:s,configPath:i}=e;if(typeof r[s]=="function")n=r[s];else if(typeof r=="function")n=r;else if(typeof r.default=="function")n=r.default;else throw new Error(`Can not read exlo config at: ${i}`);return n}}onBeforeApplyConfigCallbacks=[];onBeforeApplyConfig(e){this.onBeforeApplyConfigCallbacks.push(e)}async#c(e){for(let n of this.onBeforeApplyConfigCallbacks)await n(e)}async#o(){let e=this.buildDefineConfigParam(),n=Lt(this).map(a=>(a.callback=a.callback.bind(e),a)),r=await this.resolveConfig(),s={};r&&(await this.#c(r),s=await r(e),Array.isArray(s.onKill)&&this.onKill.push(...s.onKill),s.build&&(typeof s.build.shimRequire=="boolean"&&(this.shimRequire=s.build.shimRequire),typeof s.build.optimizeBuild=="boolean"&&(this.optimizeBuild=s.build.optimizeBuild)),typeof s.buildCallback=="function"&&(this.customBuildCallback=s.buildCallback),s.server&&typeof s.server=="object"&&(Array.isArray(s.server.request)&&n.unshift(...s.server.request),typeof s.server.port=="number"&&!this.port&&(this.port=s.server.port),typeof s.server.onReady=="function"&&(this.onReady=s.server.onReady),typeof s.server.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=s.server.setEndpointEnvVar))),this.customOfflineRequests=n;let i=s?.build?.esbuild;if(!i)return;let o=Oe(i);Object.keys(o).length&&(this.customEsBuildConfig?this.customEsBuildConfig={...this.customEsBuildConfig,...o}:this.customEsBuildConfig=o)}#a=()=>{let e=this.options.port;isNaN(e)||(this.port=e)};async kill(e){this.buildContext.dispose&&await this.buildContext.dispose();for(let n of Nt.EventSourceMapping.SOURCES)try{await n.disable()}catch(r){console.error(r)}for(let n of this.handlers)n.clear?.();this.stop(e);for(let n of this.onKill)try{await n()}catch(r){console.error(r)}}};async function _n(t){let e=Dt(t);return await e.exlo.start(),await e.waitServer,{port:e.listeningPort,url:e.listeningUrl,endpoints:e.exlo.endpoints,async kill(){await e.exlo.kill()},[Symbol.asyncDispose]:async()=>{await e.exlo.kill()}}}var Ee=class{accountId="123456789012";region="us-east-1";timeout=3;memorySize=1024;environment={};services={};functions={};runtime=`node${process.versions.node.split(".")[0]}.x`;getFunction(e){return this.functions[e]}};function Dt(t){let e=new Ee,n={};t&&(t.port&&(n.port=t.port),typeof t.debug=="boolean"&&(n.debug=t.debug),t.build&&(typeof t.build.shimRequire=="boolean"&&(n.shimRequire=t.build.shimRequire),typeof t.build.optimizeBuild=="boolean"&&(n.optimizeBuild=t.build.optimizeBuild),t.build.esbuild&&(n.customEsBuildConfig=t.build.esbuild)),t.config&&(n.config=t.config),t.functions&&(e.functions=t.functions),t.defaults&&(t.defaults.environment&&(e.environment=t.defaults.environment),t.defaults.timeout&&(e.timeout=t.defaults.timeout),t.defaults.memorySize&&(e.memorySize=t.defaults.memorySize),t.defaults.runtime&&(e.runtime=t.defaults.runtime),t.defaults.accountId&&(e.accountId=t.defaults.accountId),t.defaults.region&&(e.region=t.defaults.region)));let r=new pe({aws:e},n);typeof t?.onKill=="function"&&r.onKill.push(t.onKill);let s;r.onceServerReady.push(o=>{i.listeningPort=o.port,i.listeningUrl=o.url,s()});let i={listeningPort:0,listeningUrl:"",exlo:r,waitServer:new Promise(o=>{s=o})};return i}0&&(module.exports={createAppRunner,exloVersion,run});
|
package/dist/standalone.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var fe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});import O from"node:path";import ot from"esbuild";import{EventSourceMapping as wn}from"exlo/internal/esm";import he from"node:path";import{createRequire as ct}from"node:module";var F=fe
|
|
2
|
-
`,ge=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let l of s())l.writable&&l.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(l){console.log(l)}o=!0}),n&&(i.initialOptions.external.push(...ye),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=lt(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var be=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var Se=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),e};var ve=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var dt=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},xe=t=>{let e={},n=dt(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var we=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let l=n.split(":");l.length&&(e.name=l[l.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var C=["lambda","sns","sqs"],Ee=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=we(o);a&&r.push(a)}continue;case"dynamodb":{let a=xe(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},U=t=>{if(!(!t||t.type&&!C.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if(C.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,C.includes(n)&&(e.kind=n)}else if(C.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};import{randomUUID as Yt}from"node:crypto";import Xt from"node:http";import Zt from"node:inspector";import{networkInterfaces as Ve}from"node:os";import{randomUUID as xt}from"node:crypto";var W=!1,pt=t=>{W=t},mt=()=>W,q=(t,e)=>{W&&console.log(`\x1B[${t}m${e}\x1B[0m`)},ut=t=>console.log(`\x1B[31m${t}\x1B[0m`),ft=t=>q("32",t),ht=t=>q("33",t),yt=t=>q("36",t),gt=t=>q("90",t),bt=t=>q("94",t),St=t=>q("95",t),vt=t=>W?console.log(t):void 0,b={GREEN:ft,YELLOW:ht,CYAN:yt,BR_BLUE:bt,RED:ut,GREY:gt,PINK:St,setDebug:pt,getDebug:mt,info:vt};var Re="application/vnd.awslambda.http-integration-response",A=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==Re&&(!this._ct||this._ct==Re),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var Ie="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",Ae="<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>";var wt=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],Et=JSON.stringify({Message:null}),z=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},ke=(t,e)=>{if(!wt.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(Et),!0},L=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},V=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},B=t=>t instanceof A,Pe=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},j=t=>{let e=xt();return t.setHeader("x-amzn-RequestId",e),e},J=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Q=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),K=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),G=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},Oe=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var rr=new Error(Ae);var Le=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(Le).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];i[d]=h,m=="x-api-key"&&(s=h),c=c+2}let o={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[c]=i[c];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];a[d]?a[d].push(h):a[d]=[h],c=c+2}let l={};for(let c of Object.keys(a).sort((d,m)=>d.localeCompare(m)))l[c]=a[c];return{headers:o,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(c=>c.toLowerCase()),l=o.toLowerCase();a?r[l]?r[l].push(...a):r[l]=a:r[l]||(r[l]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};import{EventSourceMapping as Lt}from"exlo/internal/esm";import{EventSourceMapping as Rt}from"exlo/internal/esm";var Y=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,r=await this.handlers.find(s=>s.name==this.lambdaName).invoke({Records:this.#e});await this.onInvokeFinished(e,r)}};var De=10,Te=0,It=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),At=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),Ne=async(t,e,n)=>{for(let r of qe(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},kt=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},Pt=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:l}=t,c={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:kt(a)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},Ot=(t,e)=>t.map(n=>Pt(n,e)),X=class extends Rt{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Me(n,r)),await Ne(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new Y(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#c(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await At(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await It(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=Ot(s,this.config.EventSourceArn),o=await this.#l(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#c(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(n){let r=n.map(a=>{let l={...a};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(r);await Ne(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(l=>l.messageId==a.messageId));return o}};var je=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let l;if(Array.isArray(o.filterPatterns)){l=[];for(let d of o.filterPatterns)l.push({Pattern:JSON.stringify(d)});l.length||(l=void 0)}let c=new X({BatchSize:typeof o.batchSize=="number"?o.batchSize:De,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:l?{Filters:l}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Te},t,s.sqs);if(Lt.SOURCES.push(c),c.config.Enabled)try{await c.init()}catch(d){b.RED(`Failed to start EventSourceMapping ${c.config.EventSourceArn}
|
|
3
|
-
Please verify provided SQS Client validity.`),console.error(d)}}},Nt=/(-|\w+)/g,Dt=t=>t.length<81&&t.replace(Nt,"")=="",Me=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!Dt(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},qe=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};import{randomUUID as Ft}from"node:crypto";import Tt from"node:http";var Mt=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},Fe=(t,e)=>{let n=Mt(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Tt.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},He=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},qt=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=He({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(l){console.log(l)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},jt=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},_e=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return qt({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return He({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return jt({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},le=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Fe(e,t);if(!o)return;o.end(_e({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},$e=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Fe(e,t);if(!o)return;o.end(_e({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var Ht=1080*1e3,_t=new Set(["async","ddb","kinesis","s3","sns","sqs"]),Ce=t=>typeof t?.kind=="string"?_t.has(t.kind)||t.async:!1,H=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:l,esOutputPath:c,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:S,onSuccess:u,onFailure:v,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=l,this.esOutputPath=c,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=S,this.onSuccess=u,this.onFailure=v,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),Ce(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&le({...i,destination:this.onError}),this.onFailure&&le({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&Ce(n)&&$e({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=Ft();this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let l=await a(e,n);typeof l!="function"&&(e=l)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(l,c)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.name}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),l(m)}catch(m){clearTimeout(d),c(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},Ht)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;b.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),b.GREY(this.entryPoint);let l="";return typeof r?.kind=="string"&&(l=` (${r.kind.toUpperCase()})`),b.YELLOW(`\u03BB payload${l}:`),b.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}};var Z=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};import{EventEmitter as $t}from"node:events";import Ct from"node:path";import{Worker as Ut}from"node:worker_threads";var Wt=Ct.resolve(M("exlo"),"./dist/lib/runtime/runners/node/index.js"),ee=class extends $t{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((l,c)=>{this.once("loaded",d=>{d?l(void 0):c()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",l=>{let{channel:c,data:d,awsRequestId:m,type:h,encoding:p}=l;c=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(b.BR_BLUE("Solution:"),console.log(d.solution))):c=="fail"?(this.emit(m,c,d,h,p),this.unmount()):this.emit(m,c,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:l,info:c,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:l,clientContext:d},awsRequestId:h});let y=m??new A(c);function f(S,u,v,w){switch(S){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":v=="write"?y.write(u,w):v=="ct"?y.setHeader("Content-Type",u):v=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof A?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={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:b.getDebug()}};this._worker=new Ut(Wt,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};import{execSync as zt,spawn as Vt}from"node:child_process";import{watch as Bt}from"node:fs";import{access as Ue}from"node:fs/promises";import _ from"node:path";var Jt=process.cwd();function We(t){let e="";try{e=zt(t,{encoding:"utf-8"})}catch{}return e}var te=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=_.resolve(M("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=_.resolve(i);this.handlerDir=_.dirname(c),this.handlerPath=_.basename(c,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(Jt,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=c.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await Ue(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),S="",u=w=>{let E=null,R=w.toString();try{let P=R.includes(t.WATCH);if(P&&this.setWatchFiles(R),R.startsWith(t.DELIMITER)&&R.includes(t.DELIMITEREND)){let I=R.split(t.DELIMITER),D=I[I.length-1].split(t.DELIMITEREND)[0];if(I.length>1){let T;P?T=I[0].split(t.WATCHEND)[1]:T=I.slice(0,-1).join(`
|
|
4
|
-
`),T.trim()&&console.log(T)}D&&(E=JSON.parse(D)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",
|
|
1
|
+
var fe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});import O from"node:path";import ot from"esbuild";import{EventSourceMapping as wn}from"exlo/internal/esm";import he from"node:path";import{createRequire as ct}from"node:module";var F=fe,C={};function M(t){if(C[t])return C[t];if(typeof F=="function"&&typeof F.resolve=="function"){let n=he.resolve(F.resolve(t),"../../");return C[t]=n,n}F=ct(new URL(".",import.meta.url));let e=he.resolve(F.resolve(t),"../../");return C[t]=e,e}var ye=["aws-sdk","@aws-sdk/*","@angular/core","@angular/platform-browser","@aws-sdk/*","@elastic/elasticsearch","@hapi/joi","@opensearch-project/opensearch","@smithy/*","axios","axios-retry","axios-cache-interceptor","aws-serverless-express","aws-sdk","body-parser","classnames","clsx","cookie-parser","cors","core-js","date-fns","dayjs","express","helmet","joi","koa","leaflet","lodash","mysql","mysql2","mongodb","mongoose","moment","http-proxy","http-proxy-middleware","react","react/*","react-dom","react-dom/*","react-hook-form","react-infinite-scroll-component","react-modal","react-rangeslider","react-responsive","react-select","react-scroll","react-slick","react-lazy-load","react-lazyload","react-redux","react-router","react-router-dom","redux","redux-persist","regenerator-runtime","serve-static","express-session","exlo/*","serverless-http","sequelize","svelte","svelte/*","typeorm","pg","pg-hstore","prop-types","underscore","uuid","vue","xmlbuilder","yup","zod","sharp"];var lt=t=>`import { createRequire as __crE_ } from "${t}module";import { fileURLToPath as __futP_ } from "${t}url";import { dirname as __dN_ } from "${t}path";global.__filename = __futP_(import.meta.url);global.__dirname = __dN_(__filename);global.require = __crE_(__filename);
|
|
2
|
+
`,ge=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let l of s())l.writable&&l.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(l){console.log(l)}o=!0}),n&&(i.initialOptions.external.push(...ye),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=lt(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var be=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var Se=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),e};var ve=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var dt=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},xe=t=>{let e={},n=dt(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var we=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let l=n.split(":");l.length&&(e.name=l[l.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var $=["lambda","sns","sqs"],Ee=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=we(o);a&&r.push(a)}continue;case"dynamodb":{let a=xe(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},U=t=>{if(!(!t||t.type&&!$.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if($.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,$.includes(n)&&(e.kind=n)}else if($.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};import{randomUUID as Yt}from"node:crypto";import Xt from"node:http";import Zt from"node:inspector";import{networkInterfaces as Ve}from"node:os";import{randomUUID as xt}from"node:crypto";var W=!1,pt=t=>{W=t},mt=()=>W,q=(t,e)=>{W&&console.log(`\x1B[${t}m${e}\x1B[0m`)},ut=t=>console.log(`\x1B[31m${t}\x1B[0m`),ft=t=>q("32",t),ht=t=>q("33",t),yt=t=>q("36",t),gt=t=>q("90",t),bt=t=>q("94",t),St=t=>q("95",t),vt=t=>W?console.log(t):void 0,b={GREEN:ft,YELLOW:ht,CYAN:yt,BR_BLUE:bt,RED:ut,GREY:gt,PINK:St,setDebug:pt,getDebug:mt,info:vt};var Re="application/vnd.awslambda.http-integration-response",A=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==Re&&(!this._ct||this._ct==Re),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var Ie="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",Ae="<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>";var wt=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],Et=JSON.stringify({Message:null}),z=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},ke=(t,e)=>{if(!wt.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(Et),!0},L=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},V=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},B=t=>t instanceof A,Pe=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},j=t=>{let e=xt();return t.setHeader("x-amzn-RequestId",e),e},J=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Q=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),K=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),G=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},Oe=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var rr=new Error(Ae);var Le=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(Le).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];i[d]=h,m=="x-api-key"&&(s=h),c=c+2}let o={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[c]=i[c];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];a[d]?a[d].push(h):a[d]=[h],c=c+2}let l={};for(let c of Object.keys(a).sort((d,m)=>d.localeCompare(m)))l[c]=a[c];return{headers:o,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(c=>c.toLowerCase()),l=o.toLowerCase();a?r[l]?r[l].push(...a):r[l]=a:r[l]||(r[l]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};import{EventSourceMapping as Lt}from"exlo/internal/esm";import{EventSourceMapping as Rt}from"exlo/internal/esm";var Y=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,r=await this.handlers.find(s=>s.name==this.lambdaName).invoke({Records:this.#e});await this.onInvokeFinished(e,r)}};var De=10,Te=0,It=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),At=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),Ne=async(t,e,n)=>{for(let r of qe(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},kt=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},Pt=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:l}=t,c={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:kt(a)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},Ot=(t,e)=>t.map(n=>Pt(n,e)),X=class extends Rt{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Me(n,r)),await Ne(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new Y(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#c(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await At(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await It(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=Ot(s,this.config.EventSourceArn),o=await this.#l(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#c(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(n){let r=n.map(a=>{let l={...a};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(r);await Ne(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(l=>l.messageId==a.messageId));return o}};var je=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let l;if(Array.isArray(o.filterPatterns)){l=[];for(let d of o.filterPatterns)l.push({Pattern:JSON.stringify(d)});l.length||(l=void 0)}let c=new X({BatchSize:typeof o.batchSize=="number"?o.batchSize:De,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:l?{Filters:l}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Te},t,s.sqs);if(Lt.SOURCES.push(c),c.config.Enabled)try{await c.init()}catch(d){b.RED(`Failed to start EventSourceMapping ${c.config.EventSourceArn}
|
|
3
|
+
Please verify provided SQS Client validity.`),console.error(d)}}},Nt=/(-|\w+)/g,Dt=t=>t.length<81&&t.replace(Nt,"")=="",Me=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!Dt(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},qe=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};import{randomUUID as Ft}from"node:crypto";import Tt from"node:http";var Mt=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},Fe=(t,e)=>{let n=Mt(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Tt.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},He=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},qt=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=He({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(l){console.log(l)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},jt=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},_e=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return qt({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return He({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return jt({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},le=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Fe(e,t);if(!o)return;o.end(_e({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},Ce=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Fe(e,t);if(!o)return;o.end(_e({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var Ht=1080*1e3,_t=new Set(["async","ddb","kinesis","s3","sns","sqs"]),$e=t=>typeof t?.kind=="string"?_t.has(t.kind)||t.async:!1,H=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:l,esOutputPath:c,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:v,onSuccess:u,onFailure:S,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=l,this.esOutputPath=c,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=v,this.onSuccess=u,this.onFailure=S,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),$e(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&le({...i,destination:this.onError}),this.onFailure&&le({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&$e(n)&&Ce({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=Ft();this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let l=await a(e,n);typeof l!="function"&&(e=l)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(l,c)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.name}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),l(m)}catch(m){clearTimeout(d),c(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},Ht)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;b.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),b.GREY(this.entryPoint);let l="";return typeof r?.kind=="string"&&(l=` (${r.kind.toUpperCase()})`),b.YELLOW(`\u03BB payload${l}:`),b.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}};var Z=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};import{EventEmitter as Ct}from"node:events";import $t from"node:path";import{Worker as Ut}from"node:worker_threads";var Wt=$t.resolve(M("exlo"),"./dist/lib/runtime/runners/node/index.js"),ee=class extends Ct{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((l,c)=>{this.once("loaded",d=>{d?l(void 0):c()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",l=>{let{channel:c,data:d,awsRequestId:m,type:h,encoding:p}=l;c=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(b.BR_BLUE("Solution:"),console.log(d.solution))):c=="fail"?(this.emit(m,c,d,h,p),this.unmount()):this.emit(m,c,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:l,info:c,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:l,clientContext:d},awsRequestId:h});let y=m??new A(c);function f(v,u,S,w){switch(v){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":S=="write"?y.write(u,w):S=="ct"?y.setHeader("Content-Type",u):S=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof A?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={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:b.getDebug()}};this._worker=new Ut(Wt,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};import{execSync as zt,spawn as Vt}from"node:child_process";import{watch as Bt}from"node:fs";import{access as Ue}from"node:fs/promises";import _ from"node:path";var Jt=process.cwd();function We(t){let e="";try{e=zt(t,{encoding:"utf-8"})}catch{}return e}var te=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=_.resolve(M("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=_.resolve(i);this.handlerDir=_.dirname(c),this.handlerPath=_.basename(c,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(Jt,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=c.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await Ue(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),v="",u=w=>{let E=null,R=w.toString();try{let P=R.includes(t.WATCH);if(P&&this.setWatchFiles(R),R.startsWith(t.DELIMITER)&&R.includes(t.DELIMITEREND)){let I=R.split(t.DELIMITER),D=I[I.length-1].split(t.DELIMITEREND)[0];if(I.length>1){let T;P?T=I[0].split(t.WATCHEND)[1]:T=I.slice(0,-1).join(`
|
|
4
|
+
`),T.trim()&&console.log(T)}D&&(E=JSON.parse(D)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),g(E)}else if(R.startsWith(t.DELIMITER))v=R.slice(t.DELIMITER.length);else if(R.includes(t.DELIMITEREND)){let I=R.slice(0,R.indexOf(t.DELIMITEREND)),D=JSON.parse(`${v}${I}`);this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),g(D)}else if(v)v+=R;else if(!v&&R.trim()){let I;if(P){let D=R.split(`
|
|
5
5
|
`),T=D.findIndex(at=>at.startsWith(t.WATCH));I=D.slice(0,T).join(`
|
|
6
|
-
`)}else I=R;I.trim()&&console.log(I)}}catch(P){console.log("err",P),y(P)}};this.python.stdout.on("data",u);let
|
|
7
|
-
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,_.sep)}.py`);for(let o of i)try{await Ue(o),this.watchers.push(Bt(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(We(`${e} --version`))return e;let r=We("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&b.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=Vt(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,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};onComplete=e=>{}};import{spawn as Qt}from"node:child_process";import{watch as Kt}from"node:fs";import{access as ze}from"node:fs/promises";import ne from"node:path";var re=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=ne.resolve(M("exlo"),"./src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=ne.resolve(i);this.handlerDir=ne.dirname(c),this.handlerPath=ne.basename(c,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await ze(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),S
|
|
8
|
-
`);I.trim()&&console.log(I)}P&&(w=JSON.parse(P)),this.ruby.stdout.removeListener("data",
|
|
9
|
-
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await ze(i),this.watchers.push(Kt(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=Qt(this.bin,[t.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};onComplete=e=>{}};var Gt=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=Gt.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var se;Ve&&(se=Object.values(Ve()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var en=Zt?.url()!=null;en&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),H.ENABLE_TIMEOUT=!1);var tn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},ie=class extends k{#e;runtimeConfig={};#t;sco=[];aws;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),b.setDebug(n.debug),this.aws=e.aws,this.sco=[],this.#e=Xt.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=Yt();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(b.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),se&&(k.ip=se),typeof n=="function"&&await n(r,se);try{await this.onReady?.(r,k.ip),await je(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",l=>{console.error(l.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end(Ie)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(tn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){let r=n.runtime.charAt(0);n.runner=r=="n"?new ee(n):r=="p"?new te(n,this.fakeRebuildEmitter):r=="r"?new re(n,this.fakeRebuildEmitter):new Z(n.runtime);let s=new H(n);this.addHandler(s)}}};import{rm as sn}from"node:fs/promises";import N from"node:path";import{pathToFileURL as on}from"node:url";import an from"esbuild";var rn="0.0.11";function Be(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[]};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[S,u]of Object.entries(t.functions))c(S,u);t.services&&(t.services.sqs&&l("sqs",t.services.sqs),t.services.sns&&l("sns",t.services.sns),t.services.dynamodb&&l("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,v)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,v)}catch(E){d.RED(w.name),console.error(E)}},y.buildCallback=async(u,v)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,v)}catch(E){d.RED(w.name),console.error(E),v||process.exit(1)}};let S=t.plugins.reduce((u,v)=>(v.server?.request?.length&&u.push(...v.server.request),u),[]);S?.length&&(y.server.request=S.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(v){throw d.RED(u.name),v}}return y}return n.plugins=t.plugins??[],n}var cn=["js","mjs","cjs","ts","cts","mts"],ln=async t=>{let e=N.dirname(N.toNamespacedPath(t)),n=N.basename(t,N.extname(t)),r=N.join(e,`__${n}.mjs`);await an.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import(on(r).href)}catch(s){throw s}finally{await sn(r)}},Je=async t=>{if(t){if(typeof t=="string"){let e=N.posix.parse(t),n=N.posix.join(e.dir,e.name),r=e.ext.slice(1),s=N.posix.resolve(n);cn.includes(r)&&(s+=`.${r}`);let i;try{i=await ln(s)}catch(o){b.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:Be(t)}}};var dn=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},de=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(dn),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};import{randomUUID as Qe}from"node:crypto";var oe=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:l,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:c,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:l}=e,c=t.getPathParameters(n,r),d,m=n.methods.find(v=>v==a)??"ANY",h={},p="";for(let v of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(v);p+=`&${w.map(E=>encodeURI(`${v}=${E}`)).join("&")}`,h[v]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",S=l.host?.startsWith("localhost")?f:l.host?l.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:S,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(c).length&&(u.pathParameters=c),l.cookie&&(u.cookies=l.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:l}=e,c={};n.proxy=="httpApi"&&(c.version="1.0");let d=n.paths[0];c.resource=d,c.path=r.pathname,c.httpMethod=l;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);c.headers=m,c.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);c.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);c.multiValueQueryStringParameters=Object.keys(f).length?f:null;let S=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:S.toISOString(),requestTimeEpoch:S.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),c.requestContext=u;let v=t.getPathParameters(n,r);return c.pathParameters=Object.keys(v).length?v:null,c.stageVariables=null,c.body=a??null,c.isBase64Encoded=a?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from(Qe()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
|
|
6
|
+
`)}else I=R;I.trim()&&console.log(I)}}catch(P){console.log("err",P),y(P)}};this.python.stdout.on("data",u);let S=w=>{let E=w.toString();if(E.includes(t.ERR_RESPONSE))try{E=JSON.parse(E.split(t.ERR_RESPONSE)[1]),E.requestId=p}catch{}finally{this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",S),y(E)}else console.log(E)};this.python.stderr.on("data",S),this.python.stdin.write(`${f}
|
|
7
|
+
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,_.sep)}.py`);for(let o of i)try{await Ue(o),this.watchers.push(Bt(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(We(`${e} --version`))return e;let r=We("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&b.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=Vt(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,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};onComplete=e=>{}};import{spawn as Qt}from"node:child_process";import{watch as Kt}from"node:fs";import{access as ze}from"node:fs/promises";import ne from"node:path";var re=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=ne.resolve(M("exlo"),"./src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=ne.resolve(i);this.handlerDir=ne.dirname(c),this.handlerPath=ne.basename(c,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await ze(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),v=S=>{let w=null,E=S.toString();try{if(E.includes(t.WATCH))this.setWatchFiles(E);else if(E.includes(t.DELIMITER)){let R=E.split(t.DELIMITER),P=R[R.length-1];if(R.length>1){let I=R.slice(0,-1).join(`
|
|
8
|
+
`);I.trim()&&console.log(I)}P&&(w=JSON.parse(P)),this.ruby.stdout.removeListener("data",v),this.ruby.stderr.removeListener("data",u),g(w)}else E.trim()&&console.log(E)}catch(R){y(R)}};this.ruby.stdout.on("data",v);let u=S=>{let w=S.toString();if(w.includes(t.ERR_RESPONSE))try{w=JSON.parse(w.split(t.ERR_RESPONSE)[1]),w.requestId=p}catch{}finally{this.ruby.stdout.removeListener("data",v),this.ruby.stderr.removeListener("data",u),y(w)}else console.log(w)};this.ruby.stderr.on("data",u),this.ruby.stdin.write(`${f}
|
|
9
|
+
`)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await ze(i),this.watchers.push(Kt(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=Qt(this.bin,[t.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};onComplete=e=>{}};var Gt=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=Gt.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var se;Ve&&(se=Object.values(Ve()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var en=Zt?.url()!=null;en&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),H.ENABLE_TIMEOUT=!1);var tn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},ie=class extends k{#e;runtimeConfig={};#t;sco=[];aws;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),b.setDebug(n.debug),this.aws=e.aws,this.sco=[],this.#e=Xt.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=Yt();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(b.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),se&&(k.ip=se),typeof n=="function"&&await n(r,se);try{await this.onReady?.(r,k.ip),await je(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",l=>{console.error(l.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end(Ie)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(tn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){let r=n.runtime.charAt(0);n.runner=r=="n"?new ee(n):r=="p"?new te(n,this.fakeRebuildEmitter):r=="r"?new re(n,this.fakeRebuildEmitter):new Z(n.runtime);let s=new H(n);this.addHandler(s)}}};import{rm as sn}from"node:fs/promises";import N from"node:path";import{pathToFileURL as on}from"node:url";import an from"esbuild";var rn="0.0.13";function Be(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[]};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[v,u]of Object.entries(t.functions))c(v,u);t.services&&(t.services.sqs&&l("sqs",t.services.sqs),t.services.sns&&l("sns",t.services.sns),t.services.dynamodb&&l("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,S)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,S)}catch(E){d.RED(w.name),console.error(E)}},y.buildCallback=async(u,S)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,S)}catch(E){d.RED(w.name),console.error(E),S||process.exit(1)}};let v=t.plugins.reduce((u,S)=>(S.server?.request?.length&&u.push(...S.server.request),u),[]);v?.length&&(y.server.request=v.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(S){throw d.RED(u.name),S}}return y}return n.plugins=t.plugins??[],n}var cn=["js","mjs","cjs","ts","cts","mts"],ln=async t=>{let e=N.dirname(N.toNamespacedPath(t)),n=N.basename(t,N.extname(t)),r=N.join(e,`__${n}.mjs`);await an.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import(on(r).href)}catch(s){throw s}finally{await sn(r)}},Je=async t=>{if(t){if(typeof t=="string"){let e=N.posix.parse(t),n=N.posix.join(e.dir,e.name),r=e.ext.slice(1),s=N.posix.resolve(n);cn.includes(r)&&(s+=`.${r}`);let i;try{i=await ln(s)}catch(o){b.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:Be(t)}}};var dn=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},de=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(dn),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};import{randomUUID as Qe}from"node:crypto";var oe=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:l,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:c,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:l}=e,c=t.getPathParameters(n,r),d,m=n.methods.find(S=>S==a)??"ANY",h={},p="";for(let S of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(S);p+=`&${w.map(E=>encodeURI(`${S}=${E}`)).join("&")}`,h[S]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",v=l.host?.startsWith("localhost")?f:l.host?l.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:v,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(c).length&&(u.pathParameters=c),l.cookie&&(u.cookies=l.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:l}=e,c={};n.proxy=="httpApi"&&(c.version="1.0");let d=n.paths[0];c.resource=d,c.path=r.pathname,c.httpMethod=l;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);c.headers=m,c.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);c.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);c.multiValueQueryStringParameters=Object.keys(f).length?f:null;let v=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:v.toISOString(),requestTimeEpoch:v.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),c.requestContext=u;let S=t.getPathParameters(n,r);return c.pathParameters=Object.keys(S).length?S:null,c.stageVariables=null,c.body=a??null,c.isBase64Encoded=a?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from(Qe()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
|
|
10
10
|
Received:`),console.log(e),new Error;r=e.statusCode,e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.entries(e.headers).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c),h=this.#e(d);n.push([m,h])}),e.multiValueHeaders&&typeof e.multiValueHeaders=="object"&&!Array.isArray(e.multiValueHeaders)&&Object.entries(e.multiValueHeaders).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c);if(!Array.isArray(d))throw new Error;d.map(p=>this.#e(p)).forEach(p=>{n.push([m,p])})});let s=e.body;if(e.isBase64Encoded&&s){if(typeof s!="string")throw new Error;let c=Buffer.from(s,"base64").toString();if(Buffer.from(c).toString("base64")!=s)throw b.RED("response body is not properly base64 encoded"),new Error;s=c}n.findIndex(c=>c[0].toLowerCase()=="content-type")==-1&&n.push(["Content-Type",t.contentType.json]);let o=n.findIndex(c=>c[0].toLowerCase()=="content-length");o!=-1&&n.splice(o,1);let a=typeof s;a=="number"||a=="boolean"?s=String(s):s&&a!="string"&&b.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let l=r==204?"0":s?String(Buffer.from(s).byteLength):"0";n.push(["Content-Length",l]),this.res.shouldKeepAlive=!1,this.res.writeHead(r,n),this.res.end(s)};sendV2Response=e=>{this.res.setHeader("Apigw-Requestid",Buffer.from(Qe()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),e?(typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.keys(e.headers).filter(s=>s!=="Apigw-Requestid"&&s!=="Date").forEach(s=>{this.res.setHeader(s,e.headers[s])}),e.statusCode?(this.res.statusCode=e.statusCode,e.cookies?.length&&this.res.setHeader("Set-Cookie",e.cookies)):this.res.statusCode=200):this.res.statusCode=200;let n="";if(!e)return this.res.end();if(typeof e=="object"&&typeof e.body=="string"&&(n=e.body,e.isBase64Encoded)){let r=Buffer.from(n,"base64").toString();if(Buffer.from(r).toString("base64")!=n)throw b.RED("response body is not properly base64 encoded"),new Error;n=r}typeof e=="string"?(this.res.setHeader("Content-Type",t.contentType.json),n=e):typeof e=="object"&&!e.statusCode&&(this.res.setHeader("Content-Type",t.contentType.json),n=JSON.stringify(e)),this.res.end(n)};sendResponse=e=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(e):this.sendV2Response(e)}};var pn=(t,e)=>{let n=e.url.stream?t:void 0;if(n){let r=!1,s=t.write.bind(t),i=t.setHeader.bind(t),o,a,l=m=>{a=a?Buffer.concat([a,m]):m},c=()=>{if(a){let m=Pe(a),h=m.statusCode??200;try{let p=de(m.headers,m.cookies);t.writeHead(h,p)}catch(p){t.writeHead(500,p.headers),t.end?.(x.amzMsgNull),delete p.headers}}else t.writeHead(200)};n.setHeader=(m,h)=>{if(m.toLowerCase()=="content-type"){if(h=="application/vnd.awslambda.http-integration-response")return r=!0,i("Content-Type",x.contentType.json);o=h}return i(m,h)};let d=!1;return n.write=(m,h,p)=>{if(n.headersSent)return s(m,h,p);if(d)try{let g=A.codec.decode(m),y=JSON.parse(g);if(Array.isArray(y))throw new Error("Invalid stream response");return y&&typeof y=="object"?(c(),s(m,h,p)):(t.writeHead(200,{"Content-Type":x.contentType.octet}),t.end())}catch(g){let y=new Error(`When using HttpResponseStream first chunk of .write() must be valid JSON and not be Array. Number and null will respones with 200.
|
|
11
11
|
'${e.name}'`);return y.cause=g.message,console.error(y),G(t)}else if(r)Oe(m)?d=!0:l(m);else{if(o==x.contentType.json)try{let y=A.codec.decode(m),f=JSON.parse(y);if(f===null||typeof f=="number")throw new Error(y)}catch(y){let f=new Error(`When 'Content-Type' is 'application/json' first chunk of .write() must be parsable JSON and not be null or number.
|
|
12
|
-
'${e.name}'`);return f.cause=y.message,console.error(f),G(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},mn=(t,e,n,r)=>{let s=B(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let l=isNaN(i.statusCode),c=l?500:i.statusCode;if(a=!l&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=de(i.headers,i.cookies,r);e.writeHead(c,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(c,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function un(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function Ke(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function fn(t,e){if(!t.allowMethods)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function hn(t,e){if(!fn(t,e)||!Ke(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var Ge=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(ke(n,s))return;let o=new URL(r,x.dummyHost),a=j(n),l=k.parseNameFromUrl(o.pathname),c=t.handlers.find(f=>f.name==l);if(!c?.url)return n.statusCode=404,n.end("Not Found");let d;if(c.url.cors){if(un(i,s)){let S=hn(c.url.cors,i),u={"Content-Type":x.contentType.json};return S&&(u["access-control-allow-origin"]=i.origin,u["access-control-allow-methods"]=c.url.cors.allowMethods.join(","),c.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=c.url.cors.allowHeaders.join(",")),typeof c.url.cors.maxAge=="number"&&c.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${c.url.cors.maxAge}`),c.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}Ke(c.url.cors,i)&&(d={"access-control-allow-origin":i.origin},c.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=c.url.cors.exposeHeaders.join(",")),c.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await L(e,m),p=oe.createApgV2Event({req:e,mockEvent:c.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${c.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=pn(n,c),S=await c.invoke(p,c.url,void 0,f);if(!S)return n.end();mn(S,n,f,d)}catch(f){console.error(f),G(n,d)}}});var Ye=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),l=j(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:S}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(K(o,f,S))}let c=s["x-amz-invocation-type"],d=z(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Q);let m=c=="DryRun"?204:c=="Event"?202:200,h=await L(e),p=V(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(J(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let S=B(f),u=S?f.buffer:f;S?u=A.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){n.writableFinished||(n.setHeader("X-Amz-Function-Error",f.errorType??f.message??""),n.statusCode=200,n.end(JSON.stringify(f)))}}});import{randomUUID as Xe}from"node:crypto";import{setTimeout as gn}from"node:timers/promises";var Ze=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await L(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:l,Timeout:c,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:l,timeout:c,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await gn(100),n.statusCode=201,n.end(r)}}),et=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:tt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:Xe(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),bn=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function tt(t){let e={};for(let[n,r]of Object.entries(t))bn.includes(n)||(e[n]=String(r));return e}var nt=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:tt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:Xe(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),rt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});import{EventStreamCodec as Sn}from"@smithy/eventstream-codec";var vn=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},xn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),pe=new Sn(xn,vn),ae=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(pe.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(pe.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(pe.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var st=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=j(n),a=k.parseNameFromUrl(i.pathname),l=t.handlers.find(p=>p.name==a),c=await L(e),d=V(c);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(J(d.message));let m=z(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Q);let h=new ae(n);if(l){let p=l.url?.stream??{};try{let g=await l.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(K(a,p,g))}}});var it=t=>[Ze(t),nt(t),rt(t),Ye(t),st(t),Ge(t),et(t)];var me=process.cwd(),En=3,Rn=1024,In={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},An=me.split(O.sep)[0],kn=new RegExp(`^.*:${An}`),Pn=t=>kn.test(t);process.title="node (exlo)";var ce=class extends ie{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",b.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")).map(r=>r.esEntryPoint),outdir:O.join(me,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&b.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(ge({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=be(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await ot.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,l)=>{let c=`http://localhost:${a}`;b.PINK(`Lambda endpoint: ${c}`),this.endpoints.lambda=c,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=c),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",c);o({url:c,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)b.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,l=O.extname(a),c=l.slice(1),d=O.resolve(a.replace(l,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:c,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??Rn,timeout:o.timeout??this.runtimeConfig.timeout??En,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:O.basename(a),...this.runtimeConfig.environment,...o.environment,...In},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);b.RED(`'${e}' is not mounted yet.
|
|
12
|
+
'${e.name}'`);return f.cause=y.message,console.error(f),G(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},mn=(t,e,n,r)=>{let s=B(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let l=isNaN(i.statusCode),c=l?500:i.statusCode;if(a=!l&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=de(i.headers,i.cookies,r);e.writeHead(c,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(c,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function un(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function Ke(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function fn(t,e){if(!t.allowMethods?.length)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function hn(t,e){if(!fn(t,e)||!Ke(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var Ge=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(ke(n,s))return;let o=new URL(r,x.dummyHost),a=j(n),l=k.parseNameFromUrl(o.pathname),c=t.handlers.find(f=>f.name==l);if(!c?.url)return n.statusCode=404,n.end("Not Found");let d;if(c.url.cors){if(un(i,s)){let v=hn(c.url.cors,i),u={"Content-Type":x.contentType.json};return v&&(u["access-control-allow-origin"]=i.origin,c.url.cors.allowMethods.find(S=>S=="*")?u["access-control-allow-methods"]=i["access-control-request-method"]:u["access-control-allow-methods"]=c.url.cors.allowMethods.join(","),c.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=c.url.cors.allowHeaders.join(",")),typeof c.url.cors.maxAge=="number"&&c.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${c.url.cors.maxAge}`),c.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}Ke(c.url.cors,i)&&(d={"access-control-allow-origin":i.origin},c.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=c.url.cors.exposeHeaders.join(",")),c.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await L(e,m),p=oe.createApgV2Event({req:e,mockEvent:c.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${c.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=pn(n,c),v=await c.invoke(p,c.url,void 0,f);if(!v)return n.end();mn(v,n,f,d)}catch(f){console.error(f),G(n,d)}}});var Ye=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),l=j(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:v}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(K(o,f,v))}let c=s["x-amz-invocation-type"],d=z(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Q);let m=c=="DryRun"?204:c=="Event"?202:200,h=await L(e),p=V(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(J(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let v=B(f),u=v?f.buffer:f;v?u=A.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){n.writableFinished||(n.setHeader("X-Amz-Function-Error",f.errorType??f.message??""),n.statusCode=200,n.end(JSON.stringify(f)))}}});import{randomUUID as Xe}from"node:crypto";import{setTimeout as gn}from"node:timers/promises";var Ze=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await L(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:l,Timeout:c,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:l,timeout:c,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await gn(100),n.statusCode=201,n.end(r)}}),et=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:tt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:Xe(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),bn=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function tt(t){let e={};for(let[n,r]of Object.entries(t))bn.includes(n)||(e[n]=String(r));return e}var nt=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:tt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:Xe(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),rt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});import{EventStreamCodec as Sn}from"@smithy/eventstream-codec";var vn=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},xn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),pe=new Sn(xn,vn),ae=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(pe.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(pe.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(pe.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var st=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=j(n),a=k.parseNameFromUrl(i.pathname),l=t.handlers.find(p=>p.name==a),c=await L(e),d=V(c);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(J(d.message));let m=z(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Q);let h=new ae(n);if(l){let p=l.url?.stream??{};try{let g=await l.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(K(a,p,g))}}});var it=t=>[Ze(t),nt(t),rt(t),Ye(t),st(t),Ge(t),et(t)];var me=process.cwd(),En=3,Rn=1024,In={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},An=me.split(O.sep)[0],kn=new RegExp(`^.*:${An}`),Pn=t=>kn.test(t);process.title="node (exlo)";var ce=class extends ie{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",b.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")).map(r=>r.esEntryPoint),outdir:O.join(me,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&b.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(ge({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=be(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await ot.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,l)=>{let c=`http://localhost:${a}`;b.PINK(`Lambda endpoint: ${c}`),this.endpoints.lambda=c,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=c),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",c);o({url:c,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)b.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,l=O.extname(a),c=l.slice(1),d=O.resolve(a.replace(l,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:c,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??Rn,timeout:o.timeout??this.runtimeConfig.timeout??En,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:O.basename(a),...this.runtimeConfig.environment,...o.environment,...In},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);b.RED(`'${e}' is not mounted yet.
|
|
13
13
|
Please invoke it after the initial build is completed.`)},invokeSub:[],invokeSuccessSub:[],invokeErrorSub:[],setEnv:(g,y)=>{this.setEnv(e,g,y)},shutdown:async()=>{let g=this.getHandlerByName(`/@invoke/${e}`);g&&await g.shutdown()}};if(p.onError=U(o.onError),p.onError?.kind=="lambda"&&(b.YELLOW("Dead-Letter queue could only be a SNS or SQS service"),delete p.onError),o.destinations&&typeof o.destinations=="object"&&(p.onFailure=U(o.destinations.onFailure),p.onSuccess=U(o.destinations.onSuccess)),p.onInvoke=g=>{p.invokeSub.push(g)},p.onInvokeSuccess=g=>{p.invokeSuccessSub.push(g)},p.onInvokeError=g=>{p.invokeErrorSub.push(g)},process.env.NODE_ENV&&(p.environment.NODE_ENV=process.env.NODE_ENV),s&&(p.environment.AWS_REGION=s,p.environment.AWS_DEFAULT_REGION=s),p.environment.AWS_LAMBDA_FUNCTION_MEMORY_SIZE=p.memorySize,p.url=ve(o),o.triggers?.length){let{sqs:g,ddb:y}=Ee({triggers:o.triggers});p.sqs=g,p.ddb=y}return p}#r(){let e=this.aws.functions;return Object.keys(e).reduce((s,i)=>{let o=this.#n(i);return s.push(o),s},[])}#i(e){let n=Object.keys(e).filter(r=>!r.endsWith(".map")&&e[r].entryPoint).map(r=>{let i=e[r].entryPoint,o="";Pn(i)&&(i=i.split(":").slice(1).join(":")),O.isAbsolute(i)||(i=O.resolve(i));let a=i.lastIndexOf(".");return a!=-1&&(o=O.extname(i),i=i.slice(0,a)),{esOutputPath:O.join(me,r),entryPoint:i,ext:o}});for(let r of this.#e){let s=n.find(i=>i?.entryPoint==r.esEntryPoint);s&&(r.esOutputPath=s.esOutputPath,r.entryPoint=`${s.entryPoint}${s.ext}`)}}#s(){let{environment:e,memorySize:n,timeout:r}=this.aws;this.runtimeConfig.memorySize=n,this.runtimeConfig.timeout=r,this.runtimeConfig.environment=e?{...e}:{};let s=Object.keys(process.env).filter(i=>i.startsWith("AWS_"));for(let i of s)this.runtimeConfig.environment[i]=process.env[i];"FORCE_COLOR"in this.runtimeConfig.environment||process.env.FORCE_COLOR?.toLowerCase()==="false"||process.env.FORCE_COLOR?.toLowerCase()==="no"||process.env.FORCE_COLOR==="0"||("COLORTERM"in process.env||process.env.TERM?.includes("256"))&&(this.runtimeConfig.environment.FORCE_COLOR="true")}setEnv(e,n,r){let s=this.#e.findIndex(i=>i.name==e);if(s>-1){this.#e[s].environment[n]=r;let i=this.aws.getFunction(e);i&&(i.environment||(i.environment={}),i.environment[n]=r)}else b.RED(`Can not set env variable '${n}' on '${e}'`)}addLambda(e,n){if(!n.triggers)n.triggers=[];else if(!Array.isArray(n.triggers))throw new Error("Lambda 'triggers' must be an array when defined.");this.#s(),this.aws.functions[e]=n;let r=this.#n(e);this.#e.push(r)}getLambdaByName(e){return this.#e.find(n=>n.name==e)}buildDefineConfigParam(){let e=this;return{stop:async r=>{await this.kill(r)},lambdas:this.#e,addLambda:(r,s)=>{this.addLambda(r,s)},esbuild:ot,getServices(){return{s3:e.aws.services.s3,sqs:e.aws.services.sqs,sns:e.aws.services.sns,dynamodb:e.aws.services.dynamodb}},setService(r,s){switch(r){case"s3":e.aws.services.s3=s;break;case"sns":e.aws.services.sns=s;break;case"sqs":e.aws.services.sqs=s;break;case"dynamodb":e.aws.services.dynamodb=s;break;default:break}},setEndpoint:(r,s,i)=>{if(this.endpoints[r]=s,typeof i=="string"){this.aws.environment[i]=s;for(let o of this.#e)this.setEnv(o.name,i,s)}},getEndpoint:r=>this.endpoints[r],getAwsProviderDefaults:()=>({accountId:e.aws.accountId,region:e.aws.region,runtime:e.aws.runtime,memorySize:e.aws.memorySize,timeout:e.aws.timeout,environment:{...e.aws.environment}}),setAwsProviderDefaults:({accountId:r,environment:s,memorySize:i,region:o,runtime:a,timeout:l})=>{r&&(e.aws.accountId=r),s&&(e.aws.environment=s),i&&(e.aws.memorySize=i),o&&(e.aws.region=o),a&&(e.aws.runtime=a),l&&(e.aws.timeout=l)},log:b}}async resolveConfig(){let e=await Je(this.config);if(e?.exportedFunc){let n,{exportedFunc:r,configObjectName:s,configPath:i}=e;if(typeof r[s]=="function")n=r[s];else if(typeof r=="function")n=r;else if(typeof r.default=="function")n=r.default;else throw new Error(`Can not read exlo config at: ${i}`);return n}}onBeforeApplyConfigCallbacks=[];onBeforeApplyConfig(e){this.onBeforeApplyConfigCallbacks.push(e)}async#c(e){for(let n of this.onBeforeApplyConfigCallbacks)await n(e)}async#o(){let e=this.buildDefineConfigParam(),n=it(this).map(a=>(a.callback=a.callback.bind(e),a)),r=await this.resolveConfig(),s={};r&&(await this.#c(r),s=await r(e),Array.isArray(s.onKill)&&this.onKill.push(...s.onKill),s.build&&(typeof s.build.shimRequire=="boolean"&&(this.shimRequire=s.build.shimRequire),typeof s.build.optimizeBuild=="boolean"&&(this.optimizeBuild=s.build.optimizeBuild)),typeof s.buildCallback=="function"&&(this.customBuildCallback=s.buildCallback),s.server&&typeof s.server=="object"&&(Array.isArray(s.server.request)&&n.unshift(...s.server.request),typeof s.server.port=="number"&&!this.port&&(this.port=s.server.port),typeof s.server.onReady=="function"&&(this.onReady=s.server.onReady),typeof s.server.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=s.server.setEndpointEnvVar))),this.customOfflineRequests=n;let i=s?.build?.esbuild;if(!i)return;let o=Se(i);Object.keys(o).length&&(this.customEsBuildConfig?this.customEsBuildConfig={...this.customEsBuildConfig,...o}:this.customEsBuildConfig=o)}#a=()=>{let e=this.options.port;isNaN(e)||(this.port=e)};async kill(e){this.buildContext.dispose&&await this.buildContext.dispose();for(let n of wn.SOURCES)try{await n.disable()}catch(r){console.error(r)}for(let n of this.handlers)n.clear?.();this.stop(e);for(let n of this.onKill)try{await n()}catch(r){console.error(r)}}};async function ai(t){let e=On(t);return await e.exlo.start(),await e.waitServer,{port:e.listeningPort,url:e.listeningUrl,endpoints:e.exlo.endpoints,async kill(){await e.exlo.kill()},[Symbol.asyncDispose]:async()=>{await e.exlo.kill()}}}var ue=class{accountId="123456789012";region="us-east-1";timeout=3;memorySize=1024;environment={};services={};functions={};runtime=`node${process.versions.node.split(".")[0]}.x`;getFunction(e){return this.functions[e]}};function On(t){let e=new ue,n={};t&&(t.port&&(n.port=t.port),typeof t.debug=="boolean"&&(n.debug=t.debug),t.build&&(typeof t.build.shimRequire=="boolean"&&(n.shimRequire=t.build.shimRequire),typeof t.build.optimizeBuild=="boolean"&&(n.optimizeBuild=t.build.optimizeBuild),t.build.esbuild&&(n.customEsBuildConfig=t.build.esbuild)),t.config&&(n.config=t.config),t.functions&&(e.functions=t.functions),t.defaults&&(t.defaults.environment&&(e.environment=t.defaults.environment),t.defaults.timeout&&(e.timeout=t.defaults.timeout),t.defaults.memorySize&&(e.memorySize=t.defaults.memorySize),t.defaults.runtime&&(e.runtime=t.defaults.runtime),t.defaults.accountId&&(e.accountId=t.defaults.accountId),t.defaults.region&&(e.region=t.defaults.region)));let r=new ce({aws:e},n);typeof t?.onKill=="function"&&r.onKill.push(t.onKill);let s;r.onceServerReady.push(o=>{i.listeningPort=o.port,i.listeningUrl=o.url,s()});let i={listeningPort:0,listeningUrl:"",exlo:r,waitServer:new Promise(o=>{s=o})};return i}export{On as createAppRunner,rn as exloVersion,ai as run};
|
|
@@ -101,6 +101,14 @@ export type ITriggersDynamoDb = {
|
|
|
101
101
|
};
|
|
102
102
|
export type ITriggers = ITriggersSqs | ITriggersDynamoDb;
|
|
103
103
|
export type LambdaHandlerPath = `${string}.${string}`;
|
|
104
|
+
export interface IFunctionUrlCors {
|
|
105
|
+
allowOrigins: string[];
|
|
106
|
+
allowMethods?: string[];
|
|
107
|
+
allowHeaders?: string[];
|
|
108
|
+
allowCredentials?: boolean;
|
|
109
|
+
exposeHeaders?: string[];
|
|
110
|
+
maxAge?: number;
|
|
111
|
+
}
|
|
104
112
|
export type ILambdaFunction = {
|
|
105
113
|
/**
|
|
106
114
|
* Path to local handler with exported handler name as file extension
|
|
@@ -117,14 +125,7 @@ export type ILambdaFunction = {
|
|
|
117
125
|
*/
|
|
118
126
|
url?: boolean | {
|
|
119
127
|
invokeMode?: "RESPONSE_STREAM" | "BUFFERED";
|
|
120
|
-
cors?:
|
|
121
|
-
allowOrigins: string[];
|
|
122
|
-
allowMethods?: string[];
|
|
123
|
-
allowHeaders?: string[];
|
|
124
|
-
allowCredentials?: boolean;
|
|
125
|
-
exposeHeaders?: string[];
|
|
126
|
-
maxAge?: number;
|
|
127
|
-
};
|
|
128
|
+
cors?: IFunctionUrlCors;
|
|
128
129
|
};
|
|
129
130
|
} & ICommonConfig;
|
|
130
131
|
export interface ServerOptions {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "exlo",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.13",
|
|
4
4
|
"description": "A modular toolkit to emulate cloud services locally using high-quality built-in plugins and custom extensions. Includes support for Lambda, S3, SNS, SQS, Secrets Manager, DynamoDB, REST API Gateway and more.",
|
|
5
5
|
"author": "Inqnuam",
|
|
6
6
|
"license": "MIT",
|