Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(lambda): symlink layer node_modules for ESM import resolution (#259)

Stephan Mielke644362ec147a
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index dbc2986c..acb33ee0 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -385,6 +385,22 @@ class Worker:
logger.error("Unexpected error resolving layer %s: %s", layer_arn, e)
raise RuntimeError(f"Failed to resolve layer {layer_arn}") from e
+ # Symlink layer node_modules packages into the code directory so that
+ # Node.js ESM import() can resolve them via ancestor-tree lookup.
+ # ESM does not use NODE_PATH, so packages must be physically reachable
+ # from the handler file's directory tree.
+ if layers_dirs and runtime.startswith("nodejs"):
+ code_nm = os.path.join(code_dir, "node_modules")
+ os.makedirs(code_nm, exist_ok=True)
+ for ld in layers_dirs:
+ layer_nm = os.path.join(ld, "nodejs", "node_modules")
+ if os.path.isdir(layer_nm):
+ for pkg in os.listdir(layer_nm):
+ src = os.path.join(layer_nm, pkg)
+ dst = os.path.join(code_nm, pkg)
+ if not os.path.exists(dst):
+ os.symlink(src, dst)
+
handler = self.config.get("Handler", "index.handler")
module_name, handler_name = handler.rsplit(".", 1)
env_vars = self.config.get("Environment", {}).get("Variables", {})
@@ -399,8 +415,9 @@ class Worker:
# is handled via NODE_PATH populated from each layer's nodejs paths below.
if layers_dirs:
spawn_env["_LAMBDA_LAYERS_DIRS"] = os.pathsep.join(layers_dirs)
- # NODE_PATH is needed for Node.js workers, including ESM import() which
- # ignores module.paths. Prepend to any existing NODE_PATH.
+ # NODE_PATH is used by the CJS require() resolver in Node.js workers.
+ # ESM import() does not use NODE_PATH — layer packages are instead
+ # symlinked into code/node_modules/ above for ancestor-tree resolution.
node_paths = []
for ld in layers_dirs:
nm = os.path.join(ld, "nodejs", "node_modules")
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 818a5bd1..766bfec6 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -1674,6 +1674,20 @@ def _execute_function_local(func: dict, event: dict) -> dict:
lzf.extractall(layer_dir)
layers_dirs.append(layer_dir)
+ # Symlink layer node_modules packages into the code directory so that
+ # Node.js ESM import() can resolve them via ancestor-tree lookup.
+ if layers_dirs and is_node:
+ code_nm = os.path.join(code_dir, "node_modules")
+ os.makedirs(code_nm, exist_ok=True)
+ for ld in layers_dirs:
+ layer_nm = os.path.join(ld, "nodejs", "node_modules")
+ if os.path.isdir(layer_nm):
+ for pkg in os.listdir(layer_nm):
+ src = os.path.join(layer_nm, pkg)
+ dst = os.path.join(code_nm, pkg)
+ if not os.path.exists(dst):
+ os.symlink(src, dst)
+
if "." not in handler:
return {"body": {"errorMessage": f"Invalid handler format: {handler}", "errorType": "Runtime.InvalidEntrypoint"}, "error": True}
module_name, func_name = handler.rsplit(".", 1)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 0a309e85..45c68af7 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1644,6 +1644,61 @@ def test_lambda_warm_worker_nodejs_uses_layer(lam):
assert payload["value"] == "from-node-layer"
finally:
lam.delete_function(FunctionName=fname)
+
+def test_lambda_warm_worker_nodejs_esm_uses_layer(lam):
+ """ESM .mjs handler must be able to import packages from a Lambda Layer.
+
+ This is the combined case of ESM support (PR #238) and Layer extraction
+ (PR #236). Node.js ESM import() does not use NODE_PATH, so the runtime
+ symlinks layer packages into code/node_modules/ for ancestor-tree resolution.
+ """
+ # Create a layer with a Node.js package under nodejs/node_modules/
+ layer_buf = io.BytesIO()
+ with zipfile.ZipFile(layer_buf, "w") as z:
+ z.writestr(
+ "nodejs/node_modules/esmhelper/index.js",
+ "module.exports.LAYER_VALUE = 'from-esm-layer';\n",
+ )
+ layer_resp = lam.publish_layer_version(
+ LayerName="warm-esm-layer-test",
+ Content={"ZipFile": layer_buf.getvalue()},
+ CompatibleRuntimes=["nodejs20.x"],
+ )
+ layer_arn = layer_resp["LayerVersionArn"]
+
+ # Create an ESM handler that uses native import to load the layer package.
+ # The layer package exports via CJS but Node.js ESM can import CJS modules.
+ # Native import does NOT use NODE_PATH — this is the bug we are testing.
+ handler_code = (
+ "import helper from 'esmhelper';\n"
+ "export const handler = async (event) => {\n"
+ " return { value: helper.LAYER_VALUE, esm: true };\n"
+ "};\n"
+ )
+ func_buf = io.BytesIO()
+ with zipfile.ZipFile(func_buf, "w") as z:
+ z.writestr("index.mjs", handler_code)
+
+ fname = f"warm-esm-layer-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": func_buf.getvalue()},
+ Layers=[layer_arn],
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")
+ assert resp["StatusCode"] == 200
+ assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"
+ payload = json.loads(resp["Payload"].read())
+ assert payload["value"] == "from-esm-layer"
+ assert payload["esm"] is True
+ finally:
+ lam.delete_function(FunctionName=fname)
+
# ---------------------------------------------------------------------------
# Terraform compatibility tests
# ---------------------------------------------------------------------------