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
fix(lambda): fall back to import() on ERR_REQUIRE_ASYNC_MODULE too (#1466)
ryan-bennett720b83c26f5f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4044a9e2..60714525 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Lambda — Node.js ESM handlers using top-level `await` load correctly** — the warm-worker and one-shot Node bootstraps `require()` the handler module and fall back to dynamic `import()` only on `ERR_REQUIRE_ESM`; a module whose graph contains a top-level `await` instead throws Node's `ERR_REQUIRE_ASYNC_MODULE` (since a synchronous `require()` can never wait on an async operation), which fell through to an uncaught `RuntimeError`. Both bootstraps now treat `ERR_REQUIRE_ASYNC_MODULE` the same as `ERR_REQUIRE_ESM`. This is AWS's own documented Lambda cold-start pattern (a module-scope `await` to force a client connection during Init, before the first invocation) and works unmodified on real Lambda already. Contributed by @ryan-bennett.- **Cognito — `ListUsers` `Filter` matches values case-insensitively, except where AWS documents otherwise** — every filter comparison was an exact string match, so `email = "[email protected]"` missed a profile stored as `[email protected]` and a `^=` prefix search was equally literal. Values are now matched case-insensitively for `email`, `phone_number`, `name`, `given_name`, `family_name`, `preferred_username` and `sub`, while `username` and `status` stay case-sensitive as the `ListUsers` API reference specifies. Contributed by @ppettitau.- **DynamoDB — an `UpdateExpression` alias is resolved before the key-attribute check** — `set #pk = :pk` with `#pk` mapped to a non-key attribute was refused with `Cannot update attribute pk. This attribute is part of the key`, because the check matched the key name as raw text inside the `#pk` alias and the `:pk` value reference. It now reads the alias-resolved attribute roots the update evaluator already reports, so only a path that resolves to the partition or sort key is rejected. Reported by @ppettitau.- **RDS — `DescribeDBInstances` honors SDK `Filters`** — AWS Query clients serialize filters as `Filters.Filter.N` with `Values.Value.N`, but MiniStack only parsed its internal `Filters.member.N` form, so filters such as `db-cluster-id` were ignored and unrelated instances were returned. Both wire forms are now parsed with the existing AND-across-filters and OR-across-values semantics.diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 7559068f..ff91e0ba 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -821,7 +821,7 @@ rl.on("line", async (line) => {try {mod = require(resolvedPath);} catch (reqErr) {- if (reqErr.code === "ERR_REQUIRE_ESM") {+ if (reqErr.code === "ERR_REQUIRE_ESM" || reqErr.code === "ERR_REQUIRE_ASYNC_MODULE") {const { pathToFileURL } = require("url");mod = await import(pathToFileURL(resolvedPath).href);} else {diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 56ec7e41..1f3eea0a 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -802,7 +802,7 @@ process.stdin.on('end', async () => {resolvedPath = require.resolve(fullPath);mod = require(resolvedPath);} catch (reqErr) {- if (reqErr.code === 'ERR_REQUIRE_ESM' && resolvedPath) {+ if ((reqErr.code === 'ERR_REQUIRE_ESM' || reqErr.code === 'ERR_REQUIRE_ASYNC_MODULE') && resolvedPath) {mod = await import(pathToFileURL(resolvedPath).href);} else if (reqErr.code === 'MODULE_NOT_FOUND') {const mjsPath = fullPath + '.mjs';diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 74de1769..bb1b34ee 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -4241,6 +4241,49 @@ def test_lambda_nodejs_esm_type_module(lam):lam.delete_function(FunctionName=fname)+def test_lambda_nodejs_esm_top_level_await(lam):+ """Node.js ESM handlers using top-level await must load via ERR_REQUIRE_ASYNC_MODULE fallback.++ Node's `require(esm)` interop throws ERR_REQUIRE_ASYNC_MODULE — a+ distinct error code from ERR_REQUIRE_ESM — specifically when the+ required module's graph contains a top-level `await`, since a+ synchronous require() can never wait on an async operation. This is+ AWS's own documented Lambda cold-start pattern (module-scope+ `await someClient.send(...)` to force connection setup during Init,+ before the first invocation), so handlers using it must still load.+ """+ fname = f"lam-esm-tla-{_uuid_mod.uuid4().hex[:8]}"++ handler_code = (+ "await Promise.resolve();\n"+ "export const handler = async (event) => ({\n"+ " statusCode: 200,\n"+ " body: 'top-level-await-works',\n"+ "});\n"+ )++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.mjs", handler_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=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["statusCode"] == 200+ assert payload["body"] == "top-level-await-works"+ finally:+ lam.delete_function(FunctionName=fname)++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/