Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(lambda): support Node.js ESM (.mjs) handlers (#238)
Stephan Mielkece6d69727fb8
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 79c0904b..dbc2986c 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -198,8 +198,34 @@ rl.on("line", async (line) => {patchAwsSdk();try {const fullPath = path.resolve(code_dir, modPath);- const mod = require(fullPath);- handlerFn = mod[handlerName];+ let mod;+ let resolvedPath;+ try {+ resolvedPath = require.resolve(fullPath);+ } catch (resolveErr) {+ if (resolveErr.code === "MODULE_NOT_FOUND") {+ const fs = require("fs");+ const mjsPath = fullPath + ".mjs";+ if (fs.existsSync(mjsPath)) {+ resolvedPath = mjsPath;+ } else {+ throw resolveErr;+ }+ } else {+ throw resolveErr;+ }+ }+ try {+ mod = require(resolvedPath);+ } catch (reqErr) {+ if (reqErr.code === "ERR_REQUIRE_ESM") {+ const { pathToFileURL } = require("url");+ mod = await import(pathToFileURL(resolvedPath).href);+ } else {+ throw reqErr;+ }+ }+ handlerFn = mod[handlerName] || (mod.default && mod.default[handlerName]) || mod.default;if (typeof handlerFn !== "function") {process.stdout.write(JSON.stringify({status: "error",diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 3a452eb8..ddac2a85 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -216,6 +216,7 @@ if _result is not None:_NODE_WRAPPER_SCRIPT = """\const fs = require('fs');const path = require('path');+const { pathToFileURL } = require('url');const codeDir = process.env._LAMBDA_CODE_DIR || '/var/task';const modPath = process.env._LAMBDA_HANDLER_MODULE;@@ -240,10 +241,38 @@ const context = {let input = '';process.stdin.on('data', d => input += d);-process.stdin.on('end', () => {+process.stdin.on('end', async () => {const event = JSON.parse(input);- const mod = require(path.resolve(codeDir, modPath));- const handler = mod[fnName];+ const fullPath = path.resolve(codeDir, modPath);+ let mod;+ let resolvedPath;+ try {+ resolvedPath = require.resolve(fullPath);+ mod = require(resolvedPath);+ } catch (reqErr) {+ if (reqErr.code === 'ERR_REQUIRE_ESM' && resolvedPath) {+ mod = await import(pathToFileURL(resolvedPath).href);+ } else if (reqErr.code === 'MODULE_NOT_FOUND') {+ const mjsPath = fullPath + '.mjs';+ const missingHandlerEntry =+ (reqErr.message && reqErr.message.includes("'" + fullPath + "'")) ||+ (resolvedPath && reqErr.message && reqErr.message.includes("'" + resolvedPath + "'"));+ if (missingHandlerEntry && fs.existsSync(mjsPath)) {+ mod = await import(pathToFileURL(mjsPath).href);+ } else {+ throw reqErr;+ }+ } else {+ throw reqErr;+ }+ }+ const handler = mod[fnName] || (mod.default && mod.default[fnName]) || mod.default;+ if (typeof handler !== 'function') {+ process.stderr.write(+ "Handler '" + fnName + "' in module '" + modPath + "' is undefined or not a function"+ );+ process.exit(1);+ }Promise.resolve(handler(event, context)).then(result => {if (result !== undefined) process.stdout.write(JSON.stringify(result));}).catch(err => {diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex aa9f48ef..b50786f9 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1455,6 +1455,69 @@ def test_apigwv2_nodejs_lambda_proxy(lam, apigw):pass+def test_lambda_nodejs_esm_mjs_handler(lam):+ """Node.js .mjs (ESM) handlers should be loaded via dynamic import() fallback.++ Creates a ZIP with two .mjs files:+ - utils.mjs: exports a helper function using ESM `export` syntax+ - index.mjs: imports utils.mjs via ESM `import` statement and uses it++ This verifies that:+ 1. .mjs files are loaded via import() instead of require()+ 2. ESM import/export syntax works between modules+ 3. The handler's return value is correctly propagated+ """+ fname = f"lam-esm-{_uuid_mod.uuid4().hex[:8]}"++ utils_code = (+ "export function greet(name) {\n"+ " return `Hello, ${name} from ESM!`;\n"+ "}\n"+ "\n"+ "export const VERSION = '1.0.0';\n"+ )++ handler_code = (+ "import { greet, VERSION } from './utils.mjs';\n"+ "\n"+ "export const handler = async (event) => {\n"+ " const name = event.name || 'World';\n"+ " return {\n"+ " statusCode: 200,\n"+ " body: JSON.stringify({\n"+ " message: greet(name),\n"+ " version: VERSION,\n"+ " esm: true,\n"+ " }),\n"+ " };\n"+ "};\n"+ )++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.mjs", handler_code)+ z.writestr("utils.mjs", utils_code)++ lam.create_function(+ FunctionName=fname,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ try:+ resp = lam.invoke(+ FunctionName=fname,+ Payload=json.dumps({"name": "MiniStack"}),+ )+ assert resp["StatusCode"] == 200+ assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"+ payload = json.loads(resp["Payload"].read())+ assert payload["statusCode"] == 200+ body = json.loads(payload["body"])+ assert body["message"] == "Hello, MiniStack from ESM!"+ assert body["version"] == "1.0.0"+ assert body["esm"] is Truedef test_lambda_warm_worker_uses_layer(lam):"""Warm worker should extract layers and make their code available to the handler."""# Create a layer with a Python module@@ -1498,6 +1561,22 @@ def test_lambda_warm_worker_uses_layer(lam):lam.delete_function(FunctionName=fname)+def test_lambda_nodejs_esm_type_module(lam):+ """Node.js ESM via package.json type:module should trigger ERR_REQUIRE_ESM fallback."""+ fname = f"lam-esm-type-{_uuid_mod.uuid4().hex[:8]}"++ handler_code = (+ "export const handler = async (event) => ({\n"+ " statusCode: 200,\n"+ " body: 'type-module-works',\n"+ "});\n"+ )++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.js", handler_code)+ z.writestr("package.json", '{"type": "module"}')+def test_lambda_warm_worker_nodejs_uses_layer(lam):"""Warm worker should extract Node.js layers and make packages available via require()."""# Create a layer with a Node.js module under nodejs/node_modules/@@ -1531,6 +1610,8 @@ def test_lambda_warm_worker_nodejs_uses_layer(lam):Runtime="nodejs20.x",Role=_LAMBDA_ROLE,Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )Code={"ZipFile": func_buf.getvalue()},Layers=[layer_arn],)@@ -1540,6 +1621,8 @@ def test_lambda_warm_worker_nodejs_uses_layer(lam):assert resp["StatusCode"] == 200assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"payload = json.loads(resp["Payload"].read())+ assert payload["statusCode"] == 200+ assert payload["body"] == "type-module-works"assert payload["value"] == "from-node-layer"finally:lam.delete_function(FunctionName=fname)