diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec8e755..de0483a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,10 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - name: Enable Corepack - run: corepack enable + - name: Set up pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + with: + version: 10.34.5 - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 @@ -37,9 +39,6 @@ jobs: node-version: ${{ matrix.node-version }} cache: pnpm - - name: Activate pnpm - run: corepack enable - - name: Install dependencies run: pnpm install --frozen-lockfile diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2f998e7..e5f4527 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -123,4 +123,4 @@ jobs: path: .release - name: Publish the verified prepared tarball - run: npm run release:publish -- -- --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d30d4d6..4e2d743 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,9 +1,13 @@ # Contributing Read [AGENTS.md](AGENTS.md) before changing the package. Pull requests must -pass the complete gate on Node.js 22 and 24: +pass the complete gate on Node.js 22 and 24. Those are the documented local +versions (the same ones CI runs). Node 25 and later do not bundle Corepack, +so install it first if `corepack` is missing: ```sh +npm install -g corepack +corepack enable pnpm install pnpm run format:check pnpm run check diff --git a/docs/RELEASING.md b/docs/RELEASING.md index fc1d011..27cf755 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -47,7 +47,9 @@ move or recreate the tag, unpublish and reuse the version, or claim that The release tool verifies that: - the private root and sole public workspace use one stable version; -- the root pins `pnpm@10.34.5` and `pnpm-lock.yaml` lists both manifests; +- the root pins `pnpm@10.34.5` and `pnpm-lock.yaml` matches each + dependency, including `peerDependencies`, to its own specifier and a + resolved version that satisfies that specifier; - pack and trusted publish still use reviewed `npm@11.18.0`; - `@pegma/sessions` is public MIT-licensed ESM for Node 22 or newer; - runtime dependencies are pinned exactly; @@ -108,9 +110,11 @@ After the first OIDC release succeeds, set npm Publishing access to Prepare every version from `0.1.1` onward through an ordinary pull request that updates the root, workspace, and lockfile versions together and adds reviewed release notes. Run the complete gate and a local release pack on -Node 22 and 24: +Node 22 and 24. Node 25 and later do not bundle Corepack, so install it +first if `corepack` is missing: ```sh +npm install -g corepack corepack enable npm install --global npm@11.18.0 pnpm install diff --git a/packages/sessions/README.md b/packages/sessions/README.md index 2beb4f1..cde8d74 100644 --- a/packages/sessions/README.md +++ b/packages/sessions/README.md @@ -35,10 +35,15 @@ credential re-presentable to another service. ## Development -Node.js 22 or newer is required. The test suite starts a real Azurite Table -service and runs the same behavioral cases over memory and Azure Tables. +Node.js 22 or 24 is required for local development (the same versions CI +runs). The published `engines` field remains `>=22`. Node 25 and later do +not bundle Corepack, so install it first if `corepack` is missing. The test +suite starts a real Azurite Table service and runs the same behavioral cases +over memory and Azure Tables. ```sh +npm install -g corepack +corepack enable pnpm install pnpm run format:check pnpm run check diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 90cae3c..e9e46a4 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -37,6 +37,21 @@ export interface RegistryState { readonly state: "absent" | "exact"; } +export interface LockDependencyEntry { + readonly specifier: string | undefined; + readonly version: string | undefined; +} + +export interface LockImporter { + readonly [section: string]: + Readonly> | undefined; +} + +export interface ParsedPnpmLock { + readonly lockfileVersion: string | undefined; + readonly importers: Readonly>; +} + export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; export function parseArguments( @@ -58,6 +73,19 @@ export function decidePublication( registryIntegrity: string | null, ): "publish" | "skip"; +export function parsePnpmLockImporters(text: string): ParsedPnpmLock; + +export function resolvedVersionSatisfies( + version: string, + specifier: string, +): boolean; + +export function validateLockImporter( + importer: LockImporter | undefined, + manifest: Record, + location: string, +): void; + export function prepareRelease( options?: ReleaseCommandOptions, ): Promise<{ manifestPath: string; manifest: unknown }>; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 7e975e4..245bedf 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -20,6 +20,12 @@ const PACKAGE = { const REPOSITORY_URL = "git+https://github.com/pegma-dev/sessions.git"; const REVIEWED_PNPM_VERSION = "10.34.5"; const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +const DEPENDENCY_SECTIONS = [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", +]; export const RELEASE_PACKAGES = [PACKAGE]; @@ -67,9 +73,173 @@ function runNpm(arguments_, options = {}) { }); } -function pnpmLockfileHasImporter(lockfile, importer) { - const escaped = importer.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`^ {2}${escaped}:$`, "mu").test(lockfile); +function parseYamlScalar(raw) { + if (raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2) { + return raw.slice(1, -1).replaceAll("''", "'"); + } + if (raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) { + return raw.slice(1, -1).replaceAll('\\"', '"'); + } + return raw; +} + +export function parsePnpmLockImporters(text) { + const lockfileVersion = /^lockfileVersion:\s+['"]?([^'"\s]+)['"]?\s*$/mu.exec( + text, + )?.[1]; + const lines = text.split(/\r?\n/u); + const importers = {}; + let index = lines.indexOf("importers:"); + if (index === -1) { + return { lockfileVersion, importers }; + } + index += 1; + let currentImporter = null; + let currentSection = null; + let currentDependency = null; + while (index < lines.length) { + const line = lines[index]; + if (line !== "" && !line.startsWith(" ") && !line.startsWith("\t")) { + break; + } + const importerMatch = /^ (\S[^:]*):\s*(?:\{\})?\s*$/u.exec(line); + if (importerMatch !== null && !line.startsWith(" ")) { + currentImporter = parseYamlScalar(importerMatch[1]); + importers[currentImporter] = {}; + currentSection = null; + currentDependency = null; + index += 1; + continue; + } + const sectionMatch = + /^ (dependencies|devDependencies|optionalDependencies|peerDependencies):\s*$/u.exec( + line, + ); + if (sectionMatch !== null && currentImporter !== null) { + currentSection = sectionMatch[1]; + importers[currentImporter][currentSection] = {}; + currentDependency = null; + index += 1; + continue; + } + const depMatch = /^ (\S[^:]*):\s*$/u.exec(line); + if ( + depMatch !== null && + currentImporter !== null && + currentSection !== null + ) { + currentDependency = parseYamlScalar(depMatch[1]); + importers[currentImporter][currentSection][currentDependency] = { + specifier: undefined, + version: undefined, + }; + index += 1; + continue; + } + const fieldMatch = /^ (specifier|version):\s+(.+?)\s*$/u.exec(line); + if ( + fieldMatch !== null && + currentImporter !== null && + currentSection !== null && + currentDependency !== null + ) { + importers[currentImporter][currentSection][currentDependency][ + fieldMatch[1] + ] = parseYamlScalar(fieldMatch[2]); + } + index += 1; + } + return { lockfileVersion, importers }; +} + +function lockResolvedVersion(version) { + return /^(\S+?)(?:\(|$)/u.exec(version)?.[1]; +} + +function parseSemver(version) { + const match = STABLE_SEMVER.exec(lockResolvedVersion(version) ?? ""); + if (match === null) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + }; +} + +function compareSemver(left, right) { + return ( + left.major - right.major || + left.minor - right.minor || + left.patch - right.patch + ); +} + +function caretUpperBound(base) { + if (base.major > 0) return { major: base.major + 1, minor: 0, patch: 0 }; + if (base.minor > 0) return { major: 0, minor: base.minor + 1, patch: 0 }; + return { major: 0, minor: 0, patch: base.patch + 1 }; +} + +function tildeUpperBound(base) { + return { major: base.major, minor: base.minor + 1, patch: 0 }; +} + +export function resolvedVersionSatisfies(version, specifier) { + const resolved = parseSemver(version); + if (resolved === null || typeof specifier !== "string") return false; + if (specifier === "*" || specifier === "x" || specifier === "X") return true; + if (STABLE_SEMVER.test(specifier)) { + return lockResolvedVersion(version) === specifier; + } + const caret = /^\^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/u.exec( + specifier, + ); + if (caret !== null) { + const base = parseSemver(caret[1]); + return ( + base !== null && + compareSemver(resolved, base) >= 0 && + compareSemver(resolved, caretUpperBound(base)) < 0 + ); + } + const tilde = /^~((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/u.exec( + specifier, + ); + if (tilde !== null) { + const base = parseSemver(tilde[1]); + return ( + base !== null && + compareSemver(resolved, base) >= 0 && + compareSemver(resolved, tildeUpperBound(base)) < 0 + ); + } + return false; +} + +export function validateLockImporter(importer, manifest, location) { + for (const section of DEPENDENCY_SECTIONS) { + const declared = manifest[section] ?? {}; + const locked = importer?.[section] ?? {}; + const names = new Set([...Object.keys(declared), ...Object.keys(locked)]); + for (const name of names) { + const specifier = declared[name]; + const entry = locked[name]; + if (specifier === undefined) { + fail( + `${location} ${section}.${name} is not declared in the package manifest`, + ); + } + if ( + entry?.specifier !== specifier || + typeof entry.version !== "string" || + !resolvedVersionSatisfies(entry.version, specifier) + ) { + fail( + `${location} ${section}.${name} must match its own specifier and resolved version`, + ); + } + } + } } function gitCommand() { @@ -159,19 +329,26 @@ export async function validateRepository(options = {}) { const rootManifest = await readJson(join(root, "package.json")); const packageDirectory = join(root, "packages", PACKAGE.directory); const manifest = await readJson(join(packageDirectory, "package.json")); - const lockfile = await readFile(join(root, "pnpm-lock.yaml"), "utf8"); + const lock = parsePnpmLockImporters( + await readFile(join(root, "pnpm-lock.yaml"), "utf8"), + ); if ( rootManifest.private !== true || rootManifest.packageManager !== `pnpm@${REVIEWED_PNPM_VERSION}` || rootManifest.version !== manifest.version || - !/^lockfileVersion:/mu.test(lockfile) || - !pnpmLockfileHasImporter(lockfile, ".") + lock.lockfileVersion !== "9.0" || + lock.importers["."] === undefined ) { fail( `the private root must share the package version and pin pnpm@${REVIEWED_PNPM_VERSION}`, ); } + validateLockImporter( + lock.importers["."], + rootManifest, + "pnpm-lock.yaml importers[.]", + ); if ( manifest.name !== PACKAGE.name || !STABLE_SEMVER.test(manifest.version) || @@ -216,9 +393,15 @@ export async function validateRepository(options = {}) { } await stat(join(packageDirectory, "README.md")); await stat(join(packageDirectory, "LICENSE")); - if (!pnpmLockfileHasImporter(lockfile, `packages/${PACKAGE.directory}`)) { + const packageImporter = lock.importers[`packages/${PACKAGE.directory}`]; + if (packageImporter === undefined) { fail(`${PACKAGE.name} is not present in pnpm-lock.yaml`); } + validateLockImporter( + packageImporter, + manifest, + `pnpm-lock.yaml importers[packages/${PACKAGE.directory}]`, + ); const publicWorkspaces = []; for (const entry of await readdir(join(root, "packages"), { diff --git a/test/release-packages.test.ts b/test/release-packages.test.ts index 9802265..0e64e25 100644 --- a/test/release-packages.test.ts +++ b/test/release-packages.test.ts @@ -7,6 +7,9 @@ import { RELEASE_PACKAGES, decidePublication, parseArguments, + parsePnpmLockImporters, + resolvedVersionSatisfies, + validateLockImporter, validateReleaseTag, validateRepository, } from "../scripts/release-packages.mjs"; @@ -48,6 +51,198 @@ describe("release package metadata", () => { }); }); + it("never routes pack, view, or publish through npm_execpath", () => { + const source = readFileSync( + join(process.cwd(), "scripts", "release-packages.mjs"), + "utf8", + ); + expect(source).not.toContain("process.env.npm_execpath"); + expect(source).toContain( + 'process.platform === "win32" ? "npm.cmd" : "npm"', + ); + }); + + it("matches each lockfile dependency to its own specifier and resolved version", () => { + const lock = parsePnpmLockImporters( + readFileSync(join(process.cwd(), "pnpm-lock.yaml"), "utf8"), + ); + const rootManifest = JSON.parse( + readFileSync(join(process.cwd(), "package.json"), "utf8"), + ) as { devDependencies: Record }; + const packageManifest = JSON.parse( + readFileSync( + join(process.cwd(), "packages", "sessions", "package.json"), + "utf8", + ), + ) as { dependencies: Record }; + + expect(lock.lockfileVersion).toBe("9.0"); + expect(lock.importers["."]?.devDependencies?.prettier).toEqual({ + specifier: rootManifest.devDependencies.prettier, + version: "3.9.6", + }); + expect( + lock.importers["packages/sessions"]?.dependencies?.["@pegma/spine"], + ).toEqual({ + specifier: packageManifest.dependencies["@pegma/spine"], + version: "0.1.1", + }); + expect( + lock.importers["packages/sessions"]?.dependencies?.[ + "@pegma/storage-core" + ], + ).toEqual({ + specifier: packageManifest.dependencies["@pegma/storage-core"], + version: "0.4.0", + }); + + expect(() => + validateLockImporter(lock.importers["."], rootManifest, "root"), + ).not.toThrow(); + expect(() => + validateLockImporter( + lock.importers["packages/sessions"], + packageManifest, + "package", + ), + ).not.toThrow(); + expect(() => + validateLockImporter( + { + dependencies: { + "@pegma/spine": { specifier: "0.4.0", version: "0.1.1" }, + "@pegma/storage-core": { specifier: "0.1.1", version: "0.4.0" }, + }, + }, + packageManifest, + "swapped", + ), + ).toThrow("must match its own specifier and resolved version"); + }); + + it("unquotes YAML scalars before comparing lockfile specifier and version", () => { + const lock = parsePnpmLockImporters(`lockfileVersion: '9.0' + +importers: + .: + dependencies: + foo: + specifier: '1' + version: '1.0.0' + bar: + specifier: '*' + version: 2.0.0 + baz: + specifier: '1.0.0' + version: '1.0.0' +`); + expect(lock.importers["."]?.dependencies?.foo).toEqual({ + specifier: "1", + version: "1.0.0", + }); + expect(lock.importers["."]?.dependencies?.bar).toEqual({ + specifier: "*", + version: "2.0.0", + }); + expect(lock.importers["."]?.dependencies?.baz).toEqual({ + specifier: "1.0.0", + version: "1.0.0", + }); + expect(() => + validateLockImporter( + { + dependencies: { + bar: { specifier: "*", version: "2.0.0" }, + baz: { specifier: "1.0.0", version: "1.0.0" }, + }, + }, + { dependencies: { bar: "*", baz: "1.0.0" } }, + "quoted", + ), + ).not.toThrow(); + }); + + it("accepts resolved versions that satisfy the declared specifier range", () => { + expect(resolvedVersionSatisfies("1.2.3", "^1.2.0")).toBe(true); + expect( + resolvedVersionSatisfies("1.2.3(@types/node@24.0.0)", "^1.2.0"), + ).toBe(true); + expect(resolvedVersionSatisfies("1.2.9", "~1.2.0")).toBe(true); + expect(resolvedVersionSatisfies("3.9.6", "^3.9.6")).toBe(true); + expect(resolvedVersionSatisfies("1.2.0", "1.2.0")).toBe(true); + expect(resolvedVersionSatisfies("1.2.3", "*")).toBe(true); + expect(resolvedVersionSatisfies("1.2.3", "1.2.0")).toBe(false); + expect(resolvedVersionSatisfies("2.0.0", "^1.2.0")).toBe(false); + expect(resolvedVersionSatisfies("1.3.0", "~1.2.0")).toBe(false); + expect(resolvedVersionSatisfies("1.2.3", ">=1.2.0")).toBe(false); + expect(() => + validateLockImporter( + { + devDependencies: { + prettier: { specifier: "^3.9.6", version: "3.9.6" }, + }, + }, + { devDependencies: { prettier: "^3.9.6" } }, + "range", + ), + ).not.toThrow(); + expect(() => + validateLockImporter( + { + dependencies: { + "@pegma/spine": { specifier: "0.1.1", version: "0.1.2" }, + }, + }, + { dependencies: { "@pegma/spine": "0.1.1" } }, + "exact-mismatch", + ), + ).toThrow("must match its own specifier and resolved version"); + }); + + it("includes peerDependencies in lockfile validation", () => { + expect(() => + validateLockImporter( + { + peerDependencies: { + typescript: { specifier: "^5.0.0", version: "5.9.3" }, + }, + }, + { peerDependencies: { typescript: "^5.0.0" } }, + "peers", + ), + ).not.toThrow(); + expect(() => + validateLockImporter( + {}, + { peerDependencies: { typescript: "^5.0.0" } }, + "missing-peer", + ), + ).toThrow("must match its own specifier and resolved version"); + expect(() => + validateLockImporter( + { + peerDependencies: { + typescript: { specifier: "^4.0.0", version: "4.9.5" }, + }, + }, + { peerDependencies: { typescript: "^5.0.0" } }, + "stale-peer", + ), + ).toThrow("must match its own specifier and resolved version"); + expect(() => + validateLockImporter( + { + peerDependencies: { + a: { specifier: "^2.0.0", version: "2.0.0" }, + b: { specifier: "^1.0.0", version: "1.0.0" }, + }, + }, + { peerDependencies: { a: "^1.0.0", b: "^2.0.0" } }, + "swapped-peer", + ), + ).toThrow("must match its own specifier and resolved version"); + }); + it("requires the release tag to match the package version", async () => { await expect(validateRepository({ releaseTag: "v9.9.9" })).rejects.toThrow( `release tag must be v${packageVersion}`, @@ -163,11 +358,28 @@ describe("release source authentication", () => { expect(publish).not.toContain("npm install"); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("release:pack"); - expect(publish).toContain("npm run release:publish"); + expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("corepack"); + expect(publish).not.toContain("pnpm run"); + expect(prepare).toContain("npm install --global npm@11.18.0"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).not.toContain("NODE_AUTH_TOKEN"); expect(workflow).toContain("retention-days: 30"); }); + + it("installs pnpm before setup-node caches the pnpm store", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "ci.yml"), + "utf8", + ); + const setupPnpm = workflow.indexOf("pnpm/action-setup@"); + const cachePnpm = workflow.indexOf("cache: pnpm"); + expect(setupPnpm).toBeGreaterThanOrEqual(0); + expect(cachePnpm).toBeGreaterThan(setupPnpm); + expect(workflow).toContain( + "pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86", + ); + }); }); describe("retry-safe publication", () => {