From 352332db0ec5f2280a89446f65711d89d9c873bb Mon Sep 17 00:00:00 2001 From: Anish Nandamuri Date: Mon, 30 Nov 2026 01:31:57 -0500 Subject: [PATCH 1/4] fix: refresh local npm dependencies during in-source builds --- .../workflows/nodejs_npm/actions.py | 96 ++++++++ .../test_local_dependency_refresh.py | 78 ++++++ .../test_local_dependency_refresh.py | 223 ++++++++++++++++++ 3 files changed, 397 insertions(+) create mode 100644 tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py create mode 100644 tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index bf2f1bc17..c23b4cc53 100644 --- a/aws_lambda_builders/workflows/nodejs_npm/actions.py +++ b/aws_lambda_builders/workflows/nodejs_npm/actions.py @@ -2,9 +2,11 @@ Action to resolve NodeJS dependencies using NPM """ +import json import logging import os import re +import shutil from typing import Optional from aws_lambda_builders import utils @@ -167,6 +169,98 @@ class NodejsNpmUpdateAction(NodejsNpmInstallOrUpdateBaseAction): NAME = "NpmUpdate" DESCRIPTION = "Updating dependencies from NPM" + def _read_local_dependencies(self, include_dev=False): + """Read dependency declarations from the npm manifest.""" + manifest_path = os.path.join(self.install_dir, "package.json") + + try: + with open(manifest_path, encoding="utf-8-sig") as manifest_file: + manifest = json.load(manifest_file) + except (FileNotFoundError, json.JSONDecodeError): + # Let npm handle missing or invalid manifests. + return {} + + if not isinstance(manifest, dict): + return {} + + dependencies = {} + + sections = ["dependencies", "optionalDependencies"] + if include_dev or not self.omit_dev: + sections.insert(0, "devDependencies") + + for section in sections: + entries = manifest.get(section, {}) + if isinstance(entries, dict): + dependencies.update(entries) + + return dependencies + + @staticmethod + def _paths_overlap(first, second): + # Compare conservatively on case-insensitive filesystems. + first = os.path.normcase(first).casefold() + second = os.path.normcase(second).casefold() + + try: + common = os.path.commonpath([first, second]) + except ValueError: + return False + + return common in (first, second) + + def _refresh_local_dependencies(self): + """Refresh installed copies of local directory dependencies.""" + dependencies = self._read_local_dependencies() + + install_dir = os.path.realpath(self.install_dir) + modules_dir = os.path.join(install_dir, "node_modules") + + protected_sources = [ + os.path.realpath(os.path.join(install_dir, spec[5:])) + for spec in self._read_local_dependencies(include_dev=True).values() + if isinstance(spec, str) and spec.startswith("file:") and "\x00" not in spec + ] + + if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): + return + + for name, spec in dependencies.items(): + if not isinstance(spec, str) or not spec.startswith("file:"): + continue + + if not re.fullmatch( + r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", + name, + ): + continue + + local_source = os.path.realpath(os.path.join(install_dir, spec[5:])) + + if not os.path.isdir(local_source): + continue + + if not os.path.isfile(os.path.join(local_source, "package.json")): + continue + + installed = os.path.join(modules_dir, *name.split("/")) + + if not os.path.isdir(installed) or os.path.islink(installed): + continue + + if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): + continue + + if any(self._paths_overlap(installed, path) for path in protected_sources): + continue + + LOG.debug("Refreshing local npm dependency: %s", name) + + try: + shutil.rmtree(installed) + except OSError as ex: + raise ActionFailedError(str(ex)) from ex + def execute(self): """ Runs the action. @@ -176,6 +270,8 @@ def execute(self): try: LOG.debug("NODEJS updating dependencies in: %s", self.install_dir) + self._refresh_local_dependencies() + command = ["update", "--no-audit", "--no-save"] if self.omit_dev: command.append("--omit=dev") diff --git a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py new file mode 100644 index 000000000..b1dedbbe1 --- /dev/null +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,78 @@ +import json + +from aws_lambda_builders.builder import LambdaBuilder + + +def test_build_in_source_refreshes_local_dependency(tmp_path): + source_dir = tmp_path / "function" + local_dep = tmp_path / "local-dependency" + artifacts_dir = tmp_path / "artifacts" + scratch_dir = tmp_path / "scratch" + + for directory in ( + source_dir, + local_dep, + artifacts_dir, + scratch_dir, + ): + directory.mkdir() + + (local_dep / "package.json").write_text( + json.dumps( + { + "name": "local-dependency", + "version": "1.0.0", + "main": "index.js", + } + ), + encoding="utf-8", + ) + + dependency_source = local_dep / "index.js" + dependency_source.write_text( + "module.exports = 'original';\n", + encoding="utf-8", + ) + + manifest = source_dir / "package.json" + manifest.write_text( + json.dumps( + { + "name": "test-function", + "version": "1.0.0", + "dependencies": {"local-dependency": "file:../local-dependency"}, + } + ), + encoding="utf-8", + ) + + builder = LambdaBuilder( + language="nodejs", + dependency_manager="npm", + application_framework=None, + ) + + def build(): + builder.build( + str(source_dir), + str(artifacts_dir), + str(scratch_dir), + str(manifest), + runtime="nodejs20.x", + build_in_source=True, + ) + + build() + + installed = artifacts_dir / "node_modules" / "local-dependency" / "index.js" + + assert installed.read_text() == "module.exports = 'original';\n" + + dependency_source.write_text( + "module.exports = 'updated';\n", + encoding="utf-8", + ) + + build() + + assert installed.read_text() == "module.exports = 'updated';\n" diff --git a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py new file mode 100644 index 000000000..b57f9afa2 --- /dev/null +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,223 @@ +import json +from unittest.mock import Mock + +import pytest + +from aws_lambda_builders.workflows.nodejs_npm.actions import ( + NodejsNpmUpdateAction, +) + + +def make_package(path): + path.mkdir(parents=True, exist_ok=True) + (path / "package.json").write_text( + '{"name": "example", "version": "1.0.0"}', + encoding="utf-8", + ) + (path / "index.js").write_text( + "module.exports = 'example';", + encoding="utf-8", + ) + return path + + +def make_action(project, manifest, omit_dev=True): + (project / "package.json").write_text( + json.dumps(manifest), + encoding="utf-8", + ) + npm = Mock() + action = NodejsNpmUpdateAction( + str(project), + subprocess_npm=npm, + omit_dev=omit_dev, + ) + return action, npm + + +@pytest.mark.parametrize( + "section,name,omit_dev,removed", + [ + ("dependencies", "local-dependency", True, True), + ("dependencies", "@example/local", True, True), + ("optionalDependencies", "local-dependency", True, True), + ("devDependencies", "local-dependency", True, False), + ("devDependencies", "local-dependency", False, True), + ], +) +def test_refresh_dependency_types(tmp_path, section, name, omit_dev, removed): + project = tmp_path / "project" + project.mkdir() + + local = make_package(tmp_path / "local") + installed = make_package(project / "node_modules" / name) + unrelated = make_package(project / "node_modules" / "unrelated") + + action, npm = make_action( + project, + {section: {name: "file:../local"}}, + omit_dev=omit_dev, + ) + + def verify_before_update(*args, **kwargs): + assert installed.exists() != removed + assert local.exists() + assert unrelated.exists() + + npm.run.side_effect = verify_before_update + + action.execute() + + npm.run.assert_called_once() + + +def test_preserves_registry_and_tarball_dependencies(tmp_path): + project = tmp_path / "project" + project.mkdir() + + registry = make_package(project / "node_modules" / "registry") + archive = make_package(project / "node_modules" / "archive") + + (tmp_path / "archive.tgz").write_bytes(b"archive") + + action, npm = make_action( + project, + { + "dependencies": { + "registry": "^1.0.0", + "archive": "file:../archive.tgz", + } + }, + ) + + action.execute() + + assert registry.exists() + assert archive.exists() + npm.run.assert_called_once() + + +def test_preserves_symlinked_dependency(tmp_path): + project = tmp_path / "project" + modules = project / "node_modules" + modules.mkdir(parents=True) + + local = make_package(tmp_path / "local") + installed = modules / "local-dependency" + + try: + installed.symlink_to(local, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:../local"}}, + ) + + action.execute() + + assert installed.is_symlink() + assert (local / "index.js").exists() + npm.run.assert_called_once() + + +def test_preserves_symlinked_node_modules(tmp_path): + project = tmp_path / "project" + project.mkdir() + + external = tmp_path / "external" + external.mkdir() + + installed = make_package(external / "local-dependency") + make_package(tmp_path / "local") + + try: + (project / "node_modules").symlink_to(external, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:../local"}}, + ) + + action.execute() + + assert installed.exists() + npm.run.assert_called_once() + + +def test_rejects_path_traversal(tmp_path): + project = tmp_path / "project" + (project / "node_modules").mkdir(parents=True) + + protected = make_package(project / "protected") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + {"dependencies": {"../protected": "file:../local"}}, + ) + + action.execute() + + assert (protected / "index.js").exists() + npm.run.assert_called_once() + + +def test_preserves_original_source(tmp_path): + project = tmp_path / "project" + + installed = make_package(project / "node_modules" / "local-dependency") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:node_modules/local-dependency"}}, + ) + + action.execute() + + assert (installed / "index.js").exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("manifest", [None, "{invalid json"]) +def test_invalid_or_missing_manifest(tmp_path, manifest): + if manifest is not None: + (tmp_path / "package.json").write_text(manifest, encoding="utf-8") + + npm = Mock() + + action = NodejsNpmUpdateAction( + str(tmp_path), + subprocess_npm=npm, + ) + + action.execute() + + npm.run.assert_called_once() + + +@pytest.mark.parametrize("section", ["dependencies", "devDependencies"]) +def test_preserves_other_dependency_source(tmp_path, section): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + nested_source = make_package(installed / "nested-source") + make_package(tmp_path / "local") + + manifest = { + "dependencies": { + "local-dependency": "file:../local", + } + } + + manifest.setdefault(section, {})["other"] = "file:node_modules/local-dependency/nested-source" + + action, npm = make_action(project, manifest) + + action.execute() + + assert installed.exists() + assert nested_source.exists() + npm.run.assert_called_once() From 55b4dd8a9b36e2c378c145475921dacb629d6db2 Mon Sep 17 00:00:00 2001 From: Anish Nandamuri Date: Mon, 30 Nov 2026 17:47:02 -0500 Subject: [PATCH 2/4] Address review feedback for local npm dependency refresh --- .../workflows/nodejs_npm/actions.py | 202 ++++++++++-------- .../test_local_dependency_refresh.py | 181 ++++++++++------ .../test_local_dependency_refresh.py | 118 +++++++++- 3 files changed, 350 insertions(+), 151 deletions(-) diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index c23b4cc53..e5673ee20 100644 --- a/aws_lambda_builders/workflows/nodejs_npm/actions.py +++ b/aws_lambda_builders/workflows/nodejs_npm/actions.py @@ -106,99 +106,70 @@ def __init__(self, install_dir: str, subprocess_npm: SubprocessNpm, omit_dev: bo self.subprocess_npm = subprocess_npm self.omit_dev = omit_dev - -class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): - """ - A Lambda Builder Action that installs NPM project dependencies - """ - - NAME = "NpmInstall" - DESCRIPTION = "Installing dependencies from NPM" - - def __init__( - self, - install_dir: str, - subprocess_npm: SubprocessNpm, - install_links: Optional[bool] = False, - omit_dev: bool = True, - ): - """ - Parameters - ---------- - install_links : Optional[bool] - Uses the --install-links npm option if True, by default False. Required when installing into the - source directory, so that local file dependencies are installed as regular dependencies. - - See NodejsNpmInstallOrUpdateBaseAction for the rest. - """ - - super().__init__(install_dir=install_dir, subprocess_npm=subprocess_npm, omit_dev=omit_dev) - self.install_links = install_links - - def execute(self): - """ - Runs the action. - - :raises lambda_builders.actions.ActionFailedError: when NPM execution fails - """ - try: - LOG.debug("NODEJS installing dependencies in: %s", self.install_dir) - - command = ["install", "-q", "--no-audit", "--no-save"] - if self.omit_dev: - command.append("--omit=dev") - if self.install_links: - command.append("--install-links") - self.subprocess_npm.run(command, cwd=self.install_dir) - - except NpmExecutionError as ex: - raise ActionFailedError(str(ex)) - - -class NodejsNpmUpdateAction(NodejsNpmInstallOrUpdateBaseAction): - """ - A Lambda Builder Action that installs NPM project dependencies, ignoring any lockfile. - - Used when building in source and either no lockfile applies or `experimentalNodejsMonorepo` is off - - which, the flag being opt-in, is still every in-source build by default, lockfile or not. - `--no-package-lock` means dependency versions are resolved afresh on every build, so once a caller - opts in, a project that does have a lockfile is installed with NodejsNpmInstallAction instead to keep - builds reproducible. - """ - - NAME = "NpmUpdate" - DESCRIPTION = "Updating dependencies from NPM" - - def _read_local_dependencies(self, include_dev=False): - """Read dependency declarations from the npm manifest.""" + def _read_local_dependencies(self): + """Read the manifest once for active and protected dependencies.""" manifest_path = os.path.join(self.install_dir, "package.json") try: with open(manifest_path, encoding="utf-8-sig") as manifest_file: manifest = json.load(manifest_file) - except (FileNotFoundError, json.JSONDecodeError): + except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError): # Let npm handle missing or invalid manifests. - return {} + return {}, [] if not isinstance(manifest, dict): - return {} + return {}, [] dependencies = {} + protected_specs = [] - sections = ["dependencies", "optionalDependencies"] - if include_dev or not self.omit_dev: - sections.insert(0, "devDependencies") - - for section in sections: + for section in ("devDependencies", "dependencies", "optionalDependencies"): entries = manifest.get(section, {}) - if isinstance(entries, dict): + if not isinstance(entries, dict): + continue + + # Protect every declared source, including omitted dev dependencies + # and declarations overridden by another dependency section. + protected_specs.extend(entries.values()) + + if section != "devDependencies" or not self.omit_dev: dependencies.update(entries) - return dependencies + return dependencies, protected_specs + + @staticmethod + def _local_dependency_source(install_dir, spec): + """Normalize file: and bare local dependency paths.""" + if not isinstance(spec, str) or "\x00" in spec: + return None + + if spec.startswith("file:"): + path = spec[5:] + elif spec.startswith(("./", "../", "/", "~/")) or os.path.isabs(spec): + path = spec + elif os.name == "nt" and spec.startswith((".\\", "..\\", "~\\")): + path = spec + else: + return None + + if not path: + return None + + if path.startswith("~/") or (os.name == "nt" and path.startswith("~\\")): + expanded = os.path.expanduser(path) + if expanded == path: + return None + path = expanded + + return os.path.realpath(os.path.join(install_dir, path)) @staticmethod def _paths_overlap(first, second): - # Compare conservatively on case-insensitive filesystems. + """Compare conservatively using case folding on every OS. + + Even on case-sensitive filesystems, treating case variants as + overlapping errs on the side of preserving source directories. + """ first = os.path.normcase(first).casefold() second = os.path.normcase(second).casefold() @@ -210,23 +181,22 @@ def _paths_overlap(first, second): return common in (first, second) def _refresh_local_dependencies(self): - """Refresh installed copies of local directory dependencies.""" - dependencies = self._read_local_dependencies() - + """Refresh installed copies of direct local directory dependencies.""" + dependencies, protected_specs = self._read_local_dependencies() install_dir = os.path.realpath(self.install_dir) modules_dir = os.path.join(install_dir, "node_modules") protected_sources = [ - os.path.realpath(os.path.join(install_dir, spec[5:])) - for spec in self._read_local_dependencies(include_dev=True).values() - if isinstance(spec, str) and spec.startswith("file:") and "\x00" not in spec + path for spec in protected_specs if (path := self._local_dependency_source(install_dir, spec)) is not None ] if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): return for name, spec in dependencies.items(): - if not isinstance(spec, str) or not spec.startswith("file:"): + local_source = self._local_dependency_source(install_dir, spec) + + if local_source is None: continue if not re.fullmatch( @@ -235,8 +205,6 @@ def _refresh_local_dependencies(self): ): continue - local_source = os.path.realpath(os.path.join(install_dir, spec[5:])) - if not os.path.isdir(local_source): continue @@ -261,6 +229,70 @@ def _refresh_local_dependencies(self): except OSError as ex: raise ActionFailedError(str(ex)) from ex + +class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): + """ + A Lambda Builder Action that installs NPM project dependencies + """ + + NAME = "NpmInstall" + DESCRIPTION = "Installing dependencies from NPM" + + def __init__( + self, + install_dir: str, + subprocess_npm: SubprocessNpm, + install_links: Optional[bool] = False, + omit_dev: bool = True, + ): + """ + Parameters + ---------- + install_links : Optional[bool] + Uses the --install-links npm option if True, by default False. Required when installing into the + source directory, so that local file dependencies are installed as regular dependencies. + + See NodejsNpmInstallOrUpdateBaseAction for the rest. + """ + + super().__init__(install_dir=install_dir, subprocess_npm=subprocess_npm, omit_dev=omit_dev) + self.install_links = install_links + + def execute(self): + """ + Runs the action. + + :raises lambda_builders.actions.ActionFailedError: when NPM execution fails + """ + try: + LOG.debug("NODEJS installing dependencies in: %s", self.install_dir) + + command = ["install", "-q", "--no-audit", "--no-save"] + if self.omit_dev: + command.append("--omit=dev") + if self.install_links: + self._refresh_local_dependencies() + command.append("--install-links") + self.subprocess_npm.run(command, cwd=self.install_dir) + + except NpmExecutionError as ex: + raise ActionFailedError(str(ex)) + + +class NodejsNpmUpdateAction(NodejsNpmInstallOrUpdateBaseAction): + """ + A Lambda Builder Action that installs NPM project dependencies, ignoring any lockfile. + + Used when building in source and either no lockfile applies or `experimentalNodejsMonorepo` is off - + which, the flag being opt-in, is still every in-source build by default, lockfile or not. + `--no-package-lock` means dependency versions are resolved afresh on every build, so once a caller + opts in, a project that does have a lockfile is installed with NodejsNpmInstallAction instead to keep + builds reproducible. + """ + + NAME = "NpmUpdate" + DESCRIPTION = "Updating dependencies from NPM" + def execute(self): """ Runs the action. diff --git a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py index b1dedbbe1..f0be99b7f 100644 --- a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -1,78 +1,135 @@ import json +import tempfile +from pathlib import Path +from unittest import TestCase + +from parameterized import parameterized from aws_lambda_builders.builder import LambdaBuilder +from aws_lambda_builders.supported_runtimes import NODEJS_RUNTIMES +from aws_lambda_builders.workflows.nodejs_npm.npm import SubprocessNpm +from aws_lambda_builders.workflows.nodejs_npm.utils import ( + EXPERIMENTAL_FLAG_NODEJS_MONOREPO, + OSUtils, +) -def test_build_in_source_refreshes_local_dependency(tmp_path): - source_dir = tmp_path / "function" - local_dep = tmp_path / "local-dependency" - artifacts_dir = tmp_path / "artifacts" - scratch_dir = tmp_path / "scratch" - - for directory in ( - source_dir, - local_dep, - artifacts_dir, - scratch_dir, - ): - directory.mkdir() - - (local_dep / "package.json").write_text( - json.dumps( - { - "name": "local-dependency", - "version": "1.0.0", - "main": "index.js", - } - ), - encoding="utf-8", - ) +class TestLocalDependencyRefresh(TestCase): - dependency_source = local_dep / "index.js" - dependency_source.write_text( - "module.exports = 'original';\n", - encoding="utf-8", + @parameterized.expand( + [ + ( + f"{runtime}_{path_type}_{workflow}", + runtime, + spec, + workflow == "install", + ) + for runtime in NODEJS_RUNTIMES + for path_type, spec in [ + ("file", "file:../local-dependency"), + ("bare", "../local-dependency"), + ] + for workflow in ["update", "install"] + ] ) + def test_build_in_source_refreshes_local_dependency(self, _name, runtime, spec, use_lockfile): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + source_dir = root / "function" + local_dep = root / "local-dependency" + artifacts_dir = root / "artifacts" + scratch_dir = root / "scratch" - manifest = source_dir / "package.json" - manifest.write_text( - json.dumps( - { - "name": "test-function", - "version": "1.0.0", - "dependencies": {"local-dependency": "file:../local-dependency"}, - } - ), - encoding="utf-8", - ) + for directory in ( + source_dir, + local_dep, + artifacts_dir, + scratch_dir, + ): + directory.mkdir() - builder = LambdaBuilder( - language="nodejs", - dependency_manager="npm", - application_framework=None, - ) + (local_dep / "package.json").write_text( + json.dumps( + { + "name": "local-dependency", + "version": "1.0.0", + "main": "index.js", + } + ), + encoding="utf-8", + ) - def build(): - builder.build( - str(source_dir), - str(artifacts_dir), - str(scratch_dir), - str(manifest), - runtime="nodejs20.x", - build_in_source=True, - ) + dependency_source = local_dep / "index.js" - build() + original = "module.exports = 'original';\\n" + updated = "module.exports = 'updated';\\n" - installed = artifacts_dir / "node_modules" / "local-dependency" / "index.js" + dependency_source.write_text(original, encoding="utf-8") - assert installed.read_text() == "module.exports = 'original';\n" + manifest = source_dir / "package.json" + manifest.write_text( + json.dumps( + { + "name": "test-function", + "version": "1.0.0", + "dependencies": {"local-dependency": spec}, + } + ), + encoding="utf-8", + ) - dependency_source.write_text( - "module.exports = 'updated';\n", - encoding="utf-8", - ) + flags = [] + lockfile = source_dir / "package-lock.json" + original_lockfile = None + + if use_lockfile: + SubprocessNpm(OSUtils()).run( + [ + "install", + "--package-lock-only", + "--install-links", + "--no-audit", + "--no-fund", + ], + cwd=str(source_dir), + ) + + original_lockfile = lockfile.read_bytes() + flags = [EXPERIMENTAL_FLAG_NODEJS_MONOREPO] + + builder = LambdaBuilder( + language="nodejs", + dependency_manager="npm", + application_framework=None, + ) + + def build(): + builder.build( + str(source_dir), + str(artifacts_dir), + str(scratch_dir), + str(manifest), + runtime=runtime, + build_in_source=True, + experimental_flags=flags, + ) + + build() + + installed = source_dir / "node_modules" / "local-dependency" / "index.js" + + artifact = artifacts_dir / "node_modules" / "local-dependency" / "index.js" + + self.assertEqual(installed.read_text(encoding="utf-8"), original) + self.assertEqual(artifact.read_text(encoding="utf-8"), original) + + dependency_source.write_text(updated, encoding="utf-8") + + build() - build() + self.assertEqual(dependency_source.read_text(encoding="utf-8"), updated) + self.assertEqual(installed.read_text(encoding="utf-8"), updated) + self.assertEqual(artifact.read_text(encoding="utf-8"), updated) - assert installed.read_text() == "module.exports = 'updated';\n" + if use_lockfile: + self.assertEqual(lockfile.read_bytes(), original_lockfile) diff --git a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py index b57f9afa2..11b93f697 100644 --- a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -4,6 +4,7 @@ import pytest from aws_lambda_builders.workflows.nodejs_npm.actions import ( + NodejsNpmInstallAction, NodejsNpmUpdateAction, ) @@ -45,7 +46,8 @@ def make_action(project, manifest, omit_dev=True): ("devDependencies", "local-dependency", False, True), ], ) -def test_refresh_dependency_types(tmp_path, section, name, omit_dev, removed): +@pytest.mark.parametrize("spec", ["file:../local", "../local"]) +def test_refresh_dependency_types(tmp_path, section, name, omit_dev, removed, spec): project = tmp_path / "project" project.mkdir() @@ -55,7 +57,7 @@ def test_refresh_dependency_types(tmp_path, section, name, omit_dev, removed): action, npm = make_action( project, - {section: {name: "file:../local"}}, + {section: {name: spec}}, omit_dev=omit_dev, ) @@ -200,7 +202,8 @@ def test_invalid_or_missing_manifest(tmp_path, manifest): @pytest.mark.parametrize("section", ["dependencies", "devDependencies"]) -def test_preserves_other_dependency_source(tmp_path, section): +@pytest.mark.parametrize("prefix", ["file:", "./"]) +def test_preserves_other_dependency_source(tmp_path, section, prefix): project = tmp_path / "project" installed = make_package(project / "node_modules" / "local-dependency") nested_source = make_package(installed / "nested-source") @@ -212,7 +215,7 @@ def test_preserves_other_dependency_source(tmp_path, section): } } - manifest.setdefault(section, {})["other"] = "file:node_modules/local-dependency/nested-source" + manifest.setdefault(section, {})["other"] = prefix + "node_modules/local-dependency/nested-source" action, npm = make_action(project, manifest) @@ -221,3 +224,110 @@ def test_preserves_other_dependency_source(tmp_path, section): assert installed.exists() assert nested_source.exists() npm.run.assert_called_once() + + +@pytest.mark.parametrize( + "path_type", + ["relative", "absolute", "home", "file-home"], +) +def test_refresh_additional_local_paths(tmp_path, monkeypatch, path_type): + project = tmp_path / "project" + project.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("USERPROFILE", str(tmp_path)) + + if path_type == "relative": + local = make_package(project / "local") + spec = "./local" + else: + local = make_package(tmp_path / "local") + if path_type == "absolute": + spec = str(local) + elif path_type == "home": + spec = "~/local" + else: + spec = "file:~/local" + + installed = make_package(project / "node_modules" / "local-dependency") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": spec}}, + ) + + action.execute() + + assert not installed.exists() + assert (local / "index.js").exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("spec", ["file:../local\x00", "../local\x00"]) +def test_rejects_null_characters(tmp_path, spec): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": spec}}, + ) + + action.execute() + + assert installed.exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("install_links", [True, False]) +def test_install_refreshes_only_when_install_links_enabled(tmp_path, install_links): + project = tmp_path / "project" + local = make_package(tmp_path / "local") + installed = make_package(project / "node_modules" / "local-dependency") + + (project / "package.json").write_text( + json.dumps({"dependencies": {"local-dependency": "../local"}}), + encoding="utf-8", + ) + + npm = Mock() + action = NodejsNpmInstallAction( + str(project), + subprocess_npm=npm, + install_links=install_links, + ) + + def verify_before_install(*args, **kwargs): + assert installed.exists() != install_links + assert local.exists() + + npm.run.side_effect = verify_before_install + action.execute() + npm.run.assert_called_once() + + +def test_preserves_sources_from_overridden_declarations(tmp_path): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + nested_source = make_package(installed / "nested-source") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + { + "dependencies": { + "local-dependency": "../local", + "other": "1.0.0", + }, + "devDependencies": { + "other": "./node_modules/local-dependency/nested-source", + }, + }, + ) + + action.execute() + + assert installed.exists() + assert nested_source.exists() + npm.run.assert_called_once() From a77e6f083e66bbaddcb950411fb5cb57a4b77325 Mon Sep 17 00:00:00 2001 From: Anish Nandamuri Date: Tue, 1 Dec 2026 00:06:26 -0500 Subject: [PATCH 3/4] Fix local dependency refresh in npm workspaces --- .../workflows/nodejs_npm/actions.py | 248 ++++++++++++++---- .../test_local_dependency_refresh.py | 73 ++++++ .../test_local_dependency_refresh.py | 88 +++++++ 3 files changed, 365 insertions(+), 44 deletions(-) diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index e5673ee20..9ce17ce6b 100644 --- a/aws_lambda_builders/workflows/nodejs_npm/actions.py +++ b/aws_lambda_builders/workflows/nodejs_npm/actions.py @@ -106,18 +106,19 @@ def __init__(self, install_dir: str, subprocess_npm: SubprocessNpm, omit_dev: bo self.subprocess_npm = subprocess_npm self.omit_dev = omit_dev - def _read_local_dependencies(self): - """Read the manifest once for active and protected dependencies.""" - manifest_path = os.path.join(self.install_dir, "package.json") - + @staticmethod + def _read_manifest(directory): try: - with open(manifest_path, encoding="utf-8-sig") as manifest_file: + with open(os.path.join(directory, "package.json"), encoding="utf-8-sig") as manifest_file: manifest = json.load(manifest_file) - except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError): + except (OSError, ValueError): # Let npm handle missing or invalid manifests. - return {}, [] + return None + return manifest if isinstance(manifest, dict) else None - if not isinstance(manifest, dict): + def _read_local_dependencies(self, manifest): + """Derive active and protected dependencies from one parsed manifest.""" + if manifest is None: return {}, [] dependencies = {} @@ -180,54 +181,213 @@ def _paths_overlap(first, second): return common in (first, second) - def _refresh_local_dependencies(self): - """Refresh installed copies of direct local directory dependencies.""" - dependencies, protected_specs = self._read_local_dependencies() - install_dir = os.path.realpath(self.install_dir) - modules_dir = os.path.join(install_dir, "node_modules") - - protected_sources = [ - path for spec in protected_specs if (path := self._local_dependency_source(install_dir, spec)) is not None - ] + @staticmethod + def _valid_dependency_name(name): + return ( + isinstance(name, str) + and re.fullmatch(r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", name) is not None + ) - if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): + def _remove_local_copy(self, installed, local_source, protected_sources): + if local_source is None or not os.path.isdir(local_source): + return + if not os.path.isfile(os.path.join(local_source, "package.json")): + return + if not os.path.isdir(installed) or os.path.islink(installed): + return + if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): + return + if any(self._paths_overlap(installed, path) for path in protected_sources): return - for name, spec in dependencies.items(): - local_source = self._local_dependency_source(install_dir, spec) + LOG.debug("Refreshing local npm dependency: %s", installed) + try: + shutil.rmtree(installed) + except OSError as ex: + raise ActionFailedError(str(ex)) from ex + + def _workspace_root(self, install_dir, manifest): + """Find the nearest ancestor that declares npm workspaces.""" + root, root_manifest = install_dir, manifest + while not (root_manifest and root_manifest.get("workspaces")): + parent = os.path.dirname(root) + if parent == root: + return None, None + root = parent + root_manifest = self._read_manifest(root) + return root, root_manifest + + def _workspace_metadata(self, root, modules): + """Read the installed tree and ask npm for current workspace names.""" + hidden_lockfile = os.path.join(modules, ".package-lock.json") + if os.path.normcase(os.path.realpath(modules)) != os.path.normcase(modules): + return None + try: + if os.path.getmtime(hidden_lockfile) < os.path.getmtime(modules): + return None + with open(hidden_lockfile, encoding="utf-8-sig") as lockfile: + lock = json.load(lockfile) + if not isinstance(lock, dict) or lock.get("lockfileVersion") not in (2, 3): + return None + packages = lock.get("packages") + if not isinstance(packages, dict): + return None + # Let npm expand workspace patterns rather than duplicating its globbing rules. + names = json.loads(self.subprocess_npm.run(["pkg", "get", "name", "--workspaces", "--json"], cwd=root)) + except (OSError, ValueError, NpmExecutionError): + return None + return (packages, names) if isinstance(names, dict) and names else None - if local_source is None: - continue + def _workspace_member_path(self, root, modules, relative): + """Accept only a real member directory inside the workspace root.""" + if not isinstance(relative, str) or not relative or "\x00" in relative or os.path.isabs(relative): + return None + member = os.path.abspath(os.path.join(root, relative)) + try: + if os.path.commonpath([root, member]) != root or member == root: + return None + except ValueError: + return None + if self._paths_overlap(member, modules): + return None + if os.path.normcase(os.path.realpath(member)) != os.path.normcase(member): + return None + return member - if not re.fullmatch( - r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", - name, - ): - continue + def _workspace_member(self, root, name, packages): + """Match npm's workspace name to its installed link and source path.""" + if not self._valid_dependency_name(name): + return None + entry = packages.get("node_modules/" + name) + if not isinstance(entry, dict) or entry.get("link") is not True: + return None + modules = os.path.join(root, "node_modules") + member = self._workspace_member_path(root, modules, entry.get("resolved")) + if member is None: + return None + link = os.path.join(modules, *name.split("/")) + if os.path.normcase(os.path.realpath(link)) != os.path.normcase(member): + return None + return member - if not os.path.isdir(local_source): - continue + def _workspace_manifests(self, root, manifests, packages, names, current): + """Collect every member manifest, failing closed on uncertain membership.""" + for name in names: + member = self._workspace_member(root, name, packages) + if member is None: + return None + member_manifest = current[1] if member == current[0] else self._read_manifest(member) + if not member_manifest or member_manifest.get("name") != name: + return None + manifests[member] = member_manifest + return manifests + + def _recorded_local_source(self, root, entry): + if isinstance(entry, dict): + resolved = entry.get("resolved") + if isinstance(resolved, str) and resolved.startswith("file:"): + return self._local_dependency_source(root, resolved) + return None + + def _workspace_dependency_views(self, root, manifests, packages): + """Protect all declarations, even omitted ones, and recorded local sources.""" + active, protected = {}, [] + for directory, member_manifest in manifests.items(): + dependencies, specs = self._read_local_dependencies(member_manifest) + active[directory] = dependencies + protected.extend( + path for spec in specs if (path := self._local_dependency_source(directory, spec)) is not None + ) + for entry in packages.values(): + path = self._recorded_local_source(root, entry) + if path is not None: + protected.append(path) + return active, protected + + def _workspace_installed_copy(self, root, directory, name, source, packages): + """Find the nearest installed copy only if its recorded source matches.""" + location = directory + while True: + installed = os.path.join(location, "node_modules", *name.split("/")) + if os.path.lexists(installed): + key = os.path.relpath(installed, root).replace(os.sep, "/") + entry = packages.get(key) + if not isinstance(entry, dict) or entry.get("link"): + return None + actual = self._recorded_local_source(root, entry) + if actual is not None and os.path.normcase(actual) == os.path.normcase(source): + return installed + return None + if location == root: + return None + location = os.path.dirname(location) - if not os.path.isfile(os.path.join(local_source, "package.json")): - continue + def _workspace_refresh_candidates(self, root, directories, active, packages): + candidates = {} + for directory in directories: + for name, spec in active[directory].items(): + if not self._valid_dependency_name(name): + continue + source = self._local_dependency_source(directory, spec) + if source is None: + continue + installed = self._workspace_installed_copy(root, directory, name, source, packages) + if installed is not None: + candidates[installed] = source + return candidates - installed = os.path.join(modules_dir, *name.split("/")) + def _refresh_workspace_dependencies(self, install_dir, manifest): + """Use npm's installed tree to identify local copies in a workspace. - if not os.path.isdir(installed) or os.path.islink(installed): - continue + Return False for ordinary projects. For workspaces, fail closed when + the installed lockfile or npm's workspace membership cannot identify + the exact copy. Never infer a hoisted package's source from its name. + """ + root, root_manifest = self._workspace_root(install_dir, manifest) + if root is None: + return False + if root != install_dir: + npm_root = self.subprocess_npm.resolve_project_root(self.install_dir) + if not isinstance(npm_root, str): + return True + if os.path.normcase(os.path.realpath(npm_root)) != os.path.normcase(root): + return False + metadata = self._workspace_metadata(root, os.path.join(root, "node_modules")) + if metadata is None: + return True + packages, names = metadata + # Seed only the root: membership must still be verified for the requested member. + manifests = self._workspace_manifests(root, {root: root_manifest}, packages, names, (install_dir, manifest)) + if manifests is None or install_dir not in manifests: + return True + active, protected = self._workspace_dependency_views(root, manifests, packages) + directories = manifests if install_dir == root else (install_dir,) + candidates = self._workspace_refresh_candidates(root, directories, active, packages) + # Resolve all candidates first; multiple members can share one hoisted copy. + for installed, source in candidates.items(): + self._remove_local_copy(installed, source, protected) + return True - if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): - continue + def _refresh_local_dependencies(self): + """Refresh installed copies of direct local directory dependencies.""" + install_dir = os.path.realpath(self.install_dir) + manifest = self._read_manifest(install_dir) + if self._refresh_workspace_dependencies(install_dir, manifest): + return - if any(self._paths_overlap(installed, path) for path in protected_sources): + dependencies, protected_specs = self._read_local_dependencies(manifest) + modules_dir = os.path.join(install_dir, "node_modules") + protected_sources = [ + path for spec in protected_specs if (path := self._local_dependency_source(install_dir, spec)) is not None + ] + if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): + return + for name, spec in dependencies.items(): + if not self._valid_dependency_name(name): continue - - LOG.debug("Refreshing local npm dependency: %s", name) - - try: - shutil.rmtree(installed) - except OSError as ex: - raise ActionFailedError(str(ex)) from ex + local_source = self._local_dependency_source(install_dir, spec) + installed = os.path.join(modules_dir, *name.split("/")) + self._remove_local_copy(installed, local_source, protected_sources) class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): diff --git a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py index f0be99b7f..409d0aa5b 100644 --- a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -133,3 +133,76 @@ def build(): if use_lockfile: self.assertEqual(lockfile.read_bytes(), original_lockfile) + + @parameterized.expand( + [ + (f"{runtime}_{path_type}_{mode}_{lock}", runtime, spec, mode == "shared", lock == "locked") + for runtime in NODEJS_RUNTIMES + for path_type, spec in [("file", "file:../shared"), ("bare", "../shared")] + for mode in ["individual", "shared"] + for lock in ["locked", "unlocked"] + ] + ) + def test_workspace_refreshes_hoisted_local_dependency(self, _name, runtime, spec, shared, locked): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp).resolve() + member = root / "function" + dependency = root / "shared" + artifacts = root / "artifacts" + scratch = root / "scratch" + for directory in (member, dependency, artifacts, scratch): + directory.mkdir() + (root / "package.json").write_text( + json.dumps({"name": "workspace-root", "version": "1.0.0", "private": True, "workspaces": ["function"]}), + encoding="utf-8", + ) + (member / "package.json").write_text( + json.dumps({"name": "test-function", "version": "1.0.0", "dependencies": {"local-shared": spec}}), + encoding="utf-8", + ) + (dependency / "package.json").write_text( + json.dumps({"name": "local-shared", "version": "1.0.0", "main": "index.js"}), encoding="utf-8" + ) + source = dependency / "index.js" + original = "module.exports = 'original';\n" + updated = "module.exports = 'updated';\n" + source.write_text(original, encoding="utf-8") + command = ["install", "--install-links", "--no-audit", "--no-fund"] + if not locked: + command.append("--no-package-lock") + SubprocessNpm(OSUtils()).run(command, cwd=str(root)) + lockfile = root / "package-lock.json" + original_lockfile = lockfile.read_bytes() if locked else None + flags = [EXPERIMENTAL_FLAG_NODEJS_MONOREPO] + + def build(): + builder = LambdaBuilder(language="nodejs", dependency_manager="npm", application_framework=None) + if shared: + builder.prepare_shared_project(str(root), experimental_flags=flags) + builder.build( + str(member), + str(artifacts), + str(scratch), + str(member / "package.json"), + runtime=runtime, + build_in_source=True, + download_dependencies=not shared, + experimental_flags=flags, + ) + + build() + installed = root / "node_modules" / "local-shared" / "index.js" + artifact = artifacts / "node_modules" / "local-shared" / "index.js" + self.assertFalse(installed.parent.is_symlink()) + self.assertFalse((member / "node_modules" / "local-shared").exists()) + self.assertEqual(installed.read_text(encoding="utf-8"), original) + self.assertEqual(artifact.read_text(encoding="utf-8"), original) + source.write_text(updated, encoding="utf-8") + build() + self.assertEqual(installed.read_text(encoding="utf-8"), updated) + self.assertEqual(artifact.read_text(encoding="utf-8"), updated) + self.assertEqual(source.read_text(encoding="utf-8"), updated) + if locked: + self.assertEqual(lockfile.read_bytes(), original_lockfile) + else: + self.assertFalse(lockfile.exists()) diff --git a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py index 11b93f697..69f92c1f1 100644 --- a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -331,3 +331,91 @@ def test_preserves_sources_from_overridden_declarations(tmp_path): assert installed.exists() assert nested_source.exists() npm.run.assert_called_once() + + +@pytest.mark.parametrize("shared", [False, True]) +@pytest.mark.parametrize("recorded_source", ["file:shared", "file:other", "https://example.invalid/pkg.tgz"]) +def test_workspace_refresh_requires_matching_installed_source(tmp_path, shared, recorded_source): + root = tmp_path.resolve() + member = make_package(root / "function") + (member / "package.json").write_text( + json.dumps({"name": "function", "dependencies": {"local": "file:../shared"}}), encoding="utf-8" + ) + (root / "package.json").write_text(json.dumps({"workspaces": ["function"]}), encoding="utf-8") + source = make_package(root / "shared") + installed = make_package(root / "node_modules" / "local") + unrelated = make_package(root / "node_modules" / "unrelated") + try: + (root / "node_modules" / "function").symlink_to(member, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + (root / "node_modules" / ".package-lock.json").write_text( + json.dumps( + { + "lockfileVersion": 3, + "packages": { + "node_modules/function": {"link": True, "resolved": "function"}, + "node_modules/local": {"resolved": recorded_source}, + }, + } + ), + encoding="utf-8", + ) + + npm = Mock() + npm.resolve_project_root.return_value = str(root) + + def run(command, **kwargs): + if command[0] == "pkg": + return json.dumps({"function": "function"}) + assert installed.exists() == (recorded_source != "file:shared") + assert source.exists() + assert unrelated.exists() + + npm.run.side_effect = run + action = NodejsNpmInstallAction(str(root if shared else member), npm, install_links=True, omit_dev=not shared) + action.execute() + expected_npm_calls = 2 + assert npm.run.call_count == expected_npm_calls + + +def test_workspace_refresh_preserves_another_members_local_source(tmp_path): + root = tmp_path.resolve() + member = make_package(root / "function") + sibling = make_package(root / "sibling") + source = make_package(root / "shared") + installed = make_package(root / "node_modules" / "local") + protected = make_package(installed / "nested-source") + (root / "package.json").write_text(json.dumps({"workspaces": ["function", "sibling"]}), encoding="utf-8") + (member / "package.json").write_text( + json.dumps({"name": "function", "dependencies": {"local": "../shared"}}), encoding="utf-8" + ) + (sibling / "package.json").write_text( + json.dumps({"name": "sibling", "devDependencies": {"protected": "../node_modules/local/nested-source"}}), + encoding="utf-8", + ) + try: + for directory in (member, sibling): + (root / "node_modules" / directory.name).symlink_to(directory, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + (root / "node_modules" / ".package-lock.json").write_text( + json.dumps( + { + "lockfileVersion": 3, + "packages": { + "node_modules/function": {"link": True, "resolved": "function"}, + "node_modules/sibling": {"link": True, "resolved": "sibling"}, + "node_modules/local": {"resolved": "file:shared"}, + }, + } + ), + encoding="utf-8", + ) + npm = Mock() + npm.resolve_project_root.return_value = str(root) + npm.run.return_value = json.dumps({"function": "function", "sibling": "sibling"}) + NodejsNpmUpdateAction(str(member), npm).execute() + assert installed.exists() + assert protected.exists() + assert source.exists() From 692c254be0caef397030e2ddf181c77b66840c4c Mon Sep 17 00:00:00 2001 From: Anish Nandamuri Date: Tue, 1 Dec 2026 14:22:25 -0500 Subject: [PATCH 4/4] refactor: separate npm workspace support into follow-up contribution --- .../workflows/nodejs_npm/actions.py | 248 ++++-------------- .../test_local_dependency_refresh.py | 73 ------ .../test_local_dependency_refresh.py | 88 ------- 3 files changed, 44 insertions(+), 365 deletions(-) diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index 9ce17ce6b..e5673ee20 100644 --- a/aws_lambda_builders/workflows/nodejs_npm/actions.py +++ b/aws_lambda_builders/workflows/nodejs_npm/actions.py @@ -106,19 +106,18 @@ def __init__(self, install_dir: str, subprocess_npm: SubprocessNpm, omit_dev: bo self.subprocess_npm = subprocess_npm self.omit_dev = omit_dev - @staticmethod - def _read_manifest(directory): + def _read_local_dependencies(self): + """Read the manifest once for active and protected dependencies.""" + manifest_path = os.path.join(self.install_dir, "package.json") + try: - with open(os.path.join(directory, "package.json"), encoding="utf-8-sig") as manifest_file: + with open(manifest_path, encoding="utf-8-sig") as manifest_file: manifest = json.load(manifest_file) - except (OSError, ValueError): + except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError): # Let npm handle missing or invalid manifests. - return None - return manifest if isinstance(manifest, dict) else None + return {}, [] - def _read_local_dependencies(self, manifest): - """Derive active and protected dependencies from one parsed manifest.""" - if manifest is None: + if not isinstance(manifest, dict): return {}, [] dependencies = {} @@ -181,213 +180,54 @@ def _paths_overlap(first, second): return common in (first, second) - @staticmethod - def _valid_dependency_name(name): - return ( - isinstance(name, str) - and re.fullmatch(r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", name) is not None - ) - - def _remove_local_copy(self, installed, local_source, protected_sources): - if local_source is None or not os.path.isdir(local_source): - return - if not os.path.isfile(os.path.join(local_source, "package.json")): - return - if not os.path.isdir(installed) or os.path.islink(installed): - return - if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): - return - if any(self._paths_overlap(installed, path) for path in protected_sources): - return - - LOG.debug("Refreshing local npm dependency: %s", installed) - try: - shutil.rmtree(installed) - except OSError as ex: - raise ActionFailedError(str(ex)) from ex - - def _workspace_root(self, install_dir, manifest): - """Find the nearest ancestor that declares npm workspaces.""" - root, root_manifest = install_dir, manifest - while not (root_manifest and root_manifest.get("workspaces")): - parent = os.path.dirname(root) - if parent == root: - return None, None - root = parent - root_manifest = self._read_manifest(root) - return root, root_manifest - - def _workspace_metadata(self, root, modules): - """Read the installed tree and ask npm for current workspace names.""" - hidden_lockfile = os.path.join(modules, ".package-lock.json") - if os.path.normcase(os.path.realpath(modules)) != os.path.normcase(modules): - return None - try: - if os.path.getmtime(hidden_lockfile) < os.path.getmtime(modules): - return None - with open(hidden_lockfile, encoding="utf-8-sig") as lockfile: - lock = json.load(lockfile) - if not isinstance(lock, dict) or lock.get("lockfileVersion") not in (2, 3): - return None - packages = lock.get("packages") - if not isinstance(packages, dict): - return None - # Let npm expand workspace patterns rather than duplicating its globbing rules. - names = json.loads(self.subprocess_npm.run(["pkg", "get", "name", "--workspaces", "--json"], cwd=root)) - except (OSError, ValueError, NpmExecutionError): - return None - return (packages, names) if isinstance(names, dict) and names else None - - def _workspace_member_path(self, root, modules, relative): - """Accept only a real member directory inside the workspace root.""" - if not isinstance(relative, str) or not relative or "\x00" in relative or os.path.isabs(relative): - return None - member = os.path.abspath(os.path.join(root, relative)) - try: - if os.path.commonpath([root, member]) != root or member == root: - return None - except ValueError: - return None - if self._paths_overlap(member, modules): - return None - if os.path.normcase(os.path.realpath(member)) != os.path.normcase(member): - return None - return member - - def _workspace_member(self, root, name, packages): - """Match npm's workspace name to its installed link and source path.""" - if not self._valid_dependency_name(name): - return None - entry = packages.get("node_modules/" + name) - if not isinstance(entry, dict) or entry.get("link") is not True: - return None - modules = os.path.join(root, "node_modules") - member = self._workspace_member_path(root, modules, entry.get("resolved")) - if member is None: - return None - link = os.path.join(modules, *name.split("/")) - if os.path.normcase(os.path.realpath(link)) != os.path.normcase(member): - return None - return member - - def _workspace_manifests(self, root, manifests, packages, names, current): - """Collect every member manifest, failing closed on uncertain membership.""" - for name in names: - member = self._workspace_member(root, name, packages) - if member is None: - return None - member_manifest = current[1] if member == current[0] else self._read_manifest(member) - if not member_manifest or member_manifest.get("name") != name: - return None - manifests[member] = member_manifest - return manifests - - def _recorded_local_source(self, root, entry): - if isinstance(entry, dict): - resolved = entry.get("resolved") - if isinstance(resolved, str) and resolved.startswith("file:"): - return self._local_dependency_source(root, resolved) - return None - - def _workspace_dependency_views(self, root, manifests, packages): - """Protect all declarations, even omitted ones, and recorded local sources.""" - active, protected = {}, [] - for directory, member_manifest in manifests.items(): - dependencies, specs = self._read_local_dependencies(member_manifest) - active[directory] = dependencies - protected.extend( - path for spec in specs if (path := self._local_dependency_source(directory, spec)) is not None - ) - for entry in packages.values(): - path = self._recorded_local_source(root, entry) - if path is not None: - protected.append(path) - return active, protected - - def _workspace_installed_copy(self, root, directory, name, source, packages): - """Find the nearest installed copy only if its recorded source matches.""" - location = directory - while True: - installed = os.path.join(location, "node_modules", *name.split("/")) - if os.path.lexists(installed): - key = os.path.relpath(installed, root).replace(os.sep, "/") - entry = packages.get(key) - if not isinstance(entry, dict) or entry.get("link"): - return None - actual = self._recorded_local_source(root, entry) - if actual is not None and os.path.normcase(actual) == os.path.normcase(source): - return installed - return None - if location == root: - return None - location = os.path.dirname(location) - - def _workspace_refresh_candidates(self, root, directories, active, packages): - candidates = {} - for directory in directories: - for name, spec in active[directory].items(): - if not self._valid_dependency_name(name): - continue - source = self._local_dependency_source(directory, spec) - if source is None: - continue - installed = self._workspace_installed_copy(root, directory, name, source, packages) - if installed is not None: - candidates[installed] = source - return candidates - - def _refresh_workspace_dependencies(self, install_dir, manifest): - """Use npm's installed tree to identify local copies in a workspace. - - Return False for ordinary projects. For workspaces, fail closed when - the installed lockfile or npm's workspace membership cannot identify - the exact copy. Never infer a hoisted package's source from its name. - """ - root, root_manifest = self._workspace_root(install_dir, manifest) - if root is None: - return False - if root != install_dir: - npm_root = self.subprocess_npm.resolve_project_root(self.install_dir) - if not isinstance(npm_root, str): - return True - if os.path.normcase(os.path.realpath(npm_root)) != os.path.normcase(root): - return False - metadata = self._workspace_metadata(root, os.path.join(root, "node_modules")) - if metadata is None: - return True - packages, names = metadata - # Seed only the root: membership must still be verified for the requested member. - manifests = self._workspace_manifests(root, {root: root_manifest}, packages, names, (install_dir, manifest)) - if manifests is None or install_dir not in manifests: - return True - active, protected = self._workspace_dependency_views(root, manifests, packages) - directories = manifests if install_dir == root else (install_dir,) - candidates = self._workspace_refresh_candidates(root, directories, active, packages) - # Resolve all candidates first; multiple members can share one hoisted copy. - for installed, source in candidates.items(): - self._remove_local_copy(installed, source, protected) - return True - def _refresh_local_dependencies(self): """Refresh installed copies of direct local directory dependencies.""" + dependencies, protected_specs = self._read_local_dependencies() install_dir = os.path.realpath(self.install_dir) - manifest = self._read_manifest(install_dir) - if self._refresh_workspace_dependencies(install_dir, manifest): - return - - dependencies, protected_specs = self._read_local_dependencies(manifest) modules_dir = os.path.join(install_dir, "node_modules") + protected_sources = [ path for spec in protected_specs if (path := self._local_dependency_source(install_dir, spec)) is not None ] + if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): return + for name, spec in dependencies.items(): - if not self._valid_dependency_name(name): - continue local_source = self._local_dependency_source(install_dir, spec) + + if local_source is None: + continue + + if not re.fullmatch( + r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", + name, + ): + continue + + if not os.path.isdir(local_source): + continue + + if not os.path.isfile(os.path.join(local_source, "package.json")): + continue + installed = os.path.join(modules_dir, *name.split("/")) - self._remove_local_copy(installed, local_source, protected_sources) + + if not os.path.isdir(installed) or os.path.islink(installed): + continue + + if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): + continue + + if any(self._paths_overlap(installed, path) for path in protected_sources): + continue + + LOG.debug("Refreshing local npm dependency: %s", name) + + try: + shutil.rmtree(installed) + except OSError as ex: + raise ActionFailedError(str(ex)) from ex class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): diff --git a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py index 409d0aa5b..f0be99b7f 100644 --- a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -133,76 +133,3 @@ def build(): if use_lockfile: self.assertEqual(lockfile.read_bytes(), original_lockfile) - - @parameterized.expand( - [ - (f"{runtime}_{path_type}_{mode}_{lock}", runtime, spec, mode == "shared", lock == "locked") - for runtime in NODEJS_RUNTIMES - for path_type, spec in [("file", "file:../shared"), ("bare", "../shared")] - for mode in ["individual", "shared"] - for lock in ["locked", "unlocked"] - ] - ) - def test_workspace_refreshes_hoisted_local_dependency(self, _name, runtime, spec, shared, locked): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp).resolve() - member = root / "function" - dependency = root / "shared" - artifacts = root / "artifacts" - scratch = root / "scratch" - for directory in (member, dependency, artifacts, scratch): - directory.mkdir() - (root / "package.json").write_text( - json.dumps({"name": "workspace-root", "version": "1.0.0", "private": True, "workspaces": ["function"]}), - encoding="utf-8", - ) - (member / "package.json").write_text( - json.dumps({"name": "test-function", "version": "1.0.0", "dependencies": {"local-shared": spec}}), - encoding="utf-8", - ) - (dependency / "package.json").write_text( - json.dumps({"name": "local-shared", "version": "1.0.0", "main": "index.js"}), encoding="utf-8" - ) - source = dependency / "index.js" - original = "module.exports = 'original';\n" - updated = "module.exports = 'updated';\n" - source.write_text(original, encoding="utf-8") - command = ["install", "--install-links", "--no-audit", "--no-fund"] - if not locked: - command.append("--no-package-lock") - SubprocessNpm(OSUtils()).run(command, cwd=str(root)) - lockfile = root / "package-lock.json" - original_lockfile = lockfile.read_bytes() if locked else None - flags = [EXPERIMENTAL_FLAG_NODEJS_MONOREPO] - - def build(): - builder = LambdaBuilder(language="nodejs", dependency_manager="npm", application_framework=None) - if shared: - builder.prepare_shared_project(str(root), experimental_flags=flags) - builder.build( - str(member), - str(artifacts), - str(scratch), - str(member / "package.json"), - runtime=runtime, - build_in_source=True, - download_dependencies=not shared, - experimental_flags=flags, - ) - - build() - installed = root / "node_modules" / "local-shared" / "index.js" - artifact = artifacts / "node_modules" / "local-shared" / "index.js" - self.assertFalse(installed.parent.is_symlink()) - self.assertFalse((member / "node_modules" / "local-shared").exists()) - self.assertEqual(installed.read_text(encoding="utf-8"), original) - self.assertEqual(artifact.read_text(encoding="utf-8"), original) - source.write_text(updated, encoding="utf-8") - build() - self.assertEqual(installed.read_text(encoding="utf-8"), updated) - self.assertEqual(artifact.read_text(encoding="utf-8"), updated) - self.assertEqual(source.read_text(encoding="utf-8"), updated) - if locked: - self.assertEqual(lockfile.read_bytes(), original_lockfile) - else: - self.assertFalse(lockfile.exists()) diff --git a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py index 69f92c1f1..11b93f697 100644 --- a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -331,91 +331,3 @@ def test_preserves_sources_from_overridden_declarations(tmp_path): assert installed.exists() assert nested_source.exists() npm.run.assert_called_once() - - -@pytest.mark.parametrize("shared", [False, True]) -@pytest.mark.parametrize("recorded_source", ["file:shared", "file:other", "https://example.invalid/pkg.tgz"]) -def test_workspace_refresh_requires_matching_installed_source(tmp_path, shared, recorded_source): - root = tmp_path.resolve() - member = make_package(root / "function") - (member / "package.json").write_text( - json.dumps({"name": "function", "dependencies": {"local": "file:../shared"}}), encoding="utf-8" - ) - (root / "package.json").write_text(json.dumps({"workspaces": ["function"]}), encoding="utf-8") - source = make_package(root / "shared") - installed = make_package(root / "node_modules" / "local") - unrelated = make_package(root / "node_modules" / "unrelated") - try: - (root / "node_modules" / "function").symlink_to(member, target_is_directory=True) - except OSError: - pytest.skip("Directory symlinks unavailable") - (root / "node_modules" / ".package-lock.json").write_text( - json.dumps( - { - "lockfileVersion": 3, - "packages": { - "node_modules/function": {"link": True, "resolved": "function"}, - "node_modules/local": {"resolved": recorded_source}, - }, - } - ), - encoding="utf-8", - ) - - npm = Mock() - npm.resolve_project_root.return_value = str(root) - - def run(command, **kwargs): - if command[0] == "pkg": - return json.dumps({"function": "function"}) - assert installed.exists() == (recorded_source != "file:shared") - assert source.exists() - assert unrelated.exists() - - npm.run.side_effect = run - action = NodejsNpmInstallAction(str(root if shared else member), npm, install_links=True, omit_dev=not shared) - action.execute() - expected_npm_calls = 2 - assert npm.run.call_count == expected_npm_calls - - -def test_workspace_refresh_preserves_another_members_local_source(tmp_path): - root = tmp_path.resolve() - member = make_package(root / "function") - sibling = make_package(root / "sibling") - source = make_package(root / "shared") - installed = make_package(root / "node_modules" / "local") - protected = make_package(installed / "nested-source") - (root / "package.json").write_text(json.dumps({"workspaces": ["function", "sibling"]}), encoding="utf-8") - (member / "package.json").write_text( - json.dumps({"name": "function", "dependencies": {"local": "../shared"}}), encoding="utf-8" - ) - (sibling / "package.json").write_text( - json.dumps({"name": "sibling", "devDependencies": {"protected": "../node_modules/local/nested-source"}}), - encoding="utf-8", - ) - try: - for directory in (member, sibling): - (root / "node_modules" / directory.name).symlink_to(directory, target_is_directory=True) - except OSError: - pytest.skip("Directory symlinks unavailable") - (root / "node_modules" / ".package-lock.json").write_text( - json.dumps( - { - "lockfileVersion": 3, - "packages": { - "node_modules/function": {"link": True, "resolved": "function"}, - "node_modules/sibling": {"link": True, "resolved": "sibling"}, - "node_modules/local": {"resolved": "file:shared"}, - }, - } - ), - encoding="utf-8", - ) - npm = Mock() - npm.resolve_project_root.return_value = str(root) - npm.run.return_value = json.dumps({"function": "function", "sibling": "sibling"}) - NodejsNpmUpdateAction(str(member), npm).execute() - assert installed.exists() - assert protected.exists() - assert source.exists()