diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index 0b625b1ac..b7abd2c39 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -2,14 +2,19 @@ name: Bazel patch compatibility (npm) # The npm flows of the real-Bazel tests (`npm::` in `e2e_bazel_build`): # hosted and vendored mode for a package that aspect_rules_js links from a -# pnpm lock, and agent mode for the copy of it in `node_modules`, on each -# Bazel release below. bazel-compatibility.yml holds the legs and what +# pnpm lock, agent mode for the copy of it in `node_modules`, and hosted +# mode on a hub that keeps the lock up to date with a pnpm of its own (a +# pnpm 11, and the pnpm 10 that rules_js picks), on each Bazel release +# below. bazel-compatibility.yml holds the legs and what # every ecosystem shares; this file says when the npm legs run and on which # releases. # -# Beyond what every leg needs, an npm leg downloads Node from nodejs.org and -# ruleset archives from codeload.github.com; its repository cache holds them -# and comes to about 100 MB. An npm tarball under test passes through that +# Beyond what every leg needs, an npm leg downloads Node from nodejs.org, +# ruleset archives from codeload.github.com and, for the hubs that keep +# their lock up to date, the two pnpm releases that rules_js runs: the +# `pnpm` package of registry.npmjs.org, about 5 MB each, held to the +# checksums rules_js has for them. The repository cache of a leg holds them +# and comes to about 110 MB. An npm tarball under test passes through that # cache as well: Bazel's downloader fetches it and keeps it under its # sha512. So a test builds the upstream tarball and each patched one anew, # with an id of the run in the entry file, and writes the upstream sum into diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index c71be16a1..aeec2e342 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2509,6 +2509,7 @@ command's integration tests check its output. | `patch_fetch_failed` (eject) | `failed` | vendor eject (v5.0): a hosted pin's patch record could not be fetched from `…/patches/view/`; the whole eject is refused (`eject_refused`), nothing touched, exit 1. | | `redirect_pnpm_lockfile_elsewhere` / `redirect_workspace_lockfile_elsewhere` / `cargo_manifest_not_workspace_root` (hosted) | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted` (v5.0): the project directory is a workspace member whose lock lives in another directory, so the rewriters, which read only the project directory, would pin nothing, or would pin a lock of its own that its package manager never reads (`redirect_workspace_lockfile_elsewhere`: a `pnpm-lock.yaml` in a member a `pnpm-workspace.yaml` lists, which pnpm ignores for the workspace's shared lock unless the workspace sets `sharedWorkspaceLockfile: false`, checked with pnpm 10.34 and 11.27; a yarn 1 `yarn.lock` in a `package.json` workspace member, which yarn 1.22 never reads; the message names the workspace root to run from) (pnpm: no npm-family lock here, and the nearest ancestor `pnpm-workspace.yaml` or the project's `lockfile-dir` (`.npmrc`) / `lockfileDir` (`pnpm-workspace.yaml`) puts `pnpm-lock.yaml` elsewhere; npm / yarn / Bun, `redirect_workspace_lockfile_elsewhere`: no npm-family lock here, and the nearest ancestor `package.json` whose `workspaces` (array, or the object form's `packages`) matches the directory holds `package-lock.json`, `npm-shrinkwrap.json`, `yarn.lock`, `bun.lock` or `bun.lockb`; a matching root with none of them that is itself listed by an outer root's `workspaces` hands the check to that root; vlt, same code: the nearest ancestor `vlt.json` whose `workspaces` (a string, an array, or an object of groups) matches the directory holds `vlt-lock.json`, or, as vlt falls back to it when `vlt.json` has no `workspaces` field, the `package.json` `workspaces` root above holds `vlt-lock.json`, and the nearer of a `vlt.json` and a `package.json` root is named; `workspaces` patterns use the glob grammar the package managers share: `*`, `?`, `**`, brace sets and sequences (`{a,b}`, `{1..3}`) and character classes (`[a-c]`, `[!a]`), read the way the root's lock's package manager reads them (#1097): extglobs (`@(a|b)`, `?(…)`, `*(…)`, `+(…)`, `!(…)`) match for npm and yarn but not Bun or vlt; for Bun and vlt, `*`, `?` and `**` never match a directory whose name starts with `.` (`packages/*` does not list `packages/.tools`, #1542, #1631) unless the pattern spells the dot (`packages/.tools`, `packages/.*`), while a `!` pattern still excludes one; yarn berry (picomatch) also reads regex groups (`packages/(a|b)`; a group without `|` only in a pattern fast-glob deems dynamic, or in a `!` pattern), the regex quantifiers `?` / `+` after a group, `+` after a class and `+` inside a group, POSIX classes (`[[:alpha:]]`) and `..` segments in a static pattern or after a static prefix (`packages/a/../b` lists `packages/b`; literal in a `!` pattern); a group alternative holding `/` (`(packages/ui|apps/web)`) is matched across components, and a `?` or `+` quantifying such a group fails closed (the pattern lists every directory, and excludes none as a `!` pattern) (#1490); so does a pattern with extglob or regex groups that is past what socket-patch works out — a brace alternative longer than 4,096 characters or with more than 64 groups, or one whose matching against a directory takes more than about a million steps (an ambiguous group such as `*(a|aa)` repeated dozens of times against a name hundreds of characters long) — while a pattern without groups is read whatever its length, and a brace set is expanded to at most 4,096 alternatives and a megabyte of text; a `!` pattern excludes what earlier patterns matched for npm, Bun 1.3+ (a `bun.lock` with a top-level `configVersion`) and vlt, excludes whatever the order for yarn berry (a `yarn.lock` with `__metadata`, where a leading `!(` is an extglob), and is ignored by yarn classic and older Bun (a `bun.lock` without `configVersion`, or a `bun.lockb` alone without the trailing `cNfGvRsN` config-version extension, its binary twin, #1492); only the root's locks whose package manager lists the directory govern it (and are named), and a lockless root lists it when any of them would; when a pnpm workspace also governs the directory, the nearer root is named and a tie goes to `redirect_pnpm_lockfile_elsewhere`; uv (pypi, #1138), `redirect_workspace_lockfile_elsewhere`: the directory holds a `pyproject.toml`, and the nearest ancestor `pyproject.toml` declaring `[tool.uv.workspace]` lists it in `members` (and not in `exclude`), with no standalone project (`[project]`, no workspace) in between, so uv installs it from that root's `uv.lock` (a `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock` or pylock left in the member is never read and does not exempt it); the message says uv workspaces are not patched from their root yet either, and vendored refuses the same layout with `pypi_uv_workspace_unsupported` instead of rewriting a member with Hatch configuration as a lockless Hatch project; a directory whose own locks are all ones its manager never reads inside a workspace member is refused the same way, naming the ignored locks: `package-lock.json` / `npm-shrinkwrap.json` when its `package.json` `workspaces` root holds `package-lock.json` or `npm-shrinkwrap.json` (npm, #1094), `bun.lock` / `bun.lockb` when that root holds `bun.lock` or `bun.lockb` (Bun, #1101), and `vlt-lock.json` in a directory with no `vlt.json` of its own when its vlt workspace root (as above) holds `vlt-lock.json` (vlt, #1134), or, listed or not, when vlt's project root for the directory is another directory holding `vlt-lock.json` (vlt, #1584: the nearest ancestor `vlt.json`, else the outermost directory holding a `package.json` or `node_modules`, the walk ending at a directory holding `.git` and below the home directory, as vlt's own `find("project")` does; the message names that root and says a `vlt.json` in the directory makes it a project of its own); vendored refuses it with `vendor_lockfile_missing`, and `vex` reads the ignored lock as absent, with one `patched_ref_unattributable` warning naming it when it holds Socket references) or rewrite the member as a lockless project (cargo: the vendored workspace-root check). Refused before any takeover or write, `--dry-run` included; the message names the directory to run from; exit 1. Disk runs only (an in-memory project has no ancestors). | | `redirect_pnpm_settings_elsewhere` | top-level `error.code` (`status: "error"`) | scan / get `--mode hosted`: the project directory is a pnpm workspace member (listed by the `packages:` globs of the nearest ancestor `pnpm-workspace.yaml`) with its own v9 `pnpm-lock.yaml` (`sharedWorkspaceLockfile: false`) and no `pnpm-workspace.yaml` of its own, so its pnpm settings come from that ancestor file, which pnpm reads alone (a member's own file is ignored). A directory those globs do not list (no `packages:`, an empty list, a non-matching or `!`-excluded path) is a standalone project on pnpm 11.28+/12 that reads only its own file: it is pinned and gets its own `pnpm-workspace.yaml` like any single project. A root file that does not parse, or whose patterns use braces, classes or extglobs, counts as listing the project. When that file neither carries `trustLockfile: true` nor explicitly sets another value, the trust auto-config has nowhere to go: refused before any takeover or write, `--dry-run` included; the message names the root file to add `trustLockfile: true` to (or `--no-trust-lockfile-config` pins without it); exit 1. Once the root file trusts the lock (or opts out), the member is pinned and no nested `pnpm-workspace.yaml` is created; the `redirect_pnpm_trust_lockfile` warning names the root file. In memory, a member whose lock is demoted into its workspace root (#492) is never refused; one whose lock is not (the workspace root's files do not confirm it pins or ignores that lock, or socket.yml leaves the root out) is refused with this code as its project error, nothing written for it, whenever its lock is v9, the trust auto-config is on and that file may list it (listed, unreadable, or not readable as globs), whatever it says about `trustLockfile`. | +| `redirect_pnpm_bazel_workspace_hidden` | `warnings[]` (warning, one per run) | scan / get `--mode hosted`, dry and wet, and the in-memory engine: the project is in a Bazel workspace where one `npm.npm_translate_lock` call of aspect_rules_js names its `pnpm-lock.yaml` in a plain string, keeps it up to date (`update_pnpm_lock` is `True` or not written out as `True` or `False`), does not list the `pnpm-workspace.yaml` beside the lock in a `data` that is a list of strings (or lists a file that would hold only what hosted mode writes, or one hosted mode does not write `trustLockfile: true` to), and runs a pnpm that the workspace states as 11 or later or in a way that is no version, or states none under a release of aspect_rules_js whose own choice is not known (any but 1.x to 3.x, 4.0.0-alpha.0 and 4.0.0-alpha.1, by `bazel_dep`, a `single_version_override` and `MODULE.bazel.lock`) (the `pnpm_version`, or the `packageManager` of the `pnpm_version_from` file, of the `pnpm.pnpm` tag whose `name` is the repository of the call's `use_pnpm`, `pnpm` without one; a `use_pnpm` whose repository no `use_repo` takes by position under that name, or that no such tag makes unless it is `pnpm`, is no version). The pnpm that Bazel runs would not read the `trustLockfile: true` hosted mode writes, would reject the pinned lock (`ERR_PNPM_TARBALL_URL_MISMATCH`), and `bazel build` would fail. Every root pnpm lock is left untouched and no npm pin is confirmed from it; the members' own locks of a workspace with `sharedWorkspaceLockfile: false` are pinned as without Bazel (in the root lock each package is a `skipped` event: `redirect_unconfirmed`, or `redirect_unattributable` where another npm lock of the project names it, which is then not pinned either), exit 0, `status: "success"`. The detail starts with the file and the line of the call, named as the file writes it (`MODULE.bazel:7: this `npm.npm_translate_lock` …`; `MODULE.bazel:7, with paths from the root of the Bazel workspace: …` for a project below that root) and ends with what to do: `; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run`, with the label of the file beside the lock. Before the label, or alone where the call lists the file: where the file would hold only what hosted mode writes (none, an empty file, the root-only `packages` scaffold, a file of an earlier hosted run), `put a comment line in pnpm-workspace.yaml (create the file where there is none: …)`, because `rollback` removes such a file and the call would name a missing one; where the file says `trustLockfile:` with another value than `true`, or is YAML a line cannot be added to, to set `trustLockfile: true` in it. Where `data` is not written out as a list of strings, the last step is to write it out as one that holds the label. A hub without `update_pnpm_lock`, one that runs pnpm 10 or states no release under a release of the ruleset whose choice is known, one that lists a file of the user's own that takes the setting, a project whose lock no call names and a project in no Bazel workspace are not affected. See docs/ecosystems.md, "Bazel workspaces: npm". | | `eject_refused` | top-level `error.code` (`status: "error"`) | vendor eject (v5.0): a record fetch failed or a pin's upstream restore was refused while planning; nothing was changed, exit 1. | | `eject_planned` | `applied` (reason) | vendor eject `--dry-run` (v5.0): the pin would be restored upstream and vendored; nothing written. | | `eject_rolled_back` | warning; `skipped` event | vendor eject (v5.0): a package failed after the restore began; every touched file was put back from the pre-eject snapshot, so the project is still hosted; `partialFailure`, exit 1. Also the `errorCode` of the `skipped` event re-reporting each package the eject had vendored before it was rolled back (not counted in `summary.applied`). | diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index b8f6646b4..e5b52b516 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -68,6 +68,22 @@ //! Tests that need no Bazel run the same steps in a copy of the fixture, //! and in workspaces where the statement must stay as it is without Bazel. //! +//! A fourth flow is hosted mode on a hub that keeps the lock up to date +//! ([`hosted_update_pnpm_lock_on_pnpm_11`]): with `update_pnpm_lock = True` +//! rules_js runs a pnpm of its own during the build, over the lock and the +//! files the hub lists as `data`. Here that pnpm is 11 and the hub lists no +//! `pnpm-workspace.yaml`, so it would never read the `trustLockfile: true` +//! that hosted mode writes there, and would reject the pinned lock. Hosted +//! mode pins nothing, says which call stands in the way and what to add to +//! it, and the build stays the unpatched one that passes; after that +//! addition the same scan ends in the patched build, and `rollback` in the +//! unpatched one. A fifth flow ([`hosted_update_pnpm_lock_on_pnpm_10`]) is +//! the same hub with the pnpm rules_js picks itself, a pnpm 10, which has +//! no such check: hosted mode pins the lock as on any other hub. Tests +//! without Bazel hold the same two answers, the wording of the warning, +//! and that every hub which hides nothing leaves the run as it is without +//! Bazel. +//! //! A marker is read from what Bazel built. Bazel's downloader keeps every //! file it fetches in the repository cache, under its checksum, and hands it //! out again without a request; the tests of a leg share that cache, and CI @@ -773,6 +789,346 @@ fn vendored_npm_translate_lock() { ); } +/// The release of pnpm 11 that Bazel runs in the flow below. rules_js 3.6.0 +/// holds its checksum, so Bazel fetches it like the Node that runs it: from +/// the public registry, into the repository cache of the leg. +const PNPM_11: &str = "11.28.10"; + +/// The code of the warning with which hosted mode pins no pnpm lock that a +/// hub keeps up to date with a pnpm that would not trust it. +const HIDDEN: &str = "redirect_pnpm_bazel_workspace_hidden"; + +/// What that warning says to do in a project that has no +/// `pnpm-workspace.yaml`, and in one that has: its last words. +const WAY_ON: [&str; 2] = [ + " — put a comment line in pnpm-workspace.yaml (create the file where there is none: \ + `rollback` removes one that holds only what hosted mode writes, and the call would then \ + name a missing file), list `//:pnpm-workspace.yaml` in the `data` of that call and re-run", + " — list `//:pnpm-workspace.yaml` in the `data` of that call and re-run", +]; + +/// The `pnpm-workspace.yaml` a user creates for that warning: a comment. +const OWN_WORKSPACE: &str = "# What the pnpm that Bazel runs is to read.\n"; + +/// The line of the fixture's hub that names the lock, and the one that has +/// rules_js keep that lock up to date. +const UPDATE: &str = " update_pnpm_lock = True,\n"; +fn lock_line() -> String { + format!(" pnpm_lock = \"//:{LOCK}\",\n") +} + +/// The fixture's hub in the checkout of `cell` as one that keeps the lock +/// up to date: `update_pnpm_lock = True` on its call. rules_js then keeps +/// a file of hashes under `.aspect/` in the checkout, and whenever the +/// lock or a `package.json` is not what that file says, the build runs +/// `pnpm install --lockfile-only` in a directory that holds the lock, the +/// `package.json` of each importer and the files the call lists as `data`, +/// and no other file of the checkout. With `pnpm`, a `pnpm.pnpm` tag +/// states the release of that pnpm; without, rules_js runs the one it +/// picks itself (3.6.0: its newest pnpm 10). +fn keeps_the_lock_up_to_date(cell: &Cell, pnpm: Option<&str>) { + let module = text(&cell.tree(), MODULE); + let lock = lock_line(); + assert_eq!(module.matches(&lock).count(), 1, "{}: {module}", cell.test); + let mut module = module.replace(&lock, &format!("{lock}{UPDATE}")); + if let Some(release) = pnpm { + module.push_str(&format!( + "\npnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + pnpm.pnpm(name = \"pnpm\", pnpm_version = \"{release}\")\n\ + use_repo(pnpm, \"pnpm\")\n" + )); + } + cell.write(MODULE, module); +} + +/// What the warning of [`HIDDEN`] says to do, in the checkout of `cell` +/// where [`keeps_the_lock_up_to_date`] wrote the hub: a +/// `pnpm-workspace.yaml` of the user's own, and its label in the `data` of +/// the call. +fn lists_the_workspace_file(cell: &Cell) { + cell.write("pnpm-workspace.yaml", OWN_WORKSPACE); + let module = text(&cell.tree(), MODULE); + assert_eq!(module.matches(UPDATE).count(), 1, "{}: {module}", cell.test); + let data = " data = [\"//:pnpm-workspace.yaml\"],\n"; + cell.write(MODULE, module.replace(UPDATE, &format!("{data}{UPDATE}"))); +} + +/// [`open`] with a hub that keeps the lock up to date +/// ([`keeps_the_lock_up_to_date`]). +/// +/// The pnpm that Bazel runs has the stand-in as its registry, under the +/// variable each release reads (`pnpm_config_registry` from pnpm 11 on), +/// as on a machine behind a registry mirror. pnpm 11 holds every entry of +/// a lock to what the registry publishes for it before it does anything +/// else, so the stand-in serves the document of the package: its one +/// version, with the URL the public registry has for the tarball and the +/// sum of this run's. +fn open_updating(test: &str, pnpm: Option<&str>) -> Option<(Cell, StandIn, Package)> { + let (mut cell, standin, upstream) = open(test)?; + keeps_the_lock_up_to_date(&cell, pnpm); + let registry = format!("{}/{REGISTRY}/", standin.origin()); + for name in ["npm_config_registry", "pnpm_config_registry"] { + cell.repo_env.push((name.to_string(), registry.clone())); + } + let published = "2020-01-01T00:00:00.000Z"; + let document = json!({ + "name": NAME, + "dist-tags": { "latest": VERSION }, + "versions": { VERSION: { + "name": NAME, + "version": VERSION, + "dist": { + "tarball": format!("https://{REGISTRY}/{NAME}/-/{TGZ}"), + "integrity": integrity(&upstream.tarball), + }, + }}, + "time": { "created": published, "modified": published, VERSION: published }, + }); + let document = serde_json::to_vec(&document).expect("a JSON document"); + standin.serve(5, &document_route(), &document); + Some((cell, standin, upstream)) +} + +/// The route of the document a pnpm asks its registry for about the +/// package: the name with `%2F` for its `/`. +fn document_route() -> String { + format!("/{REGISTRY}/{}", NAME.replace('/', "%2F")) +} + +/// A finished hosted run in the checkout of `cell`, whose files were +/// `before`, pinned nothing because of the hub: it passes, skips the +/// package as one no lock entry could be rewritten for, names no file as +/// rewritten and changes none. Its one warning has the code [`HIDDEN`], +/// starts with the call (`names`, as far as its text is the same for every +/// such hub) and ends with what to do (`way_on`). +fn pinned_nothing(cell: &Cell, ran: &Ran, before: &Tree, names: &str, way_on: &str) { + let (test, said) = (&cell.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "success", "{test}: {said}"); + let skipped = [( + canonical_purl(PURL), + "skipped".into(), + "redirect_unconfirmed".into(), + )]; + assert_eq!(reported(&ran.envelope), skipped, "{test}: {said}"); + assert_eq!(ran.envelope["summary"]["applied"], 0, "{test}: {said}"); + let warnings = &ran.envelope["warnings"]; + assert_eq!(codes_in(warnings), [HIDDEN], "{test}: {said}"); + let detail = warnings[0]["detail"].as_str().unwrap_or_default(); + let named = detail.starts_with(names) && detail.ends_with(way_on); + assert!(named, "{test}: not {names:?} ... {way_on:?}: {detail}"); + let rewritten = &ran.envelope["redirect"]["rewrittenFiles"]; + assert_eq!(*rewritten, json!([]), "{test}: {said}"); + assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}: {said}"); +} + +/// The start of the warning for the fixture's hub in `cell`, which has +/// Bazel run [`PNPM_11`]: the file and the line of the call. +fn names_the_hub(cell: &Cell) -> String { + let module = text(&cell.tree(), MODULE); + let above = module.lines().take_while(|line| *line != format!("{HUB}(")); + format!( + "{MODULE}:{}: this `{HUB}` has Bazel run pnpm {PNPM_11} to keep ", + above.count() + 1 + ) +} + +/// The variable under which rules_js fails a build that would have to +/// write its hashes anew, which it recommends for CI. +const FROZEN: &str = "ASPECT_RULES_JS_FROZEN_PNPM_LOCK"; + +/// Step (c) on a hub that keeps the lock up to date, in the checkout of +/// `cell` with the files `pinned`. The lock changed, so the hashes of +/// rules_js are stale: a build that may not write them fails, as after any +/// change of the lock. The build a user runs passes and prints the marker +/// of `patch`, with the tarball from the stand-in patch host; rules_js ran +/// its pnpm again and wrote its hashes anew, and that file is the one file +/// of the checkout the build changes. After it, a build passes that may +/// update neither those hashes nor Bazel's own lock. +fn builds_pinned(cell: &Cell, standin: &StandIn, patch: &Patched, pinned: &Tree) { + let test = &cell.test; + let stale = cell.bazel_env("build", &[CONSUMER], &[(FROZEN, "1")]); + let refused = !stale.ok() && stale.stderr().contains("is out of date"); + assert!(refused, "{test}: {}", stale.dump()); + let fetches = standin.asked(&patch.route); + cell.builds(&patch.package.marker); + assert!( + standin.asked(&patch.route) > fetches, + "{test}: the patched build did not fetch the tarball from the stand-in patch host" + ); + let rewritten = changed(pinned, &cell.tree()); + let hashes = matches!(&rewritten[..], [file] if file.starts_with(HASHES)); + assert!(hashes, "{test}: the build changed {rewritten:?}"); + // The harness gives every command `--lockfile_mode=update`; the last + // one of a command line counts. + let frozen = ["--lockfile_mode=error", CONSUMER]; + let frozen = cell.bazel_env("build", &frozen, &[(FROZEN, "1")]); + assert!(frozen.ok(), "{test}: {}", frozen.dump()); +} + +/// The undo on such a hub: `rollback --yes` counts the package and leaves +/// every file of `before` as it was but the hashes of rules_js, which the +/// patched build wrote; the next build prints `marker` and writes those of +/// `before` again. +fn rolls_back(cell: &Cell, standin: &StandIn, before: &Tree, marker: &str) { + let undo = socket_patch(cell, standin, &["rollback", "--yes"]); + let (test, said) = (&cell.test, &undo.dump); + assert_eq!(undo.code, 0, "{test}: {said}"); + assert_eq!(undo.envelope["summary"]["rolledBack"], 1, "{test}: {said}"); + let left = changed(before, &cell.tree()); + let hashes = left.iter().all(|file| file.starts_with(HASHES)); + assert!(hashes, "{test}: {left:?}: {said}"); + cell.builds(marker); + assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}"); +} + +/// Hosted mode on a hub that keeps the lock up to date with pnpm 11 and +/// lists no `pnpm-workspace.yaml` as `data` ([`open_updating`]). The +/// checkout has no such file, as the fixture has none. +/// +/// - (a) The first build runs that pnpm, which finds the lock as the +/// registry has the package, and rules_js writes its file of hashes; the +/// build prints the unpatched marker. +/// - (b) `scan --mode hosted --yes` passes and pins nothing +/// ([`pinned_nothing`]): the pnpm that Bazel runs would not read the +/// `trustLockfile: true` of a `pnpm-workspace.yaml`, and would reject a +/// lock that names the patch host. The warning names the call and what +/// to add to it. +/// - (c) The same build passes and prints the unpatched marker. +/// - (d) What the warning says: a `pnpm-workspace.yaml` of the user's own, +/// and its label in the `data` of the call +/// ([`lists_the_workspace_file`]). The build still prints the unpatched +/// marker. The same scan now pins the lock and puts the setting in that +/// file, and the same build prints the patched marker +/// ([`builds_pinned`]). +/// - (e) `rollback --yes` leaves the checkout of (d) before the scan, the +/// user's file included, so the call names no missing file, and the +/// build prints the unpatched marker again ([`rolls_back`]). +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_on_pnpm_11() { + let test = "npm::hosted_update_pnpm_lock_on_pnpm_11"; + let started = Instant::now(); + let Some((cell, standin, upstream)) = open_updating(test, Some(PNPM_11)) else { + return; + }; + let release = cell.release().to_string(); + let patch = Patched::new(); + grant(&standin, &upstream, &patch, &patch.package.tarball); + + // (a) The unpatched build. The pnpm that Bazel ran asked the stand-in + // for the package, and rules_js left its hashes in the checkout. + let before = builds_upstream(&cell, &standin, &upstream); + assert!( + standin.asked(&document_route()) > 0, + "{test}: no pnpm asked the stand-in registry about the package" + ); + let hashes = |tree: &Tree| tree.keys().any(|file| file.starts_with(HASHES)); + assert!(hashes(&before), "{test}: {:?}", before.keys()); + + // (b) The one command of hosted mode pins nothing, and says why. + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let scan = socket_patch(&cell, &standin, &hosted); + pinned_nothing(&cell, &scan, &before, &names_the_hub(&cell), WAY_ON[0]); + + // (c) The same build is the one of (a). + cell.builds(&upstream.marker); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + + // (d) What the warning says to do, and nothing else. The build is + // still the unpatched one; then the same scan pins the lock, and the + // pnpm that Bazel runs reads the setting in the file the hub lists. + lists_the_workspace_file(&cell); + cell.builds(&upstream.marker); + let listed = cell.tree(); + let scan = socket_patch(&cell, &standin, &hosted); + let written = [LOCK, "pnpm-workspace.yaml"]; + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &listed, &written); + let workspace = format!("{OWN_WORKSPACE}{TRUSTING_WORKSPACE}"); + assert_eq!(text(&pinned, "pnpm-workspace.yaml"), workspace, "{test}"); + builds_pinned(&cell, &standin, &patch, &pinned); + + // (e) The undo, which leaves the file the hub lists. + rolls_back(&cell, &standin, &listed, &upstream.marker); + + println!( + "{test}: Bazel {release} built {:?} with pnpm {PNPM_11} keeping the lock up to date; \ + `scan --mode hosted` pinned nothing and warned {HIDDEN}, and the build stayed that \ + one; with pnpm-workspace.yaml in the hub's `data` the same scan pinned the lock and \ + the build printed {:?}; `rollback` brought {:?} back; {:?}", + upstream.marker, + patch.package.marker, + upstream.marker, + started.elapsed() + ); +} + +/// The same hub with no `pnpm.pnpm` tag: rules_js runs the pnpm it picks +/// itself, which at 3.6.0 is a pnpm 10, and pnpm 10 does not hold a lock +/// to the registry. Hosted mode pins the lock as on a hub that never runs +/// pnpm, with no line added to the call. +/// +/// - (a) The first build prints the unpatched marker, and no pnpm asked +/// the stand-in about the package. +/// - (b) `scan --mode hosted --yes` pins the lock and creates +/// `pnpm-workspace.yaml`, with no warning of [`HIDDEN`]. +/// - (c) The same build prints the patched marker ([`builds_pinned`]). +/// - (d) `rollback --yes` restores the files, and the build prints the +/// unpatched marker ([`rolls_back`]). +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_update_pnpm_lock_on_pnpm_10() { + let test = "npm::hosted_update_pnpm_lock_on_pnpm_10"; + let started = Instant::now(); + let Some((cell, standin, upstream)) = open_updating(test, None) else { + return; + }; + let release = cell.release().to_string(); + let patch = Patched::new(); + grant(&standin, &upstream, &patch, &patch.package.tarball); + + // (a) The unpatched build, by a hub that ran its pnpm. + let before = builds_upstream(&cell, &standin, &upstream); + let hashes = before.keys().any(|file| file.starts_with(HASHES)); + assert!(hashes, "{test}: {:?}", before.keys()); + + // (b) The one command of hosted mode, as on any other hub. + let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let written = [LOCK, "pnpm-workspace.yaml"]; + let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); + assert_eq!(text(&pinned, "pnpm-workspace.yaml"), TRUSTING_WORKSPACE); + let warned = codes_in(&scan.envelope["warnings"]); + assert!( + !warned.iter().any(|code| code == HIDDEN), + "{test}: {warned:?}" + ); + + // (c) The patched build, and (d) the undo. + builds_pinned(&cell, &standin, &patch, &pinned); + rolls_back(&cell, &standin, &before, &upstream.marker); + // A pnpm 11 holds the lock to the registry's document, as the flow + // above shows: the pnpm of this hub is none. + assert_eq!( + standin.asked(&document_route()), + 0, + "{test}: a pnpm held the lock to the registry" + ); + + println!( + "{test}: Bazel {release} built {:?} with the pnpm rules_js picks keeping the lock up \ + to date; `scan --mode hosted` pinned the lock and the build printed {:?}; `rollback` \ + brought {:?} back; {:?}", + upstream.marker, + patch.package.marker, + upstream.marker, + started.elapsed() + ); +} + +/// The directory of the checkout where rules_js keeps the hashes of what a +/// hub with `update_pnpm_lock` read, one file per hub. +const HASHES: &str = ".aspect/rules/external_repository_action_cache/"; + /// The file that hands the lock to rules_js, and the call that does. const MODULE: &str = "MODULE.bazel"; const HUB: &str = "npm.npm_translate_lock"; @@ -1690,6 +2046,321 @@ fn a_hosted_pin_is_attested_beside_a_second_hub_that_lists_the_package() { assert!(!text(&pinned, &beside).contains(&patch.uuid), "{beside}"); } +/// A hosted scan in the checkout of `cell`, whose project is in the +/// directory `project` (as [`install`] takes it), with what else it is +/// told. +fn hosted_scan(cell: &Cell, standin: &StandIn, project: &str, more: &[&str]) -> Ran { + let at = ["--cwd", project.trim_end_matches('/')]; + let at: &[&str] = if project.is_empty() { &[] } else { &at }; + let scan = ["scan", "--mode", "hosted"]; + socket_patch(cell, standin, &[&scan[..], more, at].concat()) +} + +/// Without a Bazel: the two scans of [`hosted_update_pnpm_lock_on_pnpm_11`] +/// and its undo, in a checkout with that hub, for the project at the root +/// and for one in a directory of the workspace, whose hub names the lock +/// there. As long as the hub lists no `pnpm-workspace.yaml`, the scan, a +/// dry run of it and `get --mode hosted` pin nothing +/// ([`pinned_nothing`]); a person reads the same warning under the line +/// that says no patch could be switched. With the file of the user's own +/// and its label in `data`, the scan pins the lock and writes the setting +/// under the user's comment, and `rollback` leaves that file as the user +/// made it. +#[test] +fn hosted_mode_pins_nothing_where_a_hub_hides_the_trust_setting_from_pnpm_11() { + for project in ["", "web/"] { + let (mut cell, standin, patch, _) = checkout(project); + cell.test = format!("{project:?}"); + let test = &cell.test; + std::fs::remove_dir_all(cell.path(&format!("{project}node_modules"))).expect("the tree"); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + let package = project.trim_end_matches('/'); + let label = |file: &str| format!("\"//{package}:{file}\""); + reads(&cell, label(LOCK).trim_matches('"')); + let before = cell.tree(); + // For a project below the root the warning says where its paths + // are from. + let from = match project { + "" => ": this", + _ => ", with paths from the root of the Bazel workspace: this", + }; + let names = names_the_hub(&cell).replacen(": this", from, 1); + let listed = WAY_ON.map(|way| way.replace("\"//:", &format!("\"//{package}:"))); + let listed = listed.map(|way| way.replace("`//:", &format!("`//{package}:"))); + let way_on = listed[0].replace( + "in pnpm-workspace.yaml (create", + &format!("in {project}pnpm-workspace.yaml (create"), + ); + assert_ne!( + way_on.contains("in web/pnpm-workspace.yaml"), + project.is_empty() + ); + + // A script: the scan, its dry run, and `get` of the package. + for more in [&["--yes"][..], &["--dry-run"]] { + let scan = hosted_scan(&cell, &standin, project, more); + pinned_nothing(&cell, &scan, &before, &names, &way_on); + } + let get = ["get", PURL, "--mode", "hosted", "--yes"]; + let at = ["--cwd", project.trim_end_matches('/')]; + let at: &[&str] = if project.is_empty() { &[] } else { &at }; + let get = socket_patch(&cell, &standin, &[&get[..], at].concat()); + pinned_nothing(&cell, &get, &before, &names, &way_on); + // A person. + let origin = standin.origin(); + let env = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let at = ["--cwd", package]; + let at: &[&str] = if project.is_empty() { &[] } else { &at }; + let scan = [&["scan", "--mode", "hosted", "--yes"][..], at].concat(); + let [stdout, stderr] = cell.socket_patch_person(&origin, &scan, &env); + let said = format!("{test}:\n--- stdout\n{stdout}\n--- stderr\n{stderr}"); + let switched = "Switched 0 packages to hosted patches; rewrote 0 files."; + assert!(stdout.lines().any(|line| line == switched), "{said}"); + let none = "No patches could be switched to hosted:"; + let warning = format!("Warning: {names}"); + let lines: Vec<&str> = stderr.lines().collect(); + let below = lines.iter().skip_while(|line| **line != none); + let warned = below.skip(1).any(|line| line.starts_with(&warning)); + assert!(warned, "no {warning:?} under {none:?}: {said}"); + let unspaced = |text: &str| text.split_whitespace().collect::(); + assert!(unspaced(&stderr).contains(&unspaced(&way_on)), "{said}"); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + + // What the warning says to do: the file, then its label. + let workspace = format!("{project}pnpm-workspace.yaml"); + cell.write(&workspace, OWN_WORKSPACE); + let module = text(&cell.tree(), MODULE); + let data = format!(" data = [{}],\n{UPDATE}", label("pnpm-workspace.yaml")); + cell.write(MODULE, module.replace(UPDATE, &data)); + let listed = cell.tree(); + let scan = hosted_scan(&cell, &standin, project, &["--yes"]); + let written = [format!("{project}{LOCK}"), workspace.clone()]; + let pinned = cell.tree(); + assert_eq!(changed(&listed, &pinned), written, "{test}: {}", scan.dump); + assert_eq!( + scan.envelope["summary"]["applied"], 1, + "{test}: {}", + scan.dump + ); + assert!(text(&pinned, &written[0]).contains(&patch.uuid), "{test}"); + let trusting = format!("{OWN_WORKSPACE}{TRUSTING_WORKSPACE}"); + assert_eq!(text(&pinned, &workspace), trusting, "{test}"); + + let undo = socket_patch(&cell, &standin, &[&["rollback", "--yes"][..], at].concat()); + assert_eq!(undo.code, 0, "{test}: {}", undo.dump); + assert_eq!( + changed(&listed, &cell.tree()), + NOTHING, + "{test}: {}", + undo.dump + ); + } +} + +/// Without a Bazel: a hub that lists the `pnpm-workspace.yaml` of the +/// project is passed over only where the pin is one the build takes and an +/// undo leaves standing. Hosted mode pins nothing where it would not write +/// the setting to that file (the file says `trustLockfile: false`), and +/// where the file would hold only what hosted mode writes, so that +/// `rollback` would remove it and leave the call with a missing file. The +/// warning names what the file needs, and no label, which is there. +#[test] +fn a_listed_workspace_file_has_to_hold_the_setting_and_a_line_of_the_users_own() { + let own = WAY_ON[0].split_once(", list ").expect("the first step").0; + let cases = [ + ( + "packages:\n - '.'\n".to_string(), + format!("{own} and re-run"), + ), + (String::new(), format!("{own} and re-run")), + ( + format!("{OWN_WORKSPACE}trustLockfile: false\n"), + " — set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ + false`, which hosted mode leaves as it is) and re-run" + .to_string(), + ), + ]; + for (workspace, way_on) in cases { + let (mut cell, standin, _, _) = checkout(""); + cell.test = format!("{workspace:?}"); + std::fs::remove_dir_all(cell.path("node_modules")).expect("the installed tree"); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + lists_the_workspace_file(&cell); + cell.write("pnpm-workspace.yaml", workspace); + let before = cell.tree(); + let scan = hosted_scan(&cell, &standin, "", &["--yes"]); + pinned_nothing(&cell, &scan, &before, &names_the_hub(&cell), &way_on); + } +} + +/// A `package-lock.json` in the checkout of `cell` that pins the package as +/// its pnpm lock does: the lock of a project that npm installs. +fn locks_with_npm(cell: &Cell) { + let lock = text(&cell.tree(), LOCK); + let (_, sum) = lock.split_once("integrity: ").expect("the sum"); + let sum = sum.split_once('}').expect("its end").0; + let entry = json!({ "version": VERSION, "integrity": sum, + "resolved": format!("https://{REGISTRY}/{NAME}/-/{TGZ}") }); + let root = json!({ "name": "socket-fixture", "version": "0.0.0", + "dependencies": { NAME: VERSION } }); + let packages = json!({ "": root, format!("node_modules/{NAME}"): entry }); + let npm = json!({ "name": "socket-fixture", "version": "0.0.0", + "lockfileVersion": 3, "requires": true, "packages": packages }); + cell.write("package-lock.json", format!("{npm:#}\n")); +} + +/// Without a Bazel: the project of that hub has a lock of npm's beside its +/// pnpm lock. Hosted mode pins neither: a pin in the npm lock alone would +/// be one that the pnpm lock, which still names the registry's tarball, +/// stands against, and such a pin is never written. The package is skipped +/// as one whose pin could not be told, under the same warning, and no file +/// changes. +#[test] +fn an_npm_lock_beside_the_pnpm_lock_is_not_pinned_either() { + let (cell, standin, _, _) = checkout(""); + std::fs::remove_dir_all(cell.path("node_modules")).expect("the installed tree"); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + locks_with_npm(&cell); + let before = cell.tree(); + let scan = hosted_scan(&cell, &standin, "", &["--yes"]); + let (test, said) = (&cell.test, &scan.dump); + assert_eq!(scan.code, 0, "{test}: {said}"); + let skipped = [( + canonical_purl(PURL), + "skipped".into(), + "redirect_unattributable".into(), + )]; + assert_eq!(reported(&scan.envelope), skipped, "{test}: {said}"); + let warned = codes_in(&scan.envelope["warnings"]); + assert_eq!(warned, [HIDDEN], "{test}: {said}"); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}: {said}"); +} + +/// Without a Bazel: a patch that is in place is not taken away. The +/// checkout has the hub of [`hosted_update_pnpm_lock_on_pnpm_11`] and a +/// vendored patch of the package. A hosted scan would take a vendored +/// patch over; here it pins nothing, so it keeps the vendored one, says +/// so, and changes no file. +#[test] +fn a_vendored_patch_stays_where_hosted_mode_pins_nothing() { + let (cell, standin, patch, _) = checkout(""); + std::fs::remove_dir_all(cell.path("node_modules")).expect("the installed tree"); + keeps_the_lock_up_to_date(&cell, Some(PNPM_11)); + let vendoring = socket_patch(&cell, &standin, &["scan", "--mode", "vendored", "--yes"]); + let (test, said) = (&cell.test, &vendoring.dump); + assert_eq!( + vendoring.envelope["summary"]["applied"], 1, + "{test}: {said}" + ); + let vendored = cell.tree(); + assert!(vendored.contains_key(&patch.vendored()), "{test}: {said}"); + + let hosted = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let said = &hosted.dump; + assert_eq!(hosted.code, 0, "{test}: {said}"); + let warned = codes_in(&hosted.envelope["warnings"]); + let kept = [HIDDEN, "redirect_takeover_kept_vendored"]; + assert!( + kept.iter().all(|code| warned.contains(&code.to_string())), + "{test}: {said}" + ); + assert_eq!(hosted.envelope["summary"]["applied"], 0, "{test}: {said}"); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}: {said}"); +} + +/// Without a Bazel: hubs that hide nothing from a pnpm that needs it, each +/// made from the fixture's `MODULE.bazel`. Hosted mode pins the lock, and +/// its run is the one of the same checkout without its `MODULE.bazel`, to a +/// script and to a person: the exit code, both streams byte for byte, and +/// every file it leaves. +/// +/// - The hub keeps the lock up to date with a pnpm 10, which a tag states. +/// - It does so with the pnpm rules_js picks itself. +/// - It does so with pnpm 11 and lists the `pnpm-workspace.yaml` of the +/// project. +/// - A tag states pnpm 11 and the hub leaves the lock to the user. +/// - The hub keeps the lock of another project up to date with pnpm 11: +/// the project is a directory of the workspace with a lock of its own +/// that no hub reads. +/// - It does so in a file that `MODULE.bazel` includes and that is not +/// there: a hub that is not read withholds nothing. +/// - The hub of the flow names a pnpm lock that the project does not have: +/// its lock is npm's, which no hub reads, and hosted mode pins that. +#[test] +fn hosted_mode_pins_as_without_bazel_where_no_hub_hides_the_trust_setting() { + let cases: [(&str, &str, Arrange); 7] = [ + ("pnpm 10", "", |cell| { + keeps_the_lock_up_to_date(cell, Some("10.34.9")) + }), + ("the pnpm rules_js picks", "", |cell| { + keeps_the_lock_up_to_date(cell, None) + }), + ("pnpm 11 and the file listed", "", |cell| { + keeps_the_lock_up_to_date(cell, Some(PNPM_11)); + lists_the_workspace_file(cell); + }), + ("pnpm 11 and no update", "", |cell| { + keeps_the_lock_up_to_date(cell, Some(PNPM_11)); + let module = text(&cell.tree(), MODULE); + cell.write(MODULE, module.replace(UPDATE, "")); + }), + ("the lock of another project", "web/", |cell| { + keeps_the_lock_up_to_date(cell, Some(PNPM_11)); + }), + ("a hub in a file that is missing", "", |cell| { + let include = "include(\"//tools:npm.MODULE.bazel\")\n"; + let module = text(&cell.tree(), MODULE); + let (head, _) = module.split_once("npm = use_extension(").expect("the hub"); + cell.write(MODULE, format!("{head}{include}")); + }), + ("a lock of npm's", "", |cell| { + keeps_the_lock_up_to_date(cell, Some(PNPM_11)); + locks_with_npm(cell); + std::fs::remove_file(cell.path(LOCK)).expect(LOCK); + }), + ]; + for (case, project, arrange) in cases { + let (mut cell, standin, patch, _) = checkout(project); + cell.test = case.to_string(); + std::fs::remove_dir_all(cell.path(&format!("{project}node_modules"))).expect("the tree"); + arrange(&cell); + // The same files in a checkout that is no Bazel workspace. The + // file of the user's own stays: it is no file of Bazel's. + let mut files = cell.tree(); + files.remove(MODULE).expect(MODULE); + files.remove(".git/HEAD").expect("the checkout's mark"); + let twin = cell.unbuilt(&files); + + let origin = standin.origin(); + let registry = format!("{origin}/{REGISTRY}"); + let env = [ + ("SOCKET_PATCH_SERVER_URL", origin.as_str()), + ("SOCKET_NPM_REGISTRY", registry.as_str()), + ]; + let at = ["--cwd", project.trim_end_matches('/')]; + let at: &[&str] = if project.is_empty() { &[] } else { &at }; + let scan = [&["scan", "--mode", "hosted", "--yes"][..], at].concat(); + let unwritten = cell.document("none"); + let gives = |cell: &Cell| cell.gives(&origin, &scan, &env, &unwritten); + let (beside_the_hub, without_bazel) = (gives(&cell), gives(&twin)); + assert_eq!(beside_the_hub, without_bazel, "{case}"); + let codes: Vec<&Value> = without_bazel.as_array().expect("two runs").iter().collect(); + let codes = codes.iter().map(|run| &run["code"]).collect::>(); + assert_eq!(codes, [&json!(0), &json!(0)], "{case}: {without_bazel:#}"); + + let mut left = cell.tree(); + left.remove(MODULE).expect(MODULE); + left.remove(".git/HEAD").expect("the checkout's mark"); + assert_eq!(left, twin.tree(), "{case}"); + let pinned = |lock: &str| { + left.get(lock) + .is_some_and(|lock| String::from_utf8_lossy(lock).contains(&patch.uuid)) + }; + let pinned = pinned(&format!("{project}{LOCK}")) || pinned("package-lock.json"); + assert!(pinned, "{case}: {:?}", left.keys()); + } +} + /// Without a Bazel, what stays fixed now that no sum is committed: the /// fixture's directories and the legs of its workflow are those of its /// table; the fixture's lock holds the one entry a test pins, with the diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index bb14874b0..37d01c8c9 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -1523,6 +1523,63 @@ async fn parity_pnpm_member_branch_lock_refusal() { ); } +/// A rules_js hub of the project's `MODULE.bazel` that keeps the pnpm lock +/// up to date with pnpm 11 and does not list `pnpm-workspace.yaml` as +/// `data`: the pnpm that Bazel runs would reject a pinned lock, so both +/// engines refuse every pnpm pin with the same warning, nothing written. +/// Path selection asks for the `MODULE.bazel` beside the lock. With a +/// file of the user's own listed both engines pin the lock; with a listed +/// file that the undo of the pin would remove both pin nothing. +#[tokio::test] +async fn parity_pnpm_bazel_hub_that_hides_the_workspace_file() { + let lock = + String::from_utf8(read_fixture("redirect/npm/pnpm/basic/input/pnpm-lock.yaml")).unwrap(); + let module = |data: &str| { + format!( + "module(name = \"app\")\n\ + bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(\n name = \"npm\",\n{data} \ + pnpm_lock = \"//:pnpm-lock.yaml\",\n update_pnpm_lock = True,\n)\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")\n" + ) + }; + let workspace = "# own\npackages:\n - '.'\n"; + let hidden = module(""); + let files = pnpm_workspace(workspace, Some(&lock), &[], &[("MODULE.bazel", &hidden)]); + let (redirect, changed) = assert_pnpm_workspace_parity(&files, true).await; + assert!(changed.is_empty(), "{}", describe(&changed)); + let warned = redirect["warnings"].to_string(); + let code = "redirect_pnpm_bazel_workspace_hidden"; + assert!(warned.contains(code), "{redirect:#}"); + assert!(warned.contains("MODULE.bazel:4: "), "{redirect:#}"); + + let listed = module(" data = [\"//:pnpm-workspace.yaml\"],\n"); + let files = pnpm_workspace(workspace, Some(&lock), &[], &[("MODULE.bazel", &listed)]); + let (redirect, changed) = assert_pnpm_workspace_parity(&files, true).await; + let paths: Vec<&str> = changed.keys().map(String::as_str).collect(); + assert_eq!(paths, ["pnpm-lock.yaml", "pnpm-workspace.yaml"]); + assert!( + !redirect["warnings"].to_string().contains(code), + "{redirect:#}" + ); + + // Listed, but a file that the undo of the pin would remove: both + // engines pin nothing, so that no `rollback` leaves the call with a + // missing file. + let scaffold = "packages:\n - '.'\n"; + let files = pnpm_workspace(scaffold, Some(&lock), &[], &[("MODULE.bazel", &listed)]); + let (redirect, changed) = assert_pnpm_workspace_parity(&files, true).await; + assert!(changed.is_empty(), "{}", describe(&changed)); + let warned = redirect["warnings"].to_string(); + assert!(warned.contains(code), "{redirect:#}"); + assert!( + warned.contains("put a comment line in pnpm-workspace.yaml"), + "{redirect:#}" + ); +} + /// #492: a member lock beside a shared root lock (one listing the member's /// importer) is a stale leftover pnpm never reads: both engines pin the /// root lock alone. diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index 665a07a83..b8e027cba 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -12,6 +12,7 @@ pub mod built; pub mod cargo; pub mod ignore; pub mod maven; +pub mod pnpm; pub mod rc; pub mod starlark; pub mod workspace; diff --git a/crates/socket-patch-core/src/bazel/pnpm.rs b/crates/socket-patch-core/src/bazel/pnpm.rs new file mode 100644 index 000000000..0fdee090e --- /dev/null +++ b/crates/socket-patch-core/src/bazel/pnpm.rs @@ -0,0 +1,1043 @@ +//! Whether the pnpm that Bazel runs for a rules_js hub reads the setting +//! that hosted mode pins a pnpm lock with. +//! +//! `npm.npm_translate_lock(update_pnpm_lock = True)` has aspect_rules_js +//! run a pnpm of its own during the build, whenever the lock or a +//! `package.json` differs from the hashes it keeps under `.aspect/`: +//! `pnpm install --lockfile-only`, in a directory that holds the lock, the +//! `package.json` of each importer and the files the call lists as `data`, +//! and nothing else of the checkout (3.6.0, +//! `npm/private/npm_translate_lock_state.bzl`). Hosted mode names the +//! patch server in the lock and writes `trustLockfile: true` to the +//! `pnpm-workspace.yaml` beside it, without which pnpm 11 and later reject +//! such a lock. A hub that does not list that file hides the setting from +//! its pnpm, and the build fails with `ERR_PNPM_TARBALL_URL_MISMATCH` +//! (Bazel 9.3.2, rules_js 3.6.0, pnpm 11.28.10). pnpm 10 has no such check +//! and builds the pinned lock, and so does pnpm 11 once the file is listed. +//! +//! [`hidden`] finds such a hub for a project, and hosted mode then writes +//! nothing for the project's root pnpm lock. One call of the tag must name +//! the project's `pnpm-lock.yaml` in a plain string and, as far as it is +//! written out, keep it up to date, not list the `pnpm-workspace.yaml` +//! beside it, and run a pnpm that may be 11 or later. +//! +//! A hub that lists the file is passed over only where the pin would be +//! one the build takes and an undo leaves standing. It is not where hosted +//! mode does not write the setting to the file (the file sets +//! `trustLockfile` to something else, or is YAML that a line cannot be +//! added to: the hub's pnpm would reject the lock all the same), and not +//! where the file would hold only what hosted mode writes (none, an empty +//! one, one with the root-only `packages` alone): `rollback` removes such +//! a file with the pin, and a call that names a missing file fails the +//! build. +//! +//! The pnpm of a call is the repository its `use_pnpm` names, `@pnpm` +//! without one. A `pnpm.pnpm` tag of that `name` in the root module makes +//! it, from its `pnpm_version` or from the `packageManager` of the +//! `package.json` that its `pnpm_version_from` names, and of several the +//! newest (`npm/private/pnpm_extension.bzl` at 3.6.0; 2.9.3 has both +//! attributes, 2.0.0 the first). Where no tag states a release, rules_js +//! runs one of its own choice: its newest pnpm 10 at 3.x and 4.0.0-alpha.1, +//! its newest pnpm 8 at 2.x. Neither rejects the lock, so nothing is +//! withheld for a release of the ruleset whose choice was read +//! ([`picks_an_older_pnpm`]); for any other the choice is not known and +//! counts as a pnpm that may be 11 or later. A pnpm release that another +//! module of the build asks for is not seen. +//! +//! A `use_pnpm` is a label of the root module, so its repository is one +//! the root module has a name for. It is followed to a tag only where a +//! `use_repo` takes the repository by position, under the name the +//! extension made it with, and, unless that name is `pnpm`, a tag makes +//! it. A `use_repo` that gives the name to another repository +//! (`eleven = "pnpm"`), and a repository of another extension or of a +//! repository rule, can be any pnpm (the first measured: Bazel 9.3.2 runs +//! the pnpm 11 of the tag `pnpm` under the name `eleven`). +//! +//! In memory the workspace is the project's own files: path selection +//! asks for the `MODULE.bazel` beside a `pnpm-lock.yaml`, and the answer is +//! the one of a checkout with the same files. A hub in a file that one +//! includes, and a Bazel root above the project, are not seen there. A +//! `pnpm_version_from` file that was not handed in (one outside the +//! project's own manifests) and `MODULE.bazel.lock` are not there either: +//! the first reads as a release that is not written out, so a lock that a +//! checkout pins can be left as it is in memory. +//! +//! What is not written out counts against writing, because a broken build +//! outranks a missed patch that a warning explains: an `update_pnpm_lock` +//! that is not the name `False`, a `data` that is not a list of strings, +//! an attribute a `**` may pass, a release that is no version (`latest`, a +//! name, a `package.json` that cannot be read), a `use_pnpm` that is not +//! followed or a use of the pnpm extension that cannot be, and a call that +//! is not a statement of its own. What the reader may not have seen at all +//! ([`Workspace::doubts`], a `WORKSPACE` file) withholds nothing: a +//! project whose lock no listed call names is left as it is. + +use super::rc::ModuleLock; +use super::starlark::{Arg, Call, How, Value}; +use super::workspace::{disk, Entry, Extension, Repo, Workspace}; +use crate::formats::text::strip_bom; +use crate::hosted::guidance::{is_trust_scaffold, plan_workspace_trust, TrustPlan}; +use crate::patch::redirect::RewriteWarning; +use crate::utils::fs::run_blocking; +use crate::utils::package_manager::pinned_version; +use crate::vendor::lock_inventory::{MemoryEntry, ProjectView}; + +/// The code of the warning with which hosted mode leaves a pnpm lock as it +/// is because of such a hub. +pub const HIDDEN: &str = "redirect_pnpm_bazel_workspace_hidden"; + +const LOCK: &str = "pnpm-lock.yaml"; +const SETTINGS: &str = "pnpm-workspace.yaml"; + +/// An extension of `@aspect_rules_js//npm:extensions.bzl`. +fn extension(name: &'static str) -> Extension<'static> { + Extension { + module: "aspect_rules_js", + file: "//npm:extensions.bzl", + name, + } +} + +/// The warning for the project of `view` when a hub hides its +/// `pnpm-workspace.yaml` from a pnpm that may be 11 or later (the module +/// docs), read from the Bazel workspace the project is in: on disk the one +/// of [`super::bazel_root`], in memory the project itself, whose files are +/// all there is. `None` in every other case, and outside a Bazel workspace. +pub async fn hidden(view: &ProjectView<'_>) -> Option { + let detail = match *view { + ProjectView::Memory(project) => { + let read = |path: &str| match project.get(path) { + Some(MemoryEntry::Text(text)) => Entry::Text(text.to_string()), + Some(_) => Entry::Unreadable("it was not handed in as text".to_string()), + None => Entry::Absent, + }; + judge(&read, "") + } + _ => { + let project = view.disk_root()?.to_path_buf(); + run_blocking(move || { + let root = super::bazel_root(&project)?; + // Bazel has `/` between the parts of a path on every system. + let below = root.project.to_string_lossy(); + let below = below.replace(std::path::MAIN_SEPARATOR, "/"); + let read = disk(&root.dir); + judge(&read, &below) + }) + .await + } + }; + detail.map(|detail| RewriteWarning { + code: HIDDEN.into(), + detail, + }) +} + +/// The text of [`hidden`] for the project in the directory `project` (from +/// the Bazel root, empty for the root) of the workspace behind `view`. +fn judge(view: &dyn Fn(&str) -> Entry, project: &str) -> Option { + let ws = Workspace::read(view); + let below = |file: &str| match project { + "" => file.to_string(), + project => format!("{project}/{file}"), + }; + let (lock, settings) = (below(LOCK), below(SETTINGS)); + let main = |label: &str| ws.label(label).filter(|label| label.repo == Repo::Main); + let hubs = ws.tags(&extension("npm"), "npm_translate_lock"); + for (file, call) in hubs.calls.iter().map(|tag| (tag.file, tag.call)) { + let named = match call.arg("pnpm_lock") { + Some(Value::Str(label)) => main(label).filter(|label| label.path() == lock), + _ => None, + }; + let Some(named) = named else { + continue; + }; + let (has, how) = match call.arg("update_pnpm_lock") { + Some(Value::Name(written)) if written == "True" => ("has", "`update_pnpm_lock`"), + Some(Value::Name(written)) if written == "False" => continue, + None if !call.unpacks() => continue, + _ => ( + "may have", + "its `update_pnpm_lock` is not written out as `True` or `False`", + ), + }; + let listed = |label: &String| main(label).is_some_and(|label| label.path() == settings); + // `None`: the call lists the file. Else whether its `data` is + // written out, so that the label is one to add to it. + let written = match call.arg("data") { + Some(Value::List(labels)) if labels.iter().any(listed) => None, + Some(Value::List(_)) => Some(true), + None => Some(!call.unpacks()), + _ => Some(false), + }; + // What the file needs before a pin in the lock is one the build + // takes and an undo leaves standing. + let own = format!( + "put a comment line in {settings} (create the file where there is none: `rollback` \ + removes one that holds only what hosted mode writes, and the call would then name a \ + missing file)" + ); + let (fix, unset) = match view(&settings) { + Entry::Absent => (Some(own), false), + Entry::Text(text) => match plan_workspace_trust(Some(&text)) { + TrustPlan::UserSet(value) => ( + Some(format!( + "set `trustLockfile: true` in {settings} (it says `trustLockfile: \ + {value}`, which hosted mode leaves as it is)" + )), + true, + ), + TrustPlan::Unsupported(why) => ( + Some(format!( + "write `trustLockfile: true` to {settings} yourself (hosted mode does \ + not add it there: {why})" + )), + true, + ), + _ if removed_with_the_pin(&text) => (Some(own), false), + _ => (None, false), + }, + Entry::Unreadable(_) => (None, false), + }; + if written.is_none() && fix.is_none() { + continue; + } + let Some(pnpm) = release(&ws, view, call) else { + continue; + }; + // The label of the file beside the lock, in the lock's own package. + let beside = match named.name.rsplit_once('/') { + Some((directory, _)) => format!("{directory}/{SETTINGS}"), + None => SETTINGS.to_string(), + }; + let label = format!("`//{}:{beside}`", named.package); + let rejects = "pnpm 11 and later reject a lock that names the patch server \ + (ERR_PNPM_TARBALL_URL_MISMATCH): `bazel build` would fail"; + // A `data` that is not written out may hold the label already: it + // is the call that has to show it. + let (why, list) = match written { + Some(true) => ( + format!( + "its `data` does not list {settings}. That pnpm reads only the lock, the \ + `package.json` files and the `data` of the call, so it would not see the \ + `trustLockfile: true` that hosted mode writes to {settings}, and without \ + it {rejects}" + ), + Some(format!("list {label} in the `data` of that call")), + ), + Some(false) => ( + format!( + "its `data` is not written out as a list of strings, so it is not known to \ + list {settings}. That pnpm reads only the lock, the `package.json` files \ + and the `data` of the call, so it may not see the `trustLockfile: true` \ + that hosted mode writes to {settings}, and without it {rejects}" + ), + Some(format!( + "write the `data` of that call out as a list of strings that holds {label}" + )), + ), + None if unset => ( + format!( + "hosted mode does not write `trustLockfile: true` to the {settings} that \ + its `data` lists. Without that setting {rejects}" + ), + None, + ), + None => ( + format!( + "the {settings} that its `data` lists would hold only what hosted mode \ + writes. A later `rollback` removes such a file, the call would then name \ + a missing file, and `bazel build` would fail" + ), + None, + ), + }; + let steps: Vec = fix.into_iter().chain(list).collect(); + // Every path of the text is one from the Bazel root. + let from = match project { + "" => "", + _ => ", with paths from the root of the Bazel workspace", + }; + return Some(format!( + "{file}:{}{from}: this `{}` {has} Bazel run {pnpm} to keep {lock} up to date \ + ({how}), and {why}; {lock} was not rewritten — {} and re-run", + call.line, + call.callee, + steps.join(", ") + )); + } + None +} + +/// Whether `rollback` removes a `pnpm-workspace.yaml` of this text with a +/// hosted pin: with the setting in it, the file is byte for byte the one +/// hosted mode creates, which the undo cannot tell from the user's own +/// (`cleanup_side_config` of the npm restore). +fn removed_with_the_pin(text: &str) -> bool { + match plan_workspace_trust(Some(text)) { + TrustPlan::Append(pinned) | TrustPlan::Scaffold(pinned) => is_trust_scaffold(&pinned), + TrustPlan::AlreadyTrue => is_trust_scaffold(text), + _ => false, + } +} + +/// The pnpm that the hub `hub` runs, when it may be 11 or later: the newest +/// release a tag of its repository states, or that one is not written out, +/// or the one a release of rules_js picks whose choice is not known (the +/// module docs). `None` when all that is stated is older, and when nothing +/// is and [`picks_an_older_pnpm`]. +fn release(ws: &Workspace, view: &dyn Fn(&str) -> Entry, hub: &Call) -> Option { + let unread = "a pnpm whose release is not written out as a version (it may be 11 or later)"; + // Whether a `use_repo` takes the repository `repo` under that very name. + let taken = |repo: &String| { + let takes = |call: &&Call| call.bind.is_none() && call.callee == "use_repo"; + let named = |arg: &Arg| arg.how == How::Positional && arg.value == Value::Str(repo.clone()); + let calls = ws.files.iter().flat_map(|(_, file)| &file.calls); + calls.filter(takes).any(|call| call.args.iter().any(named)) + }; + let repo = match hub.arg("use_pnpm") { + None if !hub.unpacks() => "pnpm".to_string(), + Some(Value::Str(label)) => match ws.label(label).map(|label| label.repo) { + Some(Repo::Apparent(repo)) if taken(&repo) => repo, + _ => return Some(unread.to_string()), + }, + _ => return Some(unread.to_string()), + }; + let tags = ws.tags(&extension("pnpm"), "pnpm"); + // Without a tag, the repository `pnpm` is the one rules_js makes. + let (mut newest, mut made) = (None::<((u64, u64, u64), String)>, repo == "pnpm"); + let mut read = tags.doubts.is_empty(); + for call in tags.calls.iter().map(|tag| tag.call) { + match call.arg("name") { + None if !call.unpacks() && repo != "pnpm" => continue, + Some(Value::Str(name)) if *name != repo => continue, + _ => made = true, + } + let stated = match (call.arg("pnpm_version_from"), call.arg("pnpm_version")) { + // A tag that states no release asks for the one rules_js picks. + (None, None) if !call.unpacks() => continue, + (None, Some(Value::Str(version))) if version.is_empty() => continue, + (None, Some(Value::Str(version))) => Some(version.clone()), + (Some(Value::Str(label)), _) => { + let file = ws.label(label).filter(|label| label.repo == Repo::Main); + let text = match file.map(|file| view(&file.path())) { + Some(Entry::Text(text)) => text, + _ => String::new(), + }; + let json = serde_json::from_str::(strip_bom(&text)).ok(); + let spec = json + .as_ref() + .and_then(|json| json["packageManager"].as_str()); + spec.and_then(|spec| pinned_version(spec, "pnpm")) + .map(str::to_string) + } + _ => None, + }; + // The numbers of a release: rules_js runs the newest of several. + let numbers = |version: &String| { + let release = version.split(['-', '+']).next().unwrap_or(version); + let mut parts = release.split('.').map(|part| part.parse::().ok()); + let major = parts.next()??; + let rest = |part: Option>| part.flatten().unwrap_or(0); + Some((major, rest(parts.next()), rest(parts.next()))) + }; + match stated.as_ref().and_then(numbers) { + Some(new) if newest.as_ref().is_none_or(|(old, _)| new > *old) => { + newest = stated.map(|version| (new, version)); + } + Some(_) => {} + None => read = false, + } + } + match newest { + Some(((major, ..), version)) if major >= 11 => Some(format!("pnpm {version}")), + _ if !read || !made => Some(unread.to_string()), + Some(_) => None, + None if picks_an_older_pnpm(ws, view) => None, + None => Some( + "the pnpm that aspect_rules_js picks itself, at a release of the ruleset whose \ + choice is not known here (it may be 11 or later)" + .to_string(), + ), + } +} + +/// Whether the pnpm that rules_js runs where no tag states a release is +/// known to be older than 11. Its releases pick the newest pnpm 8 they +/// carry through 2.9.3 and the newest pnpm 10 from 3.0.0 through 3.6.0 and +/// at 4.0.0-alpha.0 and 4.0.0-alpha.1 (`DEFAULT_PNPM_VERSION` in +/// `npm/private/pnpm_repository.bzl`; 1.42.3 its last pnpm 8). So it is +/// known for a release of 1, 2 or 3 and for those two, which is what the +/// root module has to ask for, by `bazel_dep` or a `single_version_override` +/// with a version, and what `MODULE.bazel.lock`, where there is one, has to +/// have selected. An override that takes the ruleset from elsewhere, a +/// version that is no string and any later release are not known. +fn picks_an_older_pnpm(ws: &Workspace, view: &dyn Fn(&str) -> Entry) -> bool { + const RULESET: &str = "aspect_rules_js"; + let module = Some(&Value::Str(RULESET.to_string())); + let names = |call: &&Call| { + call.bind.is_none() && [call.arg("name"), call.arg("module_name")].contains(&module) + }; + let calls = ws.files.iter().flat_map(|(_, file)| &file.calls); + let calls: Vec<&Call> = calls.filter(names).collect(); + let pin = "single_version_override"; + let version = |callee: &str| { + let call = calls.iter().find(|call| call.callee == callee); + call.and_then(|call| call.arg("version")) + }; + let elsewhere = |call: &&Call| call.callee.ends_with("_override") && call.callee != pin; + let asked = match (version(pin), version("bazel_dep")) { + _ if calls.iter().any(elsewhere) => return false, + (Some(Value::Str(pinned)), _) if !pinned.is_empty() => pinned.clone(), + (None | Some(Value::Str(_)), Some(Value::Str(least))) => least.clone(), + _ => return false, + }; + let known = |release: &str| { + let release = release.split('+').next().unwrap_or(release); + let major = release + .split(['.', '-']) + .next() + .and_then(|major| major.parse::().ok()); + matches!(major, Some(1..=3)) || ["4.0.0-alpha.0", "4.0.0-alpha.1"].contains(&release) + }; + let selected = match view("MODULE.bazel.lock") { + Entry::Text(lock) => ModuleLock::parse(&lock) + .selected(RULESET) + .iter() + .all(|r| known(r)), + _ => true, + }; + known(&asked) && selected +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vendor::lock_inventory::MemoryProject; + + /// The root module of a workspace whose hub is `hub`, on line 4, with + /// the lines `pnpm` after the proxy of the pnpm extension. + fn module(hub: &str, pnpm: &str) -> String { + format!( + "module(name = \"app\")\n\ + bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock({hub})\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + {pnpm}\n" + ) + } + + /// The hub of the measured build: it names the lock at the root + /// ([`LOCKED`]), keeps it up to date and lists nothing. + const HUB: &str = "pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = True"; + const LOCKED: &str = "pnpm_lock = \"//:pnpm-lock.yaml\""; + /// The tag that states the pnpm of that build. + const ELEVEN: &str = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")"; + + /// [`judge`] for the project in `project` of the workspace that holds + /// `files` and nothing else. + fn said(files: &[(&str, &str)], project: &str) -> Option { + let view = |path: &str| match files.iter().find(|(name, _)| *name == path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }; + judge(&view, project) + } + + /// [`said`] for the root project of a workspace with `module` and a + /// `pnpm-workspace.yaml` of the user's own. + fn root(hub: &str, pnpm: &str) -> Option { + said( + &[("MODULE.bazel", &module(hub, pnpm)), (SETTINGS, "# own\n")], + "", + ) + } + + /// The step for a file that would hold only what hosted mode writes. + const OWN: &str = "put a comment line in pnpm-workspace.yaml (create the file where there \ + is none: `rollback` removes one that holds only what hosted mode writes, \ + and the call would then name a missing file)"; + + #[test] + fn the_warning_names_the_call_and_the_line_to_add() { + let module = module(HUB, ELEVEN); + let said_of = |files: &[(&str, &str)]| said(files, "").expect("withheld"); + // The project has a `pnpm-workspace.yaml`: one line is the way on. + let listed = said_of(&[("MODULE.bazel", &module), (SETTINGS, "packages: []\n")]); + assert_eq!( + listed, + "MODULE.bazel:4: this `npm.npm_translate_lock` has Bazel run pnpm 11.28.10 to keep \ + pnpm-lock.yaml up to date (`update_pnpm_lock`), and its `data` does not list \ + pnpm-workspace.yaml. That pnpm reads only the lock, the `package.json` files and \ + the `data` of the call, so it would not see the `trustLockfile: true` that hosted \ + mode writes to pnpm-workspace.yaml, and without it pnpm 11 and later reject a lock \ + that names the patch server (ERR_PNPM_TARBALL_URL_MISMATCH): `bazel build` would \ + fail; pnpm-lock.yaml was not rewritten — list `//:pnpm-workspace.yaml` in the \ + `data` of that call and re-run" + ); + // The call is named as the file writes it. + let other = module + .replace("\nnpm = use_extension", "\njs = use_extension") + .replace("\nnpm.npm_translate_lock(", "\njs.npm_translate_lock("); + assert!(other.contains("\njs.npm_translate_lock(") && other.contains("\npnpm = ")); + let written = said_of(&[("MODULE.bazel", &other), (SETTINGS, "packages: []\n")]); + assert_eq!( + written, + listed.replace("`npm.npm_translate_lock`", "`js.npm_translate_lock`") + ); + // It has none, or one that the undo of the pin would remove because + // with the setting it is the file hosted mode creates: a line of + // the user's own comes first, so that no undo leaves the call with + // a missing file. + let (reason, way_on) = listed.split_once(" — ").expect("the way on"); + let absent = said_of(&[("MODULE.bazel", &module)]); + assert_eq!(absent, format!("{reason} — {OWN}, {way_on}")); + let scaffold = "packages:\n - '.'\ntrustLockfile: true\n"; + assert!(is_trust_scaffold(scaffold)); + let cases = [ + ("", true), + ("packages:\n - '.'\n", true), + ("packages:\r\n - '.'\r\n", true), + (scaffold, true), + ("# mine\npackages:\n - '.'\n", false), + ("packages:\n - 'apps/*'\n", false), + ]; + for (text, removed) in cases { + let said = said_of(&[("MODULE.bazel", &module), (SETTINGS, text)]); + let more = if removed { + format!("{OWN}, ") + } else { + String::new() + }; + assert_eq!(said, format!("{reason} — {more}{way_on}"), "{text:?}"); + } + // It has one that hosted mode does not write the setting to: with + // the label alone the next run would still pin nothing. + let off = "packages:\n - '.'\ntrustLockfile: false\n"; + let said = said_of(&[("MODULE.bazel", &module), (SETTINGS, off)]); + let set = "set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ + false`, which hosted mode leaves as it is)"; + assert_eq!(said, format!("{reason} — {set}, {way_on}")); + let flow = said_of(&[("MODULE.bazel", &module), (SETTINGS, "{packages: ['.']}\n")]); + let write = " — write `trustLockfile: true` to pnpm-workspace.yaml yourself (hosted \ + mode does not add it there: "; + assert!(flow.starts_with(reason) && flow.contains(write), "{flow}"); + assert!(flow.ends_with(&format!("), {way_on}")), "{flow}"); + } + + /// A hub that lists the file is passed over only where the pin is one + /// the build takes and an undo leaves standing. + #[test] + fn a_listed_file_has_to_hold_the_setting_and_a_line_of_the_users_own() { + let hub = format!("{HUB}, data = [\"//:pnpm-workspace.yaml\"]"); + let with = |pnpm: &str, text: Option<&str>| { + let module = module(&hub, pnpm); + let mut files = vec![("MODULE.bazel", module.as_str())]; + files.extend(text.map(|text| (SETTINGS, text))); + said(&files, "") + }; + let start = "MODULE.bazel:4: this `npm.npm_translate_lock` has Bazel run pnpm 11.28.10 \ + to keep pnpm-lock.yaml up to date (`update_pnpm_lock`), and "; + // `rollback` would remove it with the pin, and the call names it. + let gone = format!( + "{start}the pnpm-workspace.yaml that its `data` lists would hold only what hosted \ + mode writes. A later `rollback` removes such a file, the call would then name a \ + missing file, and `bazel build` would fail; pnpm-lock.yaml was not rewritten — \ + {OWN} and re-run" + ); + let scaffold = "packages:\n - '.'\ntrustLockfile: true\n"; + for text in [None, Some(""), Some("packages:\n - '.'\n"), Some(scaffold)] { + assert_eq!(with(ELEVEN, text), Some(gone.clone()), "{text:?}"); + } + // Hosted mode does not write the setting to it: the pnpm of the + // hub would reject the pinned lock although it reads the file. + let unset = format!( + "{start}hosted mode does not write `trustLockfile: true` to the pnpm-workspace.yaml \ + that its `data` lists. Without that setting pnpm 11 and later reject a lock that \ + names the patch server (ERR_PNPM_TARBALL_URL_MISMATCH): `bazel build` would fail; \ + pnpm-lock.yaml was not rewritten — " + ); + let off = with(ELEVEN, Some("# mine\ntrustLockfile: false\n")).expect("withheld"); + let set = "set `trustLockfile: true` in pnpm-workspace.yaml (it says `trustLockfile: \ + false`, which hosted mode leaves as it is) and re-run"; + assert_eq!(off, format!("{unset}{set}")); + let flow = with(ELEVEN, Some("{packages: ['.']}\n")).expect("withheld"); + let write = "write `trustLockfile: true` to pnpm-workspace.yaml yourself (hosted mode \ + does not add it there: "; + assert!(flow.starts_with(&format!("{unset}{write}")), "{flow}"); + assert!(flow.ends_with(") and re-run"), "{flow}"); + // A file with a line of the user's own that takes the setting, or + // has it: pinned as without the hub. And a pnpm that rejects no + // lock is not asked about the file at all. + for text in [ + "# mine\n", + "packages:\n - 'apps/*'\n", + "# mine\npackages:\n - '.'\ntrustLockfile: true\n", + ] { + assert_eq!(with(ELEVEN, Some(text)), None, "{text:?}"); + } + let ten = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"10.34.9\")"; + assert_eq!(with(ten, None), None); + assert_eq!(with("", Some("")), None); + } + + /// Where no tag states a release, rules_js runs a pnpm of its own + /// choice, which is known for the releases it was read in and for no + /// other. + #[test] + fn the_choice_of_rules_js_is_known_for_the_releases_it_was_read_in() { + let dep = "bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n"; + let asking = |ask: &str, lock: Option<&str>| { + let module = module(HUB, "").replace(dep, ask); + assert!(!module.contains("3.6.0") || ask.contains("3.6.0"), "{ask}"); + let mut files = vec![("MODULE.bazel", module.as_str()), (SETTINGS, "# own\n")]; + files.extend(lock.map(|lock| ("MODULE.bazel.lock", lock))); + said(&files, "") + }; + let at = + |version: &str| format!("bazel_dep(name = \"aspect_rules_js\", version = {version})\n"); + for known in [ + "1.42.3", + "2.9.3", + "3.0.0", + "3.6.0", + "4.0.0-alpha.0", + "4.0.0-alpha.1", + ] { + assert_eq!(asking(&at(&format!("\"{known}\"")), None), None, "{known}"); + } + let unknown = "has Bazel run the pnpm that aspect_rules_js picks itself, at a release of \ + the ruleset whose choice is not known here (it may be 11 or later) to keep"; + let pinned = |version: &str| { + format!( + "{dep}single_version_override(module_name = \"aspect_rules_js\", version = \ + {version})\n" + ) + }; + let elsewhere = format!( + "{dep}git_override(module_name = \"aspect_rules_js\", remote = \"https://example\")\n" + ); + for ask in [ + at("\"4.0.0\""), + at("\"4.1.2\""), + at("\"5.0.0-rc.1\""), + at("RULES_JS"), + at("\"\""), + pinned("\"4.0.0\""), + pinned("PIN"), + elsewhere, + ] { + let said = asking(&ask, None).unwrap_or_else(|| panic!("{ask}: not withheld")); + assert!(said.contains(unknown), "{ask}: {said}"); + } + // A pin decides whatever is asked for, and one without a version + // leaves the release to what is asked for. + assert_eq!( + asking(&pinned("\"3.5.2\"").replace("3.6.0", "4.0.0"), None), + None + ); + let unpinned = format!("{dep}single_version_override(module_name = \"aspect_rules_js\")\n"); + assert_eq!(asking(&unpinned, None), None); + // What Bazel selected, where its lock says: another module of the + // build can ask for a later release than the root does. + let lock = |release: &str| { + format!( + "{{\"lockFileVersion\": 28, \"registryFileHashes\": {{\ + \"https://bcr.bazel.build/modules/aspect_rules_js/{release}/source.json\": \"x\"}}}}" + ) + }; + assert_eq!(asking(dep, Some(&lock("3.6.0"))), None); + let later = asking(dep, Some(&lock("4.2.0"))).expect("withheld"); + assert!(later.contains(unknown), "{later}"); + // A release that a tag states is the one rules_js runs, whatever + // its own choice would be. + let ten = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"10.34.9\")"; + let stated = module(HUB, ten).replace(dep, &at("\"4.1.2\"")); + assert_eq!( + said(&[("MODULE.bazel", &stated), (SETTINGS, "# own\n")], ""), + None + ); + } + + #[test] + fn nothing_is_withheld_where_the_build_takes_the_pinned_lock() { + let listing = |label: &str| format!("{HUB}, data = [\"//:package.json\", \"{label}\"]"); + let ten = "pnpm.pnpm(name = \"pnpm\", pnpm_version = \"10.34.9\")"; + let other = "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")"; + let named = "pnpm.pnpm(pnpm_version = \"11.28.10\")\n\ + pnpm.pnpm(name = \"ten\", pnpm_version = \"10.34.9\")\n\ + use_repo(pnpm, \"pnpm\", \"ten\")"; + let by_label = format!("{HUB}, use_pnpm = \"@pnpm//:package/bin/pnpm.cjs\""); + let cases = [ + ("no update", LOCKED.to_string(), ELEVEN), + ( + "update off", + format!("{LOCKED}, update_pnpm_lock = False"), + ELEVEN, + ), + ("listed", listing("//:pnpm-workspace.yaml"), ELEVEN), + ( + "listed, in the package", + listing(":pnpm-workspace.yaml"), + ELEVEN, + ), + ( + "listed, by its name", + listing("pnpm-workspace.yaml"), + ELEVEN, + ), + ( + "listed, with `@`", + listing("@//:pnpm-workspace.yaml"), + ELEVEN, + ), + ( + "listed, with the module", + listing("@app//:pnpm-workspace.yaml"), + ELEVEN, + ), + ("pnpm 10", HUB.to_string(), ten), + ("no release", HUB.to_string(), ""), + ( + "a tag without a release", + HUB.to_string(), + "pnpm.pnpm(name = \"pnpm\")", + ), + ( + "an empty release", + HUB.to_string(), + "pnpm.pnpm(pnpm_version = \"\")", + ), + ("pnpm 11 in another repository", HUB.to_string(), other), + ( + "the lock of another project", + HUB.replace("//:", "//web:"), + ELEVEN, + ), + ( + "the lock of another repository", + HUB.replace("//:", "@other//:"), + ELEVEN, + ), + ( + "pnpm 10 in the repository the hub names", + format!("{HUB}, use_pnpm = \"@ten//:package/bin/pnpm.cjs\""), + named, + ), + ( + "the pnpm of rules_js by its label", + by_label.clone(), + "use_repo(pnpm, \"pnpm\")", + ), + ( + "pnpm 10 by its label", + by_label, + "pnpm.pnpm(pnpm_version = \"10.34.9\")\nuse_repo(pnpm, \"pnpm\")", + ), + ( + "a lock that is no string", + HUB.replace("\"//:pnpm-lock.yaml\"", "LOCK"), + ELEVEN, + ), + ]; + for (case, hub, pnpm) in cases { + assert_eq!(root(&hub, pnpm), None, "{case}"); + } + // No workspace file, one that asks for another ruleset's extension, + // and a project that is not the one whose lock the hub names. + assert_eq!(said(&[], ""), None); + let other = module(HUB, ELEVEN).replace("@aspect_rules_js//npm", "@rules_other//npm"); + assert_eq!(said(&[("MODULE.bazel", &other)], ""), None); + assert_eq!(said(&[("MODULE.bazel", &module(HUB, ELEVEN))], "web"), None); + // A part of the workspace that cannot be read withholds nothing by + // itself: the call that is read builds the pinned lock. + let unread = format!("{}include(\"//:missing.MODULE.bazel\")\n", module(HUB, ten)); + assert_eq!(said(&[("MODULE.bazel", &unread)], ""), None); + } + + #[test] + fn what_is_not_written_out_counts_against_writing() { + let eleven = "has Bazel run pnpm 11.28.10 to keep"; + let may = "may have Bazel run pnpm 11.28.10 to keep"; + let unlisted = "is not written out as a list of strings, so it is not known to list"; + let unread = "Bazel run a pnpm whose release is not written out as a version (it may be"; + let also = |more: &str| format!("{HUB}, {more}"); + let two = "pnpm.pnpm(pnpm_version = \"10.34.9\")\n"; + let named = "pnpm.pnpm(name = \"eleven\", pnpm_version = \"11.28.10\")\n\ + use_repo(pnpm, \"eleven\")"; + let by_label = |repo: &str| also(&format!("use_pnpm = \"@{repo}//:package/bin/pnpm.cjs\"")); + let other = "tools = use_extension(\"//:tools.bzl\", \"tools\")\nuse_repo(tools, \"mine\")"; + let renamed = format!( + "{ELEVEN}\npnpm.pnpm(name = \"ten\", pnpm_version = \"10.34.9\")\n\ + use_repo(pnpm, ten = \"pnpm\")" + ); + let cases = [ + ("the measured hub", HUB.to_string(), ELEVEN, eleven), + ( + "an update that is a name", + format!("{LOCKED}, update_pnpm_lock = UP"), + ELEVEN, + may, + ), + ( + "an update that `**` may pass", + format!("{LOCKED}, **COMMON"), + ELEVEN, + "may have Bazel run a pnpm whose release is not written out", + ), + ( + "data that `**` may pass", + also("**COMMON"), + ELEVEN, + unlisted, + ), + ("data that is a name", also("data = DATA"), ELEVEN, unlisted), + ( + "data that is a sum", + also("data = [\"//:pnpm-workspace.yaml\"] + MORE"), + ELEVEN, + unlisted, + ), + ( + "data without the file", + also("data = [\"//web:pnpm-workspace.yaml\", \"@other//:pnpm-workspace.yaml\"]"), + ELEVEN, + "does not list", + ), + ( + "the newest release", + HUB.to_string(), + "pnpm.pnpm(pnpm_version = \"latest\")", + unread, + ), + ( + "a release that is a name", + HUB.to_string(), + "pnpm.pnpm(pnpm_version = PNPM)", + unread, + ), + ( + "a tag that passes `**`", + HUB.to_string(), + "pnpm.pnpm(**PNPM)", + unread, + ), + ( + "a file that is not there", + HUB.to_string(), + "pnpm.pnpm(pnpm_version_from = \"//:package.json\")", + unread, + ), + ( + "a proxy that is used otherwise", + HUB.to_string(), + "TOOLS = [pnpm]", + unread, + ), + ( + "an entry point of the checkout", + also("use_pnpm = \"//tools:pnpm.cjs\""), + "", + unread, + ), + ( + "an entry point that is a name", + also("use_pnpm = PNPM"), + "", + unread, + ), + ( + "a tag whose name is a name", + HUB.to_string(), + "pnpm.pnpm(name = NAME, pnpm_version = \"11.28.10\")", + eleven, + ), + ( + "the newest of two tags", + HUB.to_string(), + &format!("{two}{ELEVEN}"), + eleven, + ), + ( + "the newest of two tags of one major", + HUB.to_string(), + &format!("pnpm.pnpm(pnpm_version = \"11.3.0\")\n{ELEVEN}"), + eleven, + ), + ( + "the newest of two tags, the first", + HUB.to_string(), + &format!("{ELEVEN}\npnpm.pnpm(pnpm_version = \"11.3.0\")"), + eleven, + ), + ( + "the repository the hub names", + by_label("eleven"), + &format!("{two}{named}"), + eleven, + ), + // Bazel 9.3.2 runs the pnpm 11 of this tag for this hub. + ( + "a repository under another name", + by_label("eleven"), + &format!("{ELEVEN}\nuse_repo(pnpm, eleven = \"pnpm\")"), + unread, + ), + // The name is that of a tag which makes another repository. + ( + "a repository under the name of a tag", + by_label("ten"), + &renamed, + unread, + ), + ( + "a repository of another extension", + by_label("mine"), + other, + unread, + ), + ( + "a repository no `use_repo` takes", + by_label("pnpm"), + "", + unread, + ), + ]; + let out = "write the `data` of that call out as a list of strings that holds \ + `//:pnpm-workspace.yaml` and re-run"; + for (case, hub, pnpm, part) in cases { + let said = root(&hub, pnpm).unwrap_or_else(|| panic!("{case}: not withheld")); + assert!(said.contains(part), "{case}: {said}"); + assert!(said.starts_with("MODULE.bazel:4: "), "{case}: {said}"); + // Only a `data` that is written out is one to add the label to. + let written_out = said.ends_with(out); + assert_eq!(said.contains(unlisted), written_out, "{case}: {said}"); + } + // A call that may not run, one of a proxy that Bazel drops under + // `--ignore_dev_dependency`, and one beside a file that cannot be + // read are taken as they are written. + let module = module(HUB, ELEVEN); + let hub = format!("npm.npm_translate_lock({HUB})"); + let behind = module.replace(&hub, &format!("UPDATE and {hub}")); + let dev = module.replace("\"npm\")", "\"npm\", dev_dependency = True)"); + let unread = format!("{module}include(\"//:missing.MODULE.bazel\")\n"); + for (case, module) in [ + ("a condition", behind), + ("a dev proxy", dev), + ("a missing file", unread), + ] { + assert_ne!(module, self::module(HUB, ELEVEN), "{case}"); + let said = said(&[("MODULE.bazel", &module)], ""); + assert!(said.is_some_and(|said| said.contains(eleven)), "{case}"); + } + } + + #[test] + fn the_release_of_a_package_json_is_its_package_manager() { + let from = "pnpm.pnpm(pnpm_version_from = \"//:package.json\")"; + let module = module(HUB, from); + let with = |manifest: &str| { + let files = [ + ("MODULE.bazel", module.as_str()), + ("package.json", manifest), + ]; + said(&files, "") + }; + let pinned = |pin: &str| with(&format!("{{\"packageManager\": \"{pin}\"}}")); + let eleven = pinned("pnpm@11.2.0+sha512.abc").expect("withheld"); + assert!( + eleven.contains("has Bazel run pnpm 11.2.0 to keep"), + "{eleven}" + ); + assert_eq!(pinned("pnpm@10.34.9"), None); + // rules_js fails on each of these; none is read as a release. + for manifest in ["{\"packageManager\": \"yarn@4.0.0\"}", "{}", "no JSON"] { + let said = with(manifest).expect("withheld"); + assert!( + said.contains("is not written out as a version"), + "{manifest}: {said}" + ); + } + } + + #[test] + fn a_project_below_the_root_is_named_from_the_root() { + let hub = |lock: &str, data: &str| { + let hub = format!("pnpm_lock = \"{lock}\", update_pnpm_lock = True{data}"); + let module = module(&hub, ELEVEN); + said( + &[ + ("MODULE.bazel", &module), + ("web/pnpm-workspace.yaml", "# own\n"), + ], + "web", + ) + }; + let said = hub("//web:pnpm-lock.yaml", "").expect("withheld"); + // Its paths are not the ones of a run in the project's directory. + let from = "MODULE.bazel:4, with paths from the root of the Bazel workspace: this \ + `npm.npm_translate_lock` has Bazel run"; + assert!(said.starts_with(from), "{said}"); + assert!( + said.contains("to keep web/pnpm-lock.yaml up to date"), + "{said}" + ); + assert!( + said.contains("; web/pnpm-lock.yaml was not rewritten — "), + "{said}" + ); + assert!( + said.contains("does not list web/pnpm-workspace.yaml."), + "{said}" + ); + assert!( + said.contains(" — list `//web:pnpm-workspace.yaml` in"), + "{said}" + ); + // The label is one of the package the call takes the lock from. + let said = hub("//:web/pnpm-lock.yaml", "").expect("withheld"); + assert!( + said.contains(" — list `//:web/pnpm-workspace.yaml` in"), + "{said}" + ); + // The file of the root is not the one beside the lock. + assert!(hub( + "//web:pnpm-lock.yaml", + ", data = [\"//:pnpm-workspace.yaml\"]" + ) + .is_some()); + for listed in ["//web:pnpm-workspace.yaml", "//:web/pnpm-workspace.yaml"] { + let data = format!(", data = [\"{listed}\"]"); + assert_eq!(hub("//web:pnpm-lock.yaml", &data), None, "{listed}"); + } + assert_eq!(hub("//:pnpm-lock.yaml", ""), None, "the lock of the root"); + } + + /// A checkout and a project in memory with the same files get the same + /// warning, and a checkout that is no Bazel workspace gets none. + #[tokio::test] + async fn a_checkout_and_a_project_in_memory_are_told_the_same() { + let module = module(HUB, ELEVEN); + let dir = tempfile::tempdir().expect("a directory"); + let mut project = MemoryProject::new(); + assert_eq!(hidden(&ProjectView::Disk(dir.path())).await, None); + assert_eq!(hidden(&ProjectView::Memory(&project)).await, None); + for (name, text) in [ + ("MODULE.bazel", module.as_str()), + (LOCK, "lockfileVersion: '9.0'\n"), + ] { + std::fs::write(dir.path().join(name), text).expect("write"); + project.insert_text(name, text); + } + let on_disk = hidden(&ProjectView::Disk(dir.path())) + .await + .expect("withheld"); + assert_eq!(on_disk.code, HIDDEN); + assert!( + on_disk.detail.starts_with("MODULE.bazel:4: "), + "{}", + on_disk.detail + ); + assert_eq!(hidden(&ProjectView::Memory(&project)).await, Some(on_disk)); + } +} diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index a63f0fd70..5690b7fad 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -891,7 +891,9 @@ pub struct CandidateFiles { /// workspace keeps one lock per member but the members cannot be /// listed (#492), `gitBranchLockfile` installs the branch from a /// `pnpm-lock..yaml` (#556), or pnpm's `lockfile` setting is - /// off so pnpm reads no lock at all (#1074). The root lock was left out of + /// off so pnpm reads no lock at all (#1074). And when a pin in it would + /// fail the Bazel build of the project ([`crate::bazel::pnpm`]). The + /// root lock was left out of /// `files`, and the rewrite reports this instead of a redirect or a /// "no lockfile" hint. pub pnpm_refusal: Option, @@ -1648,7 +1650,14 @@ pub async fn read_candidate_files_in( } else if let Some(branch) = crate::utils::pnpm_workspace::git_branch_locks(view).await { refuse_git_branch_locks(&mut out, &branch); } else { + // A hub stands against a pin in the root lock it reads, not + // against the members' own locks, which no hub of this answer + // reads: they are read and pinned as without it. + let hidden = bazel_hides_pnpm_workspace(view, &out).await; read_pnpm_member_locks(view, unreadable, &mut out).await; + if let Some(hidden) = hidden { + withhold_root_pnpm_locks(&mut out, hidden); + } } } if candidates.iter().any(|c| c.dep.ecosystem == "gem") { @@ -1791,13 +1800,32 @@ fn refuse_git_branch_locks( withhold_root_pnpm_locks(out, git_branch_lock_refusal(branch)); } +/// The refusal for a project whose `pnpm-lock.yaml` a rules_js hub of its +/// Bazel workspace keeps up to date with a pnpm that would not read the +/// `trustLockfile: true` a hosted pin needs ([`crate::bazel::pnpm::hidden`]): +/// the build would fail on the pinned lock, so the caller leaves the root +/// locks out and the run refuses every pin in them (see +/// [`withhold_root_pnpm_locks`]). Nothing of Bazel is read for a project +/// without that lock. +async fn bazel_hides_pnpm_workspace( + view: &ProjectView<'_>, + out: &CandidateFiles, +) -> Option { + if !out.files.contains_key(ROOT_PNPM_LOCKS[0]) { + return None; + } + crate::bazel::pnpm::hidden(view).await +} + /// The root pnpm locks (see [`withhold_root_pnpm_locks`]). const ROOT_PNPM_LOCKS: [&str; 2] = ["pnpm-lock.yaml", "shrinkwrap.yaml"]; /// Leave every root pnpm lock out of the run and refuse every pnpm pin /// with `refusal` (see [`CandidateFiles::pnpm_refusal`]): a branch lock -/// (#556) or pnpm's `lockfile` setting off (#1074, where pnpm reads no -/// lock at all; member locks are never read then). In memory the root +/// (#556), pnpm's `lockfile` setting off (#1074, where pnpm reads no +/// lock at all; member locks are never read then), or a Bazel hub that +/// would fail on a pin in the root lock ([`bazel_hides_pnpm_workspace`]; +/// the members' own locks are read all the same). In memory the root /// lock is dropped from the link and unreadable lists too: it is not /// written. fn withhold_root_pnpm_locks(out: &mut CandidateFiles, refusal: RewriteWarning) { @@ -8791,6 +8819,48 @@ snapshots: assert!(again.rewrite.files.contains_key(PNPM_WORKSPACE_REL)); } + /// A Bazel hub that stands against a pin in the root lock + /// ([`crate::bazel::pnpm`]) reads that lock alone. The members' own + /// locks are read and pinned as without it; the root lock is left out. + #[tokio::test] + async fn member_locks_are_pinned_beside_a_root_lock_that_a_bazel_hub_withholds() { + let tmp = tempfile::tempdir().unwrap(); + let ws = "packages:\n - 'packages/*'\nsharedWorkspaceLockfile: false\n"; + write_member_workspace(tmp.path(), ws); + write_rel( + tmp.path(), + "MODULE.bazel", + "bazel_dep(name = \"aspect_rules_js\", version = \"3.6.0\")\n\ + npm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"npm\")\n\ + npm.npm_translate_lock(pnpm_lock = \"//:pnpm-lock.yaml\", update_pnpm_lock = True)\n\ + pnpm = use_extension(\"@aspect_rules_js//npm:extensions.bzl\", \"pnpm\")\n\ + pnpm.pnpm(name = \"pnpm\", pnpm_version = \"11.28.10\")\n", + ); + let (read, done) = member_rewrite(tmp.path()).await; + let hidden = crate::bazel::pnpm::HIDDEN; + assert_eq!( + read.pnpm_refusal.as_ref().map(|w| w.code.as_str()), + Some(hidden) + ); + assert!(!read.files.contains_key("pnpm-lock.yaml")); + assert_eq!(read.pnpm_member_lock_keys, MEMBER_KEYS); + for key in MEMBER_KEYS { + let text = done + .rewrite + .files + .get(key) + .unwrap_or_else(|| panic!("{key} must be pinned: {:?}", done.rewrite.warnings)); + assert!(text.contains(&format!("tarball: {MEMBER_URL}")), "{text}"); + } + assert!(!done.rewrite.files.contains_key("pnpm-lock.yaml")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.confirmed); + assert!( + warning_codes(&done).contains(&hidden), + "{:?}", + warning_codes(&done) + ); + } + #[tokio::test] async fn member_locks_are_ignored_while_the_root_lock_is_shared() { // The default shared lock: member locks are stale leftovers. diff --git a/crates/socket-patch-core/src/hosted/guidance.rs b/crates/socket-patch-core/src/hosted/guidance.rs index b619cc7b5..d0f4b7f0c 100644 --- a/crates/socket-patch-core/src/hosted/guidance.rs +++ b/crates/socket-patch-core/src/hosted/guidance.rs @@ -372,6 +372,14 @@ pub const TRUST_SCAFFOLD_LINES: [&str; 3] = [ "trustLockfile: true", ]; +/// Whether `text` is, in either line ending, the whole file the trust +/// auto-config creates ([`TRUST_SCAFFOLD_LINES`]). The undo of a hosted pin +/// removes such a file: it cannot tell it from one hosted mode created. +pub fn is_trust_scaffold(text: &str) -> bool { + let created = format!("{}\n", TRUST_SCAFFOLD_LINES.join("\n")); + crate::utils::line_endings::eol_eq(text.as_bytes(), created.as_bytes()) +} + /// Decide how to ensure `trustLockfile: true` in pnpm-workspace.yaml. /// Line splices only (never a YAML library), mirroring the vendor backend's /// workspace surgery: untouched lines stay byte-identical, so a revert can diff --git a/crates/socket-patch-core/src/hosted/memory/select.rs b/crates/socket-patch-core/src/hosted/memory/select.rs index 6e5f01d97..61bfb1738 100644 --- a/crates/socket-patch-core/src/hosted/memory/select.rs +++ b/crates/socket-patch-core/src/hosted/memory/select.rs @@ -3,7 +3,8 @@ //! reads (`REDIRECT_CANDIDATE_FILES`, Python lock / script pairs, Cargo //! member manifests, Rush locks, pnpm workspace members' own locks, the //! install-policy configs, the -//! Plug'n'Play markers and the vendored ledger), plus one +//! Plug'n'Play markers, the `MODULE.bazel` beside a pnpm lock and the +//! vendored ledger), plus one //! presence-only Maven / NuGet marker per ecosystem so a repo holding only //! those still gets its `ecosystem_unsupported_in_memory` warning. @@ -179,6 +180,11 @@ fn classify(rel: &str, root_files: &BTreeSet<&str>, user_patches: bool) -> Optio if user_patches && rel.ends_with(".patch") { return Some(Need::Present); } + // A hub of the Bazel workspace can stand against a pin in the pnpm + // lock beside its `MODULE.bazel` ([`crate::bazel::pnpm`]). + if rel == "MODULE.bazel" && root_files.contains("pnpm-lock.yaml") { + return Some(Need::Text); + } return None; } if let Some(need) = user_patch_need(rel).filter(|_| user_patches) { @@ -596,6 +602,7 @@ pub fn candidate_files() -> Vec { "pylock.toml", "pylock.*.toml", "pnpm-lock.*.yaml (presence only)", + "MODULE.bazel (beside pnpm-lock.yaml)", "**/Cargo.toml (Cargo workspaces)", ] { out.insert(pattern.to_string()); diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs index 057dec3d8..295abe9c3 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/npm.rs @@ -2887,10 +2887,9 @@ pub(crate) async fn cleanup_side_config( const WORKSPACE: &str = "pnpm-workspace.yaml"; if let Ok(Some(ws)) = view.read(WORKSPACE).await { let lines = crate::hosted::guidance::TRUST_SCAFFOLD_LINES; - let created = format!("{}\n", lines.join("\n")); // In either line ending: a `core.autocrlf` checkout of the // created file is still that file. - if crate::utils::line_endings::eol_eq(ws.as_bytes(), created.as_bytes()) { + if crate::hosted::guidance::is_trust_scaffold(&ws) { view.remove(WORKSPACE); } else if let Some(original) = crate::formats::pnpm::workspace::strip_keyless_splice(&ws, &lines) diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 7d38f7654..521324059 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1868,7 +1868,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | Ecosystem, and how Bazel takes its packages | Hosted | Vendored | Agent | VEX | |---|---|---|---|---| -| npm: aspect_rules_js `npm.npm_translate_lock` over a pnpm lock | Supported | Supported | Not supported | Supported | +| npm: aspect_rules_js `npm.npm_translate_lock` over a pnpm lock | Supported with `pnpm-workspace.yaml` in the `data` of a hub that runs pnpm 11 or later | Supported | Not supported | Supported | | PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | | RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call | Not supported | Not supported | Supported | @@ -1917,7 +1917,10 @@ What the table was tested with: on 7.4.0. Every row is a workspace under Bzlmod (`MODULE.bazel`): nothing is tested for dependencies that a `WORKSPACE` file declares. - **npm**: aspect_rules_js 3.6.0, `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` - without `update_pnpm_lock`, and a lock of `lockfileVersion: '9.0'`. + without `update_pnpm_lock`, and a lock of `lockfileVersion: '9.0'`. Hosted mode also with + `update_pnpm_lock = True`, where rules_js runs a pnpm of its own: with the pnpm it picks + itself (10.34.9) and no `data`, and with pnpm 11.28.10 and `pnpm-workspace.yaml` in `data`. + [Bazel workspaces: npm](#bazel-workspaces-npm) says what hosted mode does on such a hub. - **PyPI**: rules_python 2.5.0-rc4, `pip.parse(requirements_lock = "//:requirements.txt")`, and a root `requirements.txt` with hashes. - **Go**: gazelle 0.54.0 with rules_go 0.65.0 (Bazel 9 and 8) and gazelle 0.45.0 with @@ -1954,7 +1957,9 @@ Bazel's own lock: a command or an undo leaves `MODULE.bazel.lock` stale for PyPI and later, for NuGet, and for Cargo under rules_rust 0.75.0. A build that may not update the lock (`--lockfile_mode=error`) fails until one that may, or `bazel mod deps --lockfile_mode=update`, has rewritten it. Commit the rewritten lock with the -patch. +patch. The same holds for the file of hashes that rules_js keeps under `.aspect/` for a hub +with `update_pnpm_lock`: a build that may not update it (`ASPECT_RULES_JS_FROZEN_PNPM_LOCK`) +fails until one that may has rewritten it. Known problems. In each of these a command exits 0 today and the next Bazel build fails: @@ -1993,12 +1998,19 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil the patched gem, which a later `rollback` does not put back. Where the lock has a `CHECKSUMS` section, deleting the entry works too: Bundler then holds the gem to that section. -- **npm on a hub with `update_pnpm_lock = True`.** Hosted mode with a pnpm of 11 or later, - when `pnpm-workspace.yaml` is not in the hub's `data`: the pnpm that Bazel runs rejects the - lock (`ERR_PNPM_TARBALL_URL_MISMATCH`). List `//:package.json` and - `//:pnpm-workspace.yaml` in `data`, as `docs/pnpm.md` of rules_js asks for. Vendored mode on - such a hub fails as well (measured with pnpm 9 and 10): the pnpm that Bazel runs does not - see `.socket/vendor`. Use hosted mode there. +- **Vendored npm on a hub with `update_pnpm_lock = True`** (measured with pnpm 9 and 10): + the pnpm that Bazel runs does not see `.socket/vendor`. Use hosted mode there. +- **Hosted npm on such a hub with a pnpm of 11 or later, when hosted mode is told not to + write `trustLockfile: true`** (`--no-trust-lockfile-config`): the lock is pinned, with the + warning that pnpm 11 rejects it, and the pnpm that Bazel runs does + (`ERR_PNPM_TARBALL_URL_MISMATCH`; measured by hand with the option on Bazel 9.3.2). Run + `socket-patch rollback`, and scan again without the option. A `trustLockfile: false` of + the project's own is not this case: hosted mode pins nothing beside it (see + [Bazel workspaces: npm](#bazel-workspaces-npm)). +- **`rollback` of a hosted npm pin on such a hub that an earlier release wrote, where the + `pnpm-workspace.yaml` the hub lists holds only what hosted mode writes**: the undo removes + the file, and the call then names a missing one. Put the file back with a comment line in + it. Hosted mode pins nothing beside such a file now. - **Vendored Go with gazelle 0.36.0 or older**: `go_deps` rejects the directory `replace` (`local file path not supported in replace directive`). Use hosted mode, or a gazelle of the list above. @@ -2032,6 +2044,107 @@ And three that concern neither: asks the Socket source for every package of the lock, and Bazel prints a warning with that source's URL, the token in it, for each package the source does not hold. +## Bazel workspaces: npm + +aspect_rules_js reads the pnpm lock itself, so a hosted pin in `pnpm-lock.yaml` is what the +build links, and no pnpm runs. One wiring differs. With `update_pnpm_lock = True` on +`npm.npm_translate_lock`, rules_js runs a pnpm of its own during the build whenever the lock +or a `package.json` is not what the hashes it keeps under `.aspect/` say: +`pnpm install --lockfile-only`, in a directory that holds the lock, the `package.json` files +and what the call lists as `data`, and nothing else of the checkout. + +pnpm 11 and later reject a lock that names the patch server unless `pnpm-workspace.yaml` +holds `trustLockfile: true`, which hosted mode writes. A hub that does not list that file +hides the setting from its pnpm, and the build fails (`ERR_PNPM_TARBALL_URL_MISMATCH`). For +such a hub hosted mode therefore writes nothing for the project's root pnpm lock: +`scan --mode hosted` and `get --mode hosted` exit 0, report each npm package of that lock as +skipped (`redirect_unconfirmed`) and warn `redirect_pnpm_bazel_workspace_hidden`. A project +that also has a lock of npm's gets no pin there either: a package that the unpinned pnpm +lock still names is skipped as `redirect_unattributable`. The members' own locks of a +workspace that keeps one lock per member (`sharedWorkspaceLockfile: false`) are pinned as +without Bazel: the hub reads the root lock alone. The build stays the unpatched one that +passes. The warning names the call by its file and line, as the file writes it, and the line +to add to it; for a project below the Bazel root it says that its paths are from that root: + +```starlark +npm.npm_translate_lock( + name = "npm", + data = ["//:pnpm-workspace.yaml"], + pnpm_lock = "//:pnpm-lock.yaml", + update_pnpm_lock = True, +) +``` + +Run the command again after that: it pins the lock, and the next build takes the patched +package. rules_js asks for this `data` itself (`docs/pnpm.md`, "update_pnpm_lock"). + +The file the hub lists has to be one that a pin and its undo leave standing, so hosted mode +also writes nothing for a hub that lists it in two cases, and the warning then names what +the file needs and no label: + +- **The file would hold only what hosted mode writes**: there is none, or it is empty, or + holds only `packages:` and `- '.'`, or is the file an earlier hosted run created. Hosted + mode would create or fill it, but `rollback` removes a file that holds nothing else (it + cannot tell it from one hosted mode created), and the call would then name a file that is + not there, which fails the build. Put a comment line in the file, creating it where there + is none. The same step comes first, before the label, where the hub does not list the + file yet. +- **Hosted mode does not write the setting to the file**: it says `trustLockfile: false` + (or any value but `true`), which hosted mode leaves as it is, or it is YAML that a line + cannot be added to (a flow-style root, several documents). The pnpm of the hub would read + the file and still reject the lock. Set `trustLockfile: true` in it yourself. + +Hosted mode withholds when one call names the project's `pnpm-lock.yaml` in a plain string +and all three hold for it: + +- `update_pnpm_lock` is `True`, or is not written out as `True` or `False`. +- `data` is not a list of strings that holds the label of the `pnpm-workspace.yaml` beside + the lock, or it is and the file is one of the two cases above. +- The pnpm it runs is stated as 11 or later, or in a way that is no version (`latest`, a + constant, a `package.json` that cannot be read). That pnpm is the repository `use_pnpm` + names, `@pnpm` without one, and a `pnpm.pnpm` tag of that `name` states its release: in + `pnpm_version`, or in the `packageManager` of the `package.json` that `pnpm_version_from` + names; of several tags the newest release counts. Where the workspace states none, + rules_js runs one it picks: its newest pnpm 8 through 2.9.3, its newest pnpm 10 from + 3.0.0 through 3.6.0 and at 4.0.0-alpha.0 and 4.0.0-alpha.1 (read in its source). Those + take a pinned lock, so nothing is withheld for a release of aspect_rules_js of 1, 2 or 3 + and for those two: the release the root module asks for with `bazel_dep`, or pins with a + `single_version_override`, and the one `MODULE.bazel.lock` selected, where that file is + there. For any later release, for a version that is not written out and for a ruleset + that an override takes from elsewhere than a registry, the choice is not known and + counts as a pnpm that may be 11 or later; a `pnpm.pnpm` tag that states the release + settles it. + A `use_pnpm` is followed to such a tag only where a `use_repo` takes its repository by + position, under the tag's own name. One that names a repository `use_repo` renames + (`use_repo(pnpm, eleven = "pnpm")`, which runs the pnpm of the tag `pnpm`), or a + repository of another extension or rule, is read as no version. + +What is not written out counts against writing, because a failing build is worse than a +patch that a warning explains. So a hub whose `data` is a constant gets no new hosted pin +until the list is written out in the call, also where the constant lists the file and the +build would take the pin (measured); the warning then says to write `data` out as a list +that holds the label. A hub whose `update_pnpm_lock` is a constant is taken as one that +keeps the lock up to date, whatever the constant holds. A lock that is pinned already stays +pinned. Everything else is as it is without Bazel: a hub without `update_pnpm_lock`, one +that runs pnpm 10, one that lists a file of your own that takes the setting, a project whose +lock no call names, and a project in no Bazel workspace. + +Not read, so that the lock is pinned as it is without Bazel: a `WORKSPACE` file; a hub in a +workspace file that cannot be read; a pnpm release that another Bazel module of the build +asks for; and a repository named `pnpm` that another extension makes and a `use_pnpm` +names. Where the pnpm of such a build is 11 or later and does not read the setting, the +build fails as above. Not read either is a `trustLockfile` that reaches the pnpm of the +build another way (`pnpm_config_trust_lockfile` in Bazel's environment): hosted mode +withholds there as well. Not read either: a hub that names the lock of a workspace member +(`pnpm_lock = "//packages/a:pnpm-lock.yaml"`), which is pinned as without Bazel. The +in-memory engine reads the `MODULE.bazel` beside the lock and gives the answer of a checkout +with the same files; it sees no file that one includes, no Bazel root above the project and +no `MODULE.bazel.lock`, and a `pnpm_version_from` file that is not among the project's own +manifests reads there as a release that is not written out, so a lock that a checkout pins +can be left as it is in memory. Nor does hosted mode look at `--no-trust-lockfile-config` +when it decides this: see the known problems of +[Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported). + ## Bazel workspaces: Maven A rules_jvm_external hub (`maven.install` in `MODULE.bazel`) builds the jars that its own lock, diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 436658668..7f28e3381 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 2665 + "max": 2952 }, "lock-readers": { "paths": [