import { deepStrictEqual, ok, strictEqual } from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { cpSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, describe, it } from "node:test"; import { fileURLToPath } from "node:url"; import { buildYarnPackagesMap } from "./helpers/buildYarnPackagesMap.ts"; import { fixtureDir } from "./helpers/fixtures.ts"; import { parseYarnLockPackages } from "./helpers/parseYarnLockPackages.ts"; import { createTempProjects } from "./helpers/tempProjects.ts"; import { readAndParseYarnLock } from "./readYarnLock.ts"; // The shipped tool against a real yarn berry: a copy of the `e2e-stale-range` // fixture, a real `yarn install`, then the built `yarn-berry-deduplicate` bin as // a user would run it and the `yarn install` it asks for. Every other test stubs // the resolution step, so this is the only one that can tell whether yarn holds // the merged version — nothing left pinning it, no resolution in the manifest, // only the rewritten lockfile — and yarn is asked for its own account of the // installed tree at the end rather than only our reading of it. // // Run once per `nodeLinker`. The tool never looks at an installed tree — it // reads `yarn.lock` and the workspace manifests, and yarn resolves before it // links, so the lockfile it rewrites is the same file under either linker. What // the pnp run adds is the other half: that yarn accepts the rewritten lockfile // and links a runtime map from it with no `node_modules` to fall back on, which // is the default a berry user is actually standing in. // // Requires network access or a warm yarn cache. The fixture pins // `packageManager`, so corepack answers with berry rather than the yarn 1.x a // bare `yarn` resolves to in a project that pins nothing. // probed inside the fixture, not the repo: corepack answers with whatever the // project pins, and only the fixture pins berry const yarnAvailable = ((): boolean => { const result = spawnSync("yarn", ["--version"], { cwd: fixtureDir("e2e-stale-range"), encoding: "utf8", }); return result.status === 0 && !result.stdout.trim().startsWith("1."); })(); const suite = yarnAvailable ? describe : describe.skip; // the built bin, the one the `bin` field points at: from `src` it is one level // up, and the compiled copy of this file sits beside it const dedupeBin = ((): string => { const built = [ "../dist/bin/yarn-berry-deduplicate.js", "./bin/yarn-berry-deduplicate.js", ] .map((binPath) => fileURLToPath(new URL(binPath, import.meta.url))) .find((binPath) => existsSync(binPath)); if (!built) { throw new Error( "yarn-berry-deduplicate is not built: run `bun run build` first", ); } return built; })(); interface Run { status: number | null; output: string; } const projects = createTempProjects("yarn-berry-deduplicate-e2e-"); afterEach(projects.cleanup); const run = ( cwd: string, command: string, args: string[], env: Record = {}, ): Run => { const result = spawnSync(command, args, { cwd, encoding: "utf8", timeout: 300_000, env: { ...process.env, ...env }, }); if (result.error) throw result.error; return { status: result.status, output: `${result.stdout}\n${result.stderr}`, }; }; // yarn makes installs immutable on CI, so each run says which side it stands on // rather than inheriting the runner's; an `--immutable` argument still wins const install = (cwd: string, ...args: string[]): Run => run(cwd, "yarn", ["install", ...args], { YARN_ENABLE_IMMUTABLE_INSTALLS: "false", }); // the bin refuses to apply where installs are immutable const dedupe = ( cwd: string, args: string[], { immutable = false }: { immutable?: boolean } = {}, ): Run => run(cwd, process.execPath, [dedupeBin, ...args], { YARN_ENABLE_IMMUTABLE_INSTALLS: String(immutable), }); const resolutionsOf = (dir: string, packageName: string): string[] => { const packagesMap = buildYarnPackagesMap( parseYarnLockPackages(readAndParseYarnLock(join(dir, "yarn.lock"))), ); return (packagesMap[packageName] ?? []).map(({ resolution }) => resolution); }; type NodeLinker = "node-modules" | "pnp"; // The fixture pins a linker so its own `yarn install` is reproducible; each run // rewrites just that line, leaving the rest of the file alone. const setNodeLinker = (dir: string, nodeLinker: NodeLinker): void => { const path = join(dir, ".yarnrc.yml"); const yarnrc = readFileSync(path, "utf8"); const updated = yarnrc.replace( /^nodeLinker:.*$/mu, `nodeLinker: ${nodeLinker}`, ); if (updated === yarnrc && !yarnrc.includes(`nodeLinker: ${nodeLinker}`)) { throw new Error(`${path} declares no nodeLinker to override`); } writeFileSync(path, updated); }; /** * The versions the linker left for the runtime to resolve, read off the * artefact it wrote. Neither artefact answers for the other: pnp writes no * `node_modules` at all, and going through `require` instead is refused by * `printable-shell-command`'s own `exports`, which does not expose * `./package.json`. */ const linkedVersions = ( dir: string, packageName: string, nodeLinker: NodeLinker, ): string[] => { if (nodeLinker === "node-modules") { const manifest = JSON.parse( readFileSync( join(dir, "node_modules", packageName, "package.json"), "utf8", ), ) as { version: string }; return [manifest.version]; } // Every copy `.pnp.cjs` can reach is a cache archive, named // `-npm---.zip`. `packageName` is interpolated // raw: the one package this test names carries no regex metacharacter. const pattern = new RegExp( `${packageName}-npm-(?.+?)-[0-9a-f]{10}-`, "gu", ); const versions = [ ...readFileSync(join(dir, ".pnp.cjs"), "utf8").matchAll(pattern), ].map((match) => match.groups!.version!); return [...new Set(versions)].toSorted(); }; suite("yarn-berry-deduplicate end to end", () => { for (const nodeLinker of ["node-modules", "pnp"] as const) { it( `merges the stale range onto the pinned version and leaves yarn installing it (nodeLinker: ${nodeLinker})`, { timeout: 300_000 }, () => { const dir = projects.create(); cpSync(fixtureDir("e2e-stale-range"), dir, { recursive: true }); setNodeLinker(dir, nodeLinker); const manifestsBefore = ["package.json", "packages/a/package.json"].map( (path) => readFileSync(join(dir, path), "utf8"), ); const installed = install(dir); strictEqual(installed.status, 0); // `a` asks for `^5.0.7` and the lockfile still answers 5.0.7, while `b` // pins the 5.3.1 that would satisfy them both deepStrictEqual(resolutionsOf(dir, "printable-shell-command"), [ "printable-shell-command@npm:5.3.1", "printable-shell-command@npm:5.0.7", ]); const check = dedupe(dir, ["--check"]); strictEqual(check.status, 1); // where yarn would not write the lockfile, an apply is a check const lockBefore = readFileSync(join(dir, "yarn.lock"), "utf8"); const gated = dedupe(dir, [], { immutable: true }); strictEqual(gated.status, 1); ok(gated.output.includes("running as --check, nothing is written")); strictEqual(readFileSync(join(dir, "yarn.lock"), "utf8"), lockBefore); const applied = dedupe(dir, []); strictEqual(applied.status, 0); ok(applied.output.includes("yarn.lock updated")); // the rewrite only asks; yarn is what applies it const reinstalled = install(dir); strictEqual(reinstalled.status, 0); deepStrictEqual(resolutionsOf(dir, "printable-shell-command"), [ "printable-shell-command@npm:5.3.1", ]); // the same thing again, read from what yarn actually put on disk deepStrictEqual( linkedVersions(dir, "printable-shell-command", nodeLinker), ["5.3.1"], ); // nothing was pinned into a manifest to hold it there deepStrictEqual( ["package.json", "packages/a/package.json"].map((path) => readFileSync(join(dir, path), "utf8"), ), manifestsBefore, ); // and yarn agrees the lockfile is one CI could install from as it stands strictEqual(install(dir, "--immutable").status, 0); strictEqual(dedupe(dir, ["--check"]).status, 0); }, ); } });