diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index bf2f1bc17..1e0ae103f 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 @@ -104,6 +106,302 @@ 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): + try: + with open(os.path.join(directory, "package.json"), encoding="utf-8-sig") as manifest_file: + manifest = json.load(manifest_file) + except (OSError, ValueError): + # Let npm handle missing or invalid manifests. + return None + return manifest if isinstance(manifest, dict) else None + + def _read_local_dependencies(self, manifest): + """Derive active and protected dependencies from one parsed manifest.""" + if manifest is None: + return {}, [] + + dependencies = {} + protected_specs = [] + + for section in ("devDependencies", "dependencies", "optionalDependencies"): + entries = manifest.get(section, {}) + 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, 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 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() + + try: + common = os.path.commonpath([first, second]) + except ValueError: + return False + + 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): + LOG.debug("Skipping workspace metadata: node_modules resolves to another path") + return None + try: + # Like npm, distrust the hidden lockfile when node_modules is newer. + # Manual changes can invalidate this metadata until the next npm install. + if os.path.getmtime(hidden_lockfile) < os.path.getmtime(modules): + LOG.debug("Skipping workspace metadata: hidden lockfile is stale") + 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): + LOG.debug("Skipping workspace metadata: unsupported hidden lockfile format") + return None + packages = lock.get("packages") + if not isinstance(packages, dict): + LOG.debug("Skipping workspace metadata: invalid packages mapping") + 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) as ex: + LOG.debug("Skipping workspace metadata: %s", type(ex).__name__) + return None + valid_names = isinstance(names, dict) and bool(names) + if not valid_names: + LOG.debug("Skipping workspace metadata: npm returned no valid workspace names") + return (packages, names) if valid_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): + LOG.debug("Skipping workspace refresh: npm project root could not be resolved") + 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: + LOG.debug("Skipping workspace refresh: installed metadata could not be verified") + 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: + LOG.debug("Skipping workspace refresh: workspace membership could not be verified") + 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.""" + 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) + installed = os.path.join(modules_dir, *name.split("/")) + self._remove_local_copy(installed, local_source, protected_sources) + class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): """ @@ -146,6 +444,7 @@ def execute(self): 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) @@ -176,6 +475,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..9be34ca61 --- /dev/null +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,232 @@ +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, +) + + +class TestLocalDependencyRefresh(TestCase): + + def _assert_dependency_layout(self, installed_package, dependency): + if installed_package.is_symlink(): + self.assertEqual(installed_package.resolve(), dependency.resolve()) + else: + self.assertNotEqual(installed_package.resolve(), dependency.resolve()) + + def _assert_before_rebuild(self, installed, artifact, original, updated): + # Linked dependencies reflect source edits immediately. + expected = updated if installed.parent.is_symlink() else original + self.assertEqual(installed.read_text(encoding="utf-8"), expected) + + # In-source artifacts may link to the installed dependency. + # Independent copies must still contain the original content. + artifact_expected = expected if artifact.samefile(installed) else original + self.assertEqual(artifact.read_text(encoding="utf-8"), artifact_expected) + + @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" + + 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" + + original = "module.exports = 'original';\\n" + updated = "module.exports = 'updated';\\n" + + dependency_source.write_text(original, encoding="utf-8") + + manifest = source_dir / "package.json" + manifest.write_text( + json.dumps( + { + "name": "test-function", + "version": "1.0.0", + "dependencies": {"local-dependency": spec}, + } + ), + 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() + + 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) + + 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" + installed_package = installed.parent + + self._assert_dependency_layout(installed_package, dependency) + 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") + + self._assert_before_rebuild(installed, artifact, original, updated) + + build() + + self._assert_dependency_layout(installed_package, dependency) + + 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 new file mode 100644 index 000000000..69f92c1f1 --- /dev/null +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,421 @@ +import json +from unittest.mock import Mock + +import pytest + +from aws_lambda_builders.workflows.nodejs_npm.actions import ( + NodejsNpmInstallAction, + 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), + ], +) +@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() + + 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: spec}}, + 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"]) +@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") + make_package(tmp_path / "local") + + manifest = { + "dependencies": { + "local-dependency": "file:../local", + } + } + + manifest.setdefault(section, {})["other"] = prefix + "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() + + +@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() + + +@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()