diff --git a/docs/detectors/pnpm-version-support.md b/docs/detectors/pnpm-version-support.md new file mode 100644 index 000000000..328030f65 --- /dev/null +++ b/docs/detectors/pnpm-version-support.md @@ -0,0 +1,88 @@ +# pnpm v10-v12 detector support tracker + +**Status:** Initial research recorded November 18, 2026. Registry-qualified version handling and pnpm-managed runtime skipping are implemented; broader compatibility fixtures are pending. + +**Goal:** Detect resolved npm dependencies from pnpm v10, v11, and v12 standalone projects and workspaces that use lockfile schema `9.0`, including lockfile-recorded config and package-manager dependencies. The opt-in `13.0` schema is out of scope. Preserve existing lockfile v5, v6, and v9 behavior. This is a static scan: do not run pnpm, execute hooks, or resolve missing versions against a registry. + +## Current baseline + +The [Pnpm detector](pnpm.md) dispatches on **lockfile schema**, not the pnpm CLI major. It recognizes schemas 5, 6, and 9 and searches `pnpm-lock.yaml` and legacy `shrinkwrap.yaml`. It does not read `pnpm-workspace.yaml` directly; workspace detection uses the resolved projects in the lockfile's `importers`. + +The [schema 9 parser](../../src/Microsoft.ComponentDetection.Detectors/pnpm/Pnpm9Detector.cs) builds the graph from `importers` and `snapshots`, including the two-document layout when both documents declare `9.0`. It reads optional roots, but the shared [snapshot model](../../src/Microsoft.ComponentDetection.Detectors/pnpm/Contracts/Package.cs) has no `optionalDependencies` edges. It does not read `resolution` metadata, so nested resolution shapes parse. The [version reader](../../src/Microsoft.ComponentDetection.Detectors/pnpm/ParsingUtilities/PnpmParsingUtilitiesFactory.cs) rejects different version strings across documents before graph parsing. Existing multi-document tests use synthetic examples; recognizing a schema number is not evidence that every CLI release or feature works. + +## pnpm v10: schema 9.0 with new dependency forms + +The [v10 lockfile writer][v10-writer] still emits [`9.0`][v10-schema] with `importers`, `packages`, and `snapshots`. Keep the schema 9 parser and test the newer entries that can appear inside it. + +| Change | Detector impact | +| --- | --- | +| [v10.0][v10-release] switches long peer suffixes and patch/checksum fields to SHA-256, manages the pinned pnpm version by default, and blocks dependency lifecycle scripts by default. | Match full snapshot keys without assuming a hash algorithm. Keep peer and patch context for edges without making it part of the npm component version. Build approval and package-manager switching do not require re-running install logic. | +| v10.0 changes workspace linking and requires injected workspace packages for the new `deploy` flow. It also drops automatic conversion from lockfile v6. | Cover external dependencies reached through injected workspace packages; preserve the scanner's independent v6 reader. | +| [Config dependencies][v10-config] are pinned as `version+integrity` in `pnpm-workspace.yaml`. | They can be absent from `pnpm-lock.yaml` and are invisible to the current detector. Decide whether to add a narrow manifest reader for these exact pins; do not treat arbitrary catalog ranges or overrides as installed packages. | +| [v10.9 adds `jsr:`][v10-year]; [v10.12.1 adds catalog modes][v10-catalogs]. | Verify how JSR and npm aliases resolve in the lockfile. Use the actual locked target for `catalog:` dependencies, not the alias or the catalog range. | +| [v10.14][v10-runtime] locks Node.js, Deno, and Bun from `devEngines.runtime`; [v10.21][v10-transitive-runtime] also installs Node.js for dependencies' `engines.runtime`. | **Done:** `@runtime:` entries are skipped, including direct and transitive references, and their nested `variations` resolutions parse. | + +## pnpm v11: schema 9.0 with an environment document + +- The [v11.0.0 constant][v11-schema] remains `9.0`. The [release notes][v11-release] move config-dependency resolutions and integrity out of `pnpm-workspace.yaml` into an optional first YAML document. It also contains resolved pnpm pins (`packageManagerDependencies`), including versions selected from a `devEngines.packageManager` range. The last document contains the project graph. The [v11 writer][v11-env] initializes the environment document with `9.0`; [upstream compatibility tests][v11-env-tests] also use the nonnumeric `env-1.0` marker. Treat that marker as a fixture candidate for a recognized environment shape, not the default v11 output. +- The [v11.0 release][v11-release] moves general project settings into `pnpm-workspace.yaml`, adds scoped `registries` and per-project `packageConfigs`, replaces the old build-approval settings with `allowBuilds`, and introduces `dedupePeers`, which can shorten nested peer suffixes. [v11.2][v11-optional] includes one level of config-package optional dependencies and records all platform variants. Test both peer forms and optional edges; do not simulate settings, registry access, or build policies. +- [Named registry support][v11-sources] adds dependency aliases in v11.1, and [v11.20][registry-keys] uses registry-qualified keys (`name@registry:version`). [v11.25][v11-revisions] adds registry revisions, and [v11.26][v11-workspace-catalogs] allows `workspace:` ranges in catalogs. Preserve source distinctions for graph lookup and verify component identity separately. +- [Upstream runtime examples][runtime-shapes] record entries like `node@runtime:22.0.0` and nest platform variants under `resolution`. **Done:** the parser no longer reads `resolution`, so these entries don't stop the rest of the npm graph from being reported, and runtime entries are skipped. + +## pnpm v12: schema 9.0 + +[pnpm v12.0][v12-release] switches the CLI to Rust but [retains schema 9.0][v12-schema]. Treat it as another writer to test, not a reason to route on the CLI major. Upstream's [release listing][releases] shows `12.22.0` as the current v12 release as of this research. + +| Change | Detector impact | +| --- | --- | +| v12.0 adds registry revisions (`resolution.revision`, with `+rN` pins) and can manage other package managers and runtimes. [v12.13][package-sources] adds `tool:` but still writes `runtime:` in the lockfile. [v12.15][v12-includes] adds `lockfile.integrityTarget: tar` and tar registries. | Verify that revision and integrity metadata do not change npm identity accidentally. **Done:** resolution metadata is not read, and `runtime:` tools, including Yarn 6, are skipped instead of being labeled as npm packages. | +| [v12.2-v12.3][v12-workspace-catalogs] adds `workspace:` support inside catalogs; [v12.6][v12-local-catalogs] adds `file:` and `link:`. [v12.7][v12-workspaces] can create `pnpm-workspace.yaml` from `package.json` workspace globs. [v12.12][v12-config] supports saving config-dependency ranges, and v12.15 can delegate named settings via `include`. | Test locked external dependencies of linked and injected projects, and use the exact environment resolution for config dependencies. Do not follow includes or infer dependencies from workspace globs when the lockfile already supplies the graph. | +| [v12.4][v12-polyglot] manages Cargo and Python in the same workspace but retains their separate `Cargo.lock` and `pylock.toml`. | Keep ecosystem attribution separate. Track any missing Cargo/Python coverage with the respective detectors. | +| [v12.16][v12-registry-keys] consistently uses registry-qualified keys for a registry with a prefix. [v12.18][v12-variants] adds platform variants for npm packages served by pnpr, not just for runtime binaries. | Keep registry-qualified graph keys and export the bare semantic version. **Done:** packages with nested variant resolutions parse and are reported as npm packages. | + +[v12.19][v12-next] also introduced experimental `lockfile.format: v13`. That format remains unsupported. + +## Implementation and verification + +- [x] Compare release notes and tagged upstream writers with the local dispatch, graph model, and existing tests. +- [x] Fix the v12 schema 9 regression where a named-registry key such as `sample@my-registry:0.1.12` exported `my-registry:0.1.12` instead of `0.1.12`, which Governance rejected. Retain the full key for direct and transitive lookups and preserve pnpm protocol prefixes that are not [registry aliases][registry-aliases]. +- [x] Skip pnpm-managed runtimes and tools (`@runtime:`) instead of reporting them as npm packages with an invalid `runtime:` version. Stop reading `resolution` so nested `variations` resolutions from runtimes and pnpr variant packages no longer fail the whole lockfile. +- [ ] Generate minimal standalone and multi-project fixtures, starting with pnpm `10.31.0`, `11.0.0`, `11.28.13`, `12.0.0`, and `12.22.0`. Record the producer, settings, and expected graph with each fixture; commit the resulting inputs so detector tests can run offline. Include shared and per-project locks (`sharedWorkspaceLockfile: false`). +- [ ] Extend the existing schema 9 parser where fixtures show gaps: optional transitive edges, aliases, and peer/patch-aware lookups. Cover the v10 manifest-only config pin if in scope. Keep ordinary npm component IDs and direct/dev attribution stable. +- [ ] Make document selection role-aware: parse the project version from the last document, validate and read a recognized environment document separately, and register config and manager dependencies without joining unrelated snapshot edges across documents. Verify whether to support an environment-only file: the upstream writer can leave the project document empty before the first full install. Reject extra documents and arbitrary mixed schemas. +- [ ] Add targeted graph assertions to [PnpmDetectorTests](../../test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs) and end-to-end inputs under [verification resources](../../test/Microsoft.ComponentDetection.VerificationTests/resources/pnpm). Assert identities, direct/transitive and optional edges, production winning over dev when both are reachable, and no loss of ordinary npm packages in mixed inputs. Retain v5/v6/v9 regressions and bump the `Pnpm` detector result version when output changes. + +**Next implementation slice:** Verify schema 9 compatibility on v10, v11, and default v12 output. Track workspace-only declarations, alternate lockfile paths such as branch lockfiles, and inventory of non-npm tools separately unless the fixture work makes them essential. + +[v10-release]: https://github.com/pnpm/pnpm/releases/tag/v10.0.0 +[v10-writer]: https://github.com/pnpm/pnpm/blob/v10.31.0/lockfile/fs/src/lockfileFormatConverters.ts +[v10-schema]: https://github.com/pnpm/pnpm/blob/v10.31.0/packages/constants/src/index.ts +[v10-config]: https://pnpm.io/10.x/config-dependencies +[v10-year]: https://pnpm.io/blog/2025/12/29/pnpm-in-2025 +[v10-catalogs]: https://github.com/pnpm/pnpm/releases/tag/v10.12.1 +[v10-runtime]: https://pnpm.io/blog/releases/10.14 +[v10-transitive-runtime]: https://pnpm.io/blog/releases/10.21 +[v11-release]: https://pnpm.io/blog/releases/11.0 +[v11-schema]: https://github.com/pnpm/pnpm/blob/v11.0.0/core/constants/src/index.ts +[v11-env]: https://github.com/pnpm/pnpm/blob/v11.0.0/lockfile/fs/src/envLockfile.ts +[v11-env-tests]: https://github.com/pnpm/pnpm/blob/v11.0.0/lockfile/fs/test/write.test.ts +[v11-optional]: https://pnpm.io/blog/releases/11.2 +[v11-sources]: https://pnpm.io/blog/releases/11.1 +[registry-keys]: https://pnpm.io/blog/releases/11.20 +[v11-revisions]: https://pnpm.io/blog/releases/11.25 +[v11-workspace-catalogs]: https://pnpm.io/blog/releases/11.26 +[runtime-shapes]: https://github.com/pnpm/pacquet/issues/437 +[v12-release]: https://github.com/pnpm/pnpm/releases/tag/v12.0.0 +[v12-schema]: https://github.com/pnpm/pnpm/blob/v12.0.0/pnpm/crates/lockfile/src/lib.rs +[releases]: https://github.com/pnpm/pnpm/releases +[v12-workspace-catalogs]: https://pnpm.io/blog/releases/12.2-12.3 +[v12-polyglot]: https://pnpm.io/blog/releases/12.4 +[v12-local-catalogs]: https://pnpm.io/blog/releases/12.6 +[v12-workspaces]: https://pnpm.io/blog/releases/12.7 +[v12-config]: https://pnpm.io/blog/releases/12.12.0 +[package-sources]: https://pnpm.io/package-sources +[v12-includes]: https://pnpm.io/blog/releases/12.15.0 +[v12-registry-keys]: https://pnpm.io/blog/releases/12.16.0 +[v12-variants]: https://pnpm.io/blog/releases/12.18.0 +[v12-next]: https://pnpm.io/blog/releases/12.19.0 +[registry-aliases]: https://github.com/pnpm/pnpm/blob/v12.22.0/pnpm/crates/deps-path/src/registry_qualified.rs diff --git a/docs/detectors/pnpm.md b/docs/detectors/pnpm.md index d6ee5aa0a..af6a46463 100644 --- a/docs/detectors/pnpm.md +++ b/docs/detectors/pnpm.md @@ -9,6 +9,8 @@ Pnpm detection relies on the presence of lockfiles generated by the pnpm package The detector supports lockfile versions 5, 6, and 9, with version 9 being the maximum supported version. +For the distinction between lockfile schemas and pnpm CLI releases, and for planned support, see the [pnpm v10-v12 support tracker](pnpm-version-support.md). + Lockfiles can contain one or two YAML documents. When an environment document is present, it comes before the project document. Both documents are scanned so that config and package-manager dependencies are included alongside project dependencies. @@ -62,10 +64,20 @@ Pnpm supports both single-package projects ("dedicated shrinkwrap") and multi-pa 2. **HTTP/HTTPS dependencies**: In version 9, dependencies referenced via `http:` or `https:` protocols are also skipped as they are treated similarly to local dependencies -3. **Lockfile version support**: Only versions 5, 6, and 9 are supported. If an unsupported version is detected, the file will be skipped and a warning will be logged +3. **pnpm-managed runtimes are skipped**: pnpm 10.14 and later can download Node.js, Deno, and Bun, and pnpm 12 can also download Yarn 6. These are recorded in the lockfile as `@runtime:` entries. They are not npm packages, so the detector does not report them. The rest of the dependency graph, including packages that depend on a runtime, is still detected. + + Example of ignored entries: + ```yaml + devDependencies: + node: + specifier: runtime:^22.0.0 + version: runtime:22.0.0 + ``` + +4. **Lockfile version support**: Only versions 5, 6, and 9 are supported. If an unsupported version is detected, the file will be skipped and a warning will be logged -4. **Version 9 dev dependency detection**: Lockfile version 9 removed the metadata that explicitly marks packages as dev dependencies. The detector relies on the dependency tree structure to determine dev dependency status, which may be less accurate in complex scenarios +5. **Version 9 dev dependency detection**: Lockfile version 9 removed the metadata that explicitly marks packages as dev dependencies. The detector relies on the dependency tree structure to determine dev dependency status, which may be less accurate in complex scenarios -5. **Pnpm dependency path complexity**: Pnpm uses specialized dependency paths that include peer dependency information and other metadata. While the detector handles standard cases, highly complex dependency scenarios with multiple peer dependencies may not be perfectly represented +6. **Pnpm dependency path complexity**: Pnpm uses specialized dependency paths that include peer dependency information and other metadata. While the detector handles standard cases, highly complex dependency scenarios with multiple peer dependencies may not be perfectly represented -6. **Automatic root dependency calculation required**: The detector sets `NeedsAutomaticRootDependencyCalculation = true`, indicating that the orchestrator must perform additional analysis to determine root-level dependencies +7. **Automatic root dependency calculation required**: The detector sets `NeedsAutomaticRootDependencyCalculation = true`, indicating that the orchestrator must perform additional analysis to determine root-level dependencies diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/Contracts/Package.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/Contracts/Package.cs index 5fb589a23..d1fcb37e1 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/Contracts/Package.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/Contracts/Package.cs @@ -15,7 +15,7 @@ public class Package [YamlMember(Alias = "name")] public string Name { get; set; } - [YamlMember(Alias = "resolution")] + [YamlIgnore] public Dictionary Resolution { get; set; } [YamlMember(Alias = "version")] diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/IPnpmDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/IPnpmDetector.cs index bc10e9b86..68b14f1d6 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/IPnpmDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/IPnpmDetector.cs @@ -26,4 +26,9 @@ public static class PnpmConstants public const string PnpmLinkDependencyPath = "link:"; public const string PnpmHttpDependencyPath = "http:"; public const string PnpmHttpsDependencyPath = "https:"; + + /// + /// Prefix pnpm writes for runtimes and tools it downloads itself, such as node@runtime:22.0.0. These are not npm packages. + /// + public const string PnpmRuntimeDependencyPath = "runtime:"; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/ParsingUtilities/PnpmV9ParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/ParsingUtilities/PnpmV9ParsingUtilities.cs index 501893539..cdcc12995 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/ParsingUtilities/PnpmV9ParsingUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/ParsingUtilities/PnpmV9ParsingUtilities.cs @@ -1,6 +1,8 @@ #nullable disable namespace Microsoft.ComponentDetection.Detectors.Pnpm; +using System.Linq; +using global::NuGet.Versioning; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; @@ -21,7 +23,7 @@ public override DetectedComponent CreateDetectedComponentFromPnpmPath(string pnp // An example of a dependency path with these: /webpack-cli@4.10.0(webpack-bundle-analyzer@4.10.1)(webpack-dev-server@4.6.0)(webpack@5.89.0) (var fullPackageName, var packageVersion) = this.ExtractNameAndVersionFromPnpmPackagePath(pnpmPackagePath); - return new DetectedComponent(new NpmComponent(fullPackageName, packageVersion)); + return new DetectedComponent(new NpmComponent(fullPackageName, GetComponentVersion(packageVersion))); } public override (string FullPackageName, string PackageVersion) ExtractNameAndVersionFromPnpmPackagePath(string pnpmPackagePath) @@ -69,4 +71,27 @@ public override string ReconstructPnpmDependencyPath(string dependencyName, stri return $"{dependencyName}@{dependencyVersion}"; } } + + private static string GetComponentVersion(string packageVersion) + { + var separator = packageVersion.IndexOf(':'); + if (separator <= 0 || !char.IsAsciiLetter(packageVersion[0])) + { + return packageVersion; + } + + var prefix = packageVersion[..separator]; + + // These pnpm protocol prefixes cannot be named registry aliases. + if (prefix is "bitbucket" or "catalog" or "custom" or "file" or "git" or "github" or "gitlab" + or "http" or "https" or "jsr" or "link" or "npm" or "pkg" or "runtime" or "ssh" or "tool" or "workspace" + || !prefix.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) + { + return packageVersion; + } + + // Only normalize the exported version; snapshot lookups still use the full key. + var version = packageVersion[(separator + 1)..]; + return SemanticVersion.TryParse(version, out _) ? version : packageVersion; + } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/Pnpm9Detector.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/Pnpm9Detector.cs index 1ee378222..c982eee81 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/Pnpm9Detector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/Pnpm9Detector.cs @@ -30,9 +30,9 @@ public void RecordDependencyGraphFromFile(string yamlFileContent, ISingleFileCom { foreach (var (pnpmDependencyPath, package) in yaml.Snapshots ?? Enumerable.Empty>()) { - // Ignore "file:" as these are local packages. - // Such local packages should only be referenced at the top level (via ProcessDependencyList) which also skips them or from other local packages (which this skips). - // There should be no cases where a non-local package references a local package, so skipping them here should not result in failed lookups below when adding all the graph references. + // Do not register local packages ("file:", "link:"), URL references, or pnpm-managed runtimes ("runtime:") as npm packages. + // Keep these entries in components for importer lookups, while skipping their registration below. + // Ordinary packages can reference runtimes, so ProcessIndirectDependencies must also skip runtime edges. var (packageName, packageVersion) = this.pnpmParsingUtilities.ExtractNameAndVersionFromPnpmPackagePath(pnpmDependencyPath); var isFileOrLink = this.IsFileOrLink(packageVersion) || this.IsFileOrLink(pnpmDependencyPath); @@ -114,7 +114,7 @@ private void ProcessDependencyList(ISingleFileComponentRecorder singleFileCompon // Lockfile v9 apparently removed the tagging of dev dependencies in the lockfile, so we revert to using the dependency tree to establish dev dependency state. // At this point, the root dependencies are marked according to which dependency group they are declared in the lockfile itself. - // Ignore "file:" and "link:" as these are local packages. + // Ignore local packages, URL references, and pnpm-managed runtimes. if (!isFileOrLink) { singleFileComponentRecorder.RegisterUsage(component, isExplicitReferencedDependency: true, isDevelopmentDependency: isDevelopmentDependency); @@ -130,7 +130,8 @@ private bool IsFileOrLink(string packagePath) return packagePath.StartsWith(PnpmConstants.PnpmLinkDependencyPath) || packagePath.StartsWith(PnpmConstants.PnpmFileDependencyPath) || packagePath.StartsWith(PnpmConstants.PnpmHttpDependencyPath) || - packagePath.StartsWith(PnpmConstants.PnpmHttpsDependencyPath); + packagePath.StartsWith(PnpmConstants.PnpmHttpsDependencyPath) || + packagePath.StartsWith(PnpmConstants.PnpmRuntimeDependencyPath); } private void ProcessIndirectDependencies(ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary components, string parentComponentId, Dictionary dependencies, bool isDevDependency, HashSet seenDependencies) @@ -138,7 +139,7 @@ private void ProcessIndirectDependencies(ISingleFileComponentRecorder singleFile // Now that the `components` dictionary is populated, make another pass of all components, registering all the dependency edges in the graph. foreach (var (name, version) in dependencies ?? Enumerable.Empty>()) { - // Ignore "file:" and "link:" as these are local packages. + // Ignore local packages, URL references, and pnpm-managed runtimes. if (this.IsFileOrLink(version)) { continue; diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs index 9e8937f86..6f52bd497 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs @@ -42,7 +42,7 @@ public PnpmComponentDetectorFactory( public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Npm]; - public override int Version { get; } = 9; + public override int Version { get; } = 10; public override bool NeedsAutomaticRootDependencyCalculation => true; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs index 5dfee6a20..8e9605d75 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs @@ -717,6 +717,112 @@ public async Task TestPnpmDetector_V9_GoodLockVersion_ParsesAliasedDependency() parentComponent => parentComponent.Name == "sampleDependency"); } + [TestMethod] + public async Task TestPnpmDetector_V9_RegistryQualifiedVersionsPreserveDependencyGraphAsync() + { + var yamlFile = """ + lockfileVersion: '9.0' + importers: + .: + dependencies: + '@example/client': + specifier: ^0.1.0 + version: my-registry:0.1.12(peer@1.0.0) + snapshots: + '@example/client@my-registry:0.1.12(peer@1.0.0)': + dependencies: + child-alias: child@other_registry:2.0.0-beta.1+build.5 + '@example/client@0.1.12(peer@1.0.0)': + dependencies: + unrelated: 3.0.0 + child@other_registry:2.0.0-beta.1+build.5: {} + unrelated@3.0.0: {} + """; + + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile("pnpm-lock.yaml", yamlFile) + .ExecuteDetectorAsync(); + + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + + var npmComponents = componentRecorder.GetDetectedComponents().Select(x => (NpmComponent)x.Component).ToList(); + npmComponents.Should().HaveCount(3); + var client = npmComponents.Should().ContainSingle(x => x.Name == "@example/client" && x.Version == "0.1.12").Subject; + var child = npmComponents.Should().ContainSingle(x => x.Name == "child" && x.Version == "2.0.0-beta.1+build.5").Subject; + var graph = componentRecorder.GetDependencyGraphsByLocation().Values.Single(); + graph.IsComponentExplicitlyReferenced(client.Id).Should().BeTrue(); + graph.GetDependenciesForComponent(client.Id).Should().ContainSingle().Which.Should().Be(child.Id); + } + + [TestMethod] + public async Task TestPnpmDetector_V9_RuntimeEntriesAreSkippedAndVariationsResolutionsParseAsync() + { + var yamlFile = """ + lockfileVersion: '9.0' + importers: + .: + dependencies: + cli-with-engine: + specifier: 1.0.0 + version: 1.0.0 + native-addon: + specifier: 1.0.0 + version: 1.0.0 + devDependencies: + node: + specifier: runtime:^22.0.0 + version: runtime:22.0.0 + packages: + cli-with-engine@1.0.0: + resolution: {integrity: sha512-AAAA} + helper@2.0.0: + resolution: {integrity: sha512-BBBB} + native-addon@1.0.0: + resolution: + type: variations + variants: + - resolution: {integrity: sha512-CCCC, tarball: https://registry.example/native-addon/-/native-addon-1.0.0~linux-x64.tgz} + targets: [{os: linux, cpu: x64}] + node@runtime:22.0.0: + hasBin: true + resolution: + type: variations + variants: + - resolution: + archive: tarball + bin: + node: bin/node + integrity: sha256-DDDD + type: binary + url: https://nodejs.org/download/release/v22.0.0/node-v22.0.0-linux-x64.tar.gz + targets: + - cpu: x64 + os: linux + version: 22.0.0 + snapshots: + cli-with-engine@1.0.0: + dependencies: + helper: 2.0.0 + node: runtime:22.0.0 + helper@2.0.0: {} + native-addon@1.0.0: {} + node@runtime:22.0.0: {} + """; + + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile("pnpm-lock.yaml", yamlFile) + .ExecuteDetectorAsync(); + + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + + var npmComponents = componentRecorder.GetDetectedComponents().Select(x => (NpmComponent)x.Component).ToList(); + npmComponents.Select(x => $"{x.Name}@{x.Version}").Should().BeEquivalentTo("cli-with-engine@1.0.0", "helper@2.0.0", "native-addon@1.0.0"); + var cli = npmComponents.Single(x => x.Name == "cli-with-engine"); + var helper = npmComponents.Single(x => x.Name == "helper"); + var graph = componentRecorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(cli.Id).Should().ContainSingle().Which.Should().Be(helper.Id); + } + [TestMethod] public async Task TestPnpmDetector_V9_GoodLockVersion_SkipsFileAndLinkDependencies() { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs index b5f111ac1..2a622c94b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs @@ -202,6 +202,22 @@ public void DeserializePnpmYamlFileVersion_MultiDocument_ConsistentVersions_Retu version.Should().Be("9.0"); } + [TestMethod] + [DataRow("pkg@build.feed:1.2.3", "1.2.3")] + [DataRow("pkg@build.feed:main", "build.feed:main")] + [DataRow("pkg@9registry:1.2.3", "9registry:1.2.3")] + [DataRow("pkg@not/a/registry:1.2.3", "not/a/registry:1.2.3")] + [DataRow("node@runtime:22.0.0", "runtime:22.0.0")] + [DataRow("pkg@file:1.2.3", "file:1.2.3")] + public void CreateDetectedComponentFromPnpmPathV9_OnlyStripsRegistryAliases(string packagePath, string expectedVersion) + { + var pnpmParsingUtilities = PnpmParsingUtilitiesFactory.Create(); + + var component = (NpmComponent)pnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(packagePath).Component; + + component.Version.Should().Be(expectedVersion); + } + [TestMethod] public void DeserializePnpmYamlFileVersion_MultiDocument_InconsistentVersions_ThrowsInvalidOperationException() {