Skip to content

Commit

Permalink
Add support for loading ECMAScript modules (#222)
Browse files Browse the repository at this point in the history
Loading ECMAScript modules is incompatible with the watch mode, though,
as we can't invalidate the import cache.
  • Loading branch information
tdanecker committed Jul 19, 2023
1 parent 618782e commit 058f557
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 21 deletions.
15 changes: 15 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import utils = require('./lib/utils');
.option('-e, --event-path <path>', '(required if --watch is not in use) Event data file name.')
.option('-h, --handler <handler name>',
'(optional) Lambda function handler name. Default is \'handler\'.')
.option('--esm',
'(optional) Load lambda function as ECMAScript module.')
.option('-t, --timeout <timeout seconds>',
'(optional) Seconds until lambda function timeout. Default is 3 seconds.')
.option('-r, --region <aws region>',
Expand Down Expand Up @@ -50,6 +52,7 @@ import utils = require('./lib/utils');
var eventPath = program.eventPath,
lambdaPath = program.lambdaPath,
lambdaHandler = program.handler,
esm = program.esm,
profilePath = program.profilePath,
profileName = program.profile,
region = program.region,
Expand Down Expand Up @@ -129,6 +132,17 @@ import utils = require('./lib/utils');
_close_inspector = function(){inspector.close();}
}
}

if (esm) {
if (utils.get_node_major_version() < 12) {
console.log("Loading ESCMAScript modules not available on NodeJS < 12.0.0.");
process.exit(1);
}
if (program.watch) {
console.log("Watch mode not supported for ECMAScript lambda modules.");
process.exit(1);
}
}
var event = function(){
if(program.watch) return null;
return require(utils.getAbsolutePath(eventPath));
Expand All @@ -140,6 +154,7 @@ import utils = require('./lib/utils');
event: event,
lambdaPath: lambdaPath,
lambdaHandler: lambdaHandler,
esm: esm,
profilePath: profilePath,
profileName: profileName,
region: region,
Expand Down
53 changes: 32 additions & 21 deletions src/lambdalocal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ function _executeSync(opts) {
lambdaFunc = opts.lambdaFunc,
lambdaPath = opts.lambdaPath,
lambdaHandler = opts.lambdaHandler || 'handler',
esm = opts.esm,
profilePath = opts.profilePath,
profileName = opts.profileName || process.env['AWS_PROFILE'] || process.env['AWS_DEFAULT_PROFILE'],
region = opts.region,
Expand Down Expand Up @@ -246,30 +247,40 @@ function _executeSync(opts) {

var ctx = context.generate_context();

try {
// load lambda function
if (!(lambdaFunc)){
// delete this function from the require.cache to ensure every dependency is refreshed
delete require.cache[require.resolve(lambdaPath)];
lambdaFunc = require(lambdaPath);
}

//load event
if (event instanceof Function){
event = event();
}
const executeLambdaFunc = lambdaFunc => {
try {
//load event
if (event instanceof Function){
event = event();
}

//start timeout
context._init_timeout();
//start timeout
context._init_timeout();

// execute lambda function
var result = lambdaFunc[lambdaHandler](event, ctx, ctx.done);
if (result) {
if (result.then) {
result.then(ctx.succeed, ctx.fail);
} else {
ctx.succeed(null);
// execute lambda function
var result = lambdaFunc[lambdaHandler](event, ctx, ctx.done);
if (result) {
if (result.then) {
result.then(ctx.succeed, ctx.fail);
} else {
ctx.succeed(null);
}
}
} catch(err){
ctx.fail(err);
}
}

try {
if (lambdaFunc) {
executeLambdaFunc(lambdaFunc);
} else if (esm) {
// use eval to avoid typescript transpilation of dynamic import ()
eval("import(lambdaPath)").then(executeLambdaFunc, err => ctx.fail(err));
} else {
// delete this function from the require.cache to ensure every dependency is refreshed
delete require.cache[require.resolve(lambdaPath)];
executeLambdaFunc(require(lambdaPath));
}
} catch(err){
ctx.fail(err);
Expand Down
3 changes: 3 additions & 0 deletions test/functs/test-func-esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export async function handler(event, context) {
return {"result": event.key, "context": context}
}
27 changes: 27 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,25 @@ describe("- Testing lambdalocal.js", function () {
});
});
}
if (get_node_major_version() >= 12) {
describe('* Loading ECMAScript module', function () {
it('should load ECMAScript lambda module successfully', function () {
var lambdalocal = require(lambdalocal_path);
lambdalocal.setLogger(winston);
return lambdalocal.execute({
event: require(path.join(__dirname, "./events/test-event.js")),
lambdaPath: path.join(__dirname, "./functs/test-func-esm.mjs"),
lambdaHandler: functionName,
esm: true,
callbackWaitsForEmptyEventLoop: false,
timeoutMs: timeoutMs,
verboseLevel: 1
}).then(function (data) {
assert.equal(data.result, "testvar")
})
})
})
}
});
describe("- Testing cli.js", function () {
var spawnSync = require('child_process').spawnSync;
Expand Down Expand Up @@ -570,6 +589,14 @@ describe("- Testing cli.js", function () {
assert.equal(r.status, 1);
console.log(r.output);
});

it("should fail: esm with unsupported watch mode", function () {
var command = get_shell("node ../build/cli.js -l ./functs/test-func-esm.mjs --esm --watch");
var r = spawnSync(command[0], command[1]);
process_outputs(r);
assert.equal(r.status, 1);
console.log(r.output);
})
});

describe("* Environment test run", function () {
Expand Down

0 comments on commit 058f557

Please sign in to comment.