From 5f48868b002922c7be2cd371a5ef9d0dcfc141f0 Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Thu, 17 Sep 2026 15:03:54 -0700 Subject: [PATCH] fix(release): gate npm publishing by released paths --- .github/workflows/release-please.yml | 175 ++++++++-- docs/releasing.md | 43 ++- scripts/npm-publish-workspace-if-needed.mjs | 261 --------------- .../npm-publish-workspace-if-needed.test.mjs | 304 ------------------ tests/workspace-contract.test.mjs | 89 +++-- 5 files changed, 255 insertions(+), 617 deletions(-) delete mode 100755 scripts/npm-publish-workspace-if-needed.mjs delete mode 100644 tests/npm-publish-workspace-if-needed.test.mjs diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index cea2473..cce147b 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -9,18 +9,16 @@ concurrency: group: release-please-${{ github.ref }} cancel-in-progress: false -permissions: - contents: write - pull-requests: write - id-token: write - jobs: - release: - name: Release and publish + release-please: + name: Release Please runs-on: ubuntu-latest - env: - NPM_CONFIG_LEGACY_PEER_DEPS: "true" - + permissions: + contents: write + pull-requests: write + outputs: + releases_created: ${{ steps.release.outputs.releases_created }} + paths_released: ${{ steps.release.outputs.paths_released }} steps: - name: Release Please id: release @@ -29,6 +27,82 @@ jobs: config-file: release-please-config.json manifest-file: .release-please-manifest.json + publish-pi-arc: + needs: release-please + if: ${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/pi-arc') }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NPM_CONFIG_LEGACY_PEER_DEPS: "true" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + cache: npm + cache-dependency-path: package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Run tests + run: npm test --workspace @sentiolabs/pi-arc + + - name: Verify package contents + run: npm run pack:dry-run --workspace @sentiolabs/pi-arc + + - name: Publish to npm + run: npm publish --workspace @sentiolabs/pi-arc --access public --provenance + + publish-pi-code-quality: + needs: release-please + if: ${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/pi-code-quality') }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NPM_CONFIG_LEGACY_PEER_DEPS: "true" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + cache: npm + cache-dependency-path: package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Run tests + run: npm test --workspace @sentiolabs/pi-code-quality + + - name: Verify package contents + run: npm run pack:dry-run --workspace @sentiolabs/pi-code-quality + + - name: Publish to npm + run: npm publish --workspace @sentiolabs/pi-code-quality --access public --provenance + + publish-pi-git-spice: + needs: release-please + if: ${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/pi-git-spice') }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NPM_CONFIG_LEGACY_PEER_DEPS: "true" + steps: - name: Checkout uses: actions/checkout@v4 @@ -38,21 +112,82 @@ jobs: node-version: 24 registry-url: https://registry.npmjs.org cache: npm + cache-dependency-path: package-lock.json - name: Install dependencies run: npm ci - - name: Publish pi-arc to npm - run: node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-arc + - name: Run tests + run: npm test --workspace @sentiolabs/pi-git-spice + + - name: Verify package contents + run: npm run pack:dry-run --workspace @sentiolabs/pi-git-spice + + - name: Publish to npm + run: npm publish --workspace @sentiolabs/pi-git-spice --access public --provenance + + publish-pi-frontend-design: + needs: release-please + if: ${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/pi-frontend-design') }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NPM_CONFIG_LEGACY_PEER_DEPS: "true" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + cache: npm + cache-dependency-path: package-lock.json - - name: Publish pi-code-quality to npm - run: node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-code-quality + - name: Install dependencies + run: npm ci + + - name: Run tests + run: npm test --workspace @sentiolabs/pi-frontend-design + + - name: Verify package contents + run: npm run pack:dry-run --workspace @sentiolabs/pi-frontend-design + + - name: Publish to npm + run: npm publish --workspace @sentiolabs/pi-frontend-design --access public --provenance + + publish-pi-scriptable-statusline: + needs: release-please + if: ${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/pi-scriptable-statusline') }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NPM_CONFIG_LEGACY_PEER_DEPS: "true" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + cache: npm + cache-dependency-path: package-lock.json + + - name: Install dependencies + run: npm ci - - name: Publish pi-git-spice to npm - run: node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-git-spice + - name: Run tests + run: npm test --workspace @sentiolabs/pi-scriptable-statusline - - name: Publish pi-frontend-design to npm - run: node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-frontend-design + - name: Verify package contents + run: npm run pack:dry-run --workspace @sentiolabs/pi-scriptable-statusline - - name: Publish pi-scriptable-statusline to npm - run: node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-scriptable-statusline + - name: Publish to npm + run: npm publish --workspace @sentiolabs/pi-scriptable-statusline --access public --provenance diff --git a/docs/releasing.md b/docs/releasing.md index c7bb336..c00bfdf 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -10,7 +10,7 @@ Each package under `packages/*` has its own Release Please entry. Packages in th ### Imported package baselines -When a package is imported from a standalone repository, keep the workspace package version and `.release-please-manifest.json` entry aligned to the latest already-published npm version before making new changes in this monorepo. For `@sentiolabs/pi-arc`, the imported baseline is `0.10.0`; the existing publish helper skips that already-published version and future Release Please releases publish the next semver version from `pi-nexus`. +When a package is imported from a standalone repository, keep the workspace package version and `.release-please-manifest.json` entry aligned to the latest already-published npm version before making new changes in this monorepo. For `@sentiolabs/pi-arc`, the imported baseline is `0.10.0`; future Release Please releases publish the next semver version from `pi-nexus` only when that package path is newly released. Current package entries include: @@ -87,29 +87,48 @@ Current package entries include: } ``` -## npm provenance +## Package-specific publishing + +The `.github/workflows/release-please.yml` workflow serializes `main` runs using a ref-scoped concurrency group without cancelling in-progress publishing. Its `release-please` job maintains the aggregate release PR and exposes `releases_created` and `paths_released`. After a release PR merge, only paths in `paths_released` receive publisher jobs, and only when `releases_created` is `true`. An ordinary `main` push does not scan or republish workspace versions. -Publishing uses GitHub Actions and npm provenance through `scripts/npm-publish-workspace-if-needed.mjs`. The release workflow serializes `main` runs using a ref-scoped concurrency group without cancelling in-progress publishing. It runs the helper for every workspace package on every `main` push, not only packages reported by Release Please as newly released. The helper checks whether the exact workspace package version already exists on npm and skips duplicate publishes. This all-package scan is a recovery mechanism when a GitHub release succeeds but npm publication fails. +| Publisher job | Released path | Workspace package | +|---|---|---| +| `publish-pi-arc` | `packages/pi-arc` | `@sentiolabs/pi-arc` | +| `publish-pi-code-quality` | `packages/pi-code-quality` | `@sentiolabs/pi-code-quality` | +| `publish-pi-git-spice` | `packages/pi-git-spice` | `@sentiolabs/pi-git-spice` | +| `publish-pi-frontend-design` | `packages/pi-frontend-design` | `@sentiolabs/pi-frontend-design` | +| `publish-pi-scriptable-statusline` | `packages/pi-scriptable-statusline` | `@sentiolabs/pi-scriptable-statusline` | -After a successful real publish, the helper waits for exact-version registry visibility by polling `npm view @ version --json`. It defaults to 24 attempts with a 5000 ms delay between not-found responses. `NPM_PUBLISH_VERIFY_ATTEMPTS` and `NPM_PUBLISH_VERIFY_DELAY_MS` override those defaults; each must be a positive base-10 integer within JavaScript's safe integer range, or the helper fails before publishing. Exhausted attempts fail with the package version and attempt count, while non-not-found errors fail immediately and forward npm's output. Publishes using `--dry-run` skip post-publish visibility checks because they create no registry version. +Each package job independently checks out the repository, sets up Node 24 with npm caching, installs dependencies, tests its workspace, dry-runs its package contents, and publishes. For example, the Git Spice job runs these commands in order: ```bash -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-arc -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-code-quality -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-frontend-design -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-git-spice -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-scriptable-statusline +npm ci +npm test --workspace @sentiolabs/pi-git-spice +npm run pack:dry-run --workspace @sentiolabs/pi-git-spice +npm publish --workspace @sentiolabs/pi-git-spice --access public --provenance ``` +`npm publish` acceptance (exit status zero) is the completion boundary. The workflow does not poll registry visibility or retry publication. A nonzero exit status fails that package job. + +Publisher jobs depend only on `release-please`, never on each other, so a failed package does not block unrelated publisher jobs. Rerun only the failed package job (or use **Re-run failed jobs**), not **Re-run all jobs**, to avoid republishing unrelated packages. Direct publication does not skip existing versions: if npm already accepted a version, investigate before rerunning that package's publish step. + +### Merge ordering + +Merge the workflow-alignment changes before aggregate release PR #20 so its newly released paths use the independent publisher jobs. Do not merge the release PR first and rely on a later ordinary `main` push to recover publication. + +## npm provenance + +Publishing uses GitHub Actions and npm provenance. Only publisher jobs receive `contents: read` and `id-token: write`; the Release Please job receives `contents: write` and `pull-requests: write`. All jobs stay in `.github/workflows/release-please.yml`, preserving the workflow filename used by npm Trusted Publisher settings. + npm provenance requires the package `repository.url` to match the GitHub repository URL and case exactly. Before enabling a real publish, verify: ```bash git remote get-url origin node --test tests/workspace-contract.test.mjs -node scripts/npm-publish-workspace-if-needed.mjs @sentiolabs/pi-arc --dry-run +npm run pack:dry-run --workspace @sentiolabs/pi-arc ``` -If the GitHub organization or repository casing changes, update `packages/pi-arc/package.json` before publishing. +If the GitHub organization or repository casing changes, update the affected workspace package manifests before publishing. ## Adding another package @@ -120,4 +139,4 @@ To add another independently released package: 3. Add a manifest entry in `.release-please-manifest.json`. 4. Add package docs and root README table entry. 5. Add the package-lock workspace version path to the package's Release Please `extra-files` entry. -6. Extend the release workflow with `node scripts/npm-publish-workspace-if-needed.mjs ` for the new package. +6. Add an independent publisher job to `.github/workflows/release-please.yml`, gated by `releases_created` and the exact `packages/` path in `paths_released`. Include workspace tests, a package dry-run, and `npm publish --workspace --access public --provenance`. Extend the workspace contract tests for the new job. diff --git a/scripts/npm-publish-workspace-if-needed.mjs b/scripts/npm-publish-workspace-if-needed.mjs deleted file mode 100755 index 40dce33..0000000 --- a/scripts/npm-publish-workspace-if-needed.mjs +++ /dev/null @@ -1,261 +0,0 @@ -#!/usr/bin/env node -import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; -import { join } from "node:path"; -import { spawnSync } from "node:child_process"; - -const [, , packageName, ...publishExtraArgs] = process.argv; - -if (!packageName) { - console.error("Usage: npm-publish-workspace-if-needed.mjs [npm-publish-extra-args...]"); - process.exit(2); -} - -const rootDir = process.cwd(); -const npmCommand = process.env.NPM_PUBLISH_IF_NEEDED_NPM ?? "npm"; -const verifyAttempts = positiveIntegerEnv("NPM_PUBLISH_VERIFY_ATTEMPTS", 24); -const verifyDelayMs = positiveIntegerEnv("NPM_PUBLISH_VERIFY_DELAY_MS", 5000); - -function positiveIntegerEnv(name, defaultValue) { - const raw = process.env[name]; - if (raw === undefined) return defaultValue; - - const value = Number(raw); - if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value <= 0) { - console.error(`${name} must be a positive base-10 integer within the safe integer range.`); - process.exit(1); - } - return value; -} - -async function sleep(delayMs) { - // Node clamps oversized timers to 1 ms; split long configured delays instead. - for (let remaining = delayMs; remaining > 0;) { - const interval = Math.min(remaining, 2_147_483_647); - await new Promise((resolve) => setTimeout(resolve, interval)); - remaining -= interval; - } -} - -function readJson(path) { - return JSON.parse(readFileSync(path, "utf8")); -} - -function parseNpmJsonValue(stdout) { - const value = stdout.trim(); - if (!value) return ""; - - try { - return JSON.parse(value); - } catch { - return value.replace(/^"|"$/g, ""); - } -} - -function parseSemver(version) { - const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version); - if (!match) { - throw new Error(`Unsupported semver version: ${version}`); - } - - return { - major: Number(match[1]), - minor: Number(match[2]), - patch: Number(match[3]), - prerelease: match[4]?.split(".") ?? [], - }; -} - -function compareIdentifiers(left, right) { - const leftIsNumeric = /^\d+$/.test(left); - const rightIsNumeric = /^\d+$/.test(right); - - if (leftIsNumeric && rightIsNumeric) { - return Number(left) - Number(right); - } - - if (leftIsNumeric) return -1; - if (rightIsNumeric) return 1; - if (left === right) return 0; - return left < right ? -1 : 1; -} - -function comparePrerelease(left, right) { - if (left.length === 0 && right.length === 0) return 0; - if (left.length === 0) return 1; - if (right.length === 0) return -1; - - const maxLength = Math.max(left.length, right.length); - for (let index = 0; index < maxLength; index += 1) { - const leftIdentifier = left[index]; - const rightIdentifier = right[index]; - - if (leftIdentifier === undefined) return -1; - if (rightIdentifier === undefined) return 1; - - const comparison = compareIdentifiers(leftIdentifier, rightIdentifier); - if (comparison !== 0) return comparison; - } - - return 0; -} - -function compareSemver(left, right) { - const leftVersion = parseSemver(left); - const rightVersion = parseSemver(right); - - for (const key of ["major", "minor", "patch"]) { - if (leftVersion[key] !== rightVersion[key]) { - return leftVersion[key] - rightVersion[key]; - } - } - - return comparePrerelease(leftVersion.prerelease, rightVersion.prerelease); -} - -function isPrerelease(version) { - return parseSemver(version).prerelease.length > 0; -} - -function publishDistTag(args) { - let tag = "latest"; - for (let index = 0; index < args.length; index += 1) { - const arg = args[index]; - if (arg === "--tag" && args[index + 1]) { - tag = args[index + 1]; - index += 1; - } else if (arg.startsWith("--tag=")) { - tag = arg.slice("--tag=".length); - } - } - return tag; -} - -function expandWorkspacePattern(pattern) { - if (!pattern.endsWith("/*")) { - return [pattern]; - } - - const parent = pattern.slice(0, -2); - const parentPath = join(rootDir, parent); - if (!existsSync(parentPath)) { - return []; - } - - return readdirSync(parentPath) - .map((entry) => join(parent, entry)) - .filter((workspacePath) => { - const absolutePath = join(rootDir, workspacePath); - return statSync(absolutePath).isDirectory() && existsSync(join(absolutePath, "package.json")); - }); -} - -function findWorkspacePackage(name) { - const rootPackage = readJson(join(rootDir, "package.json")); - const workspaces = Array.isArray(rootPackage.workspaces) - ? rootPackage.workspaces - : rootPackage.workspaces?.packages; - - if (!Array.isArray(workspaces)) { - throw new Error("Root package.json does not declare npm workspaces"); - } - - for (const workspacePattern of workspaces) { - for (const workspacePath of expandWorkspacePattern(workspacePattern)) { - const packagePath = join(rootDir, workspacePath, "package.json"); - const pkg = readJson(packagePath); - if (pkg.name === name) { - return { packagePath, workspacePath, pkg }; - } - } - } - - throw new Error(`Workspace package not found: ${name}`); -} - -function runNpm(args) { - return spawnSync(npmCommand, args, { - cwd: rootDir, - encoding: "utf8", - }); -} - -function isNpmNotFound(result) { - const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`; - return /\bE404\b|404 Not Found|No match found for version/i.test(output); -} - -const { workspacePath, pkg } = findWorkspacePackage(packageName); -const versionSpecifier = `${pkg.name}@${pkg.version}`; -const distTag = publishDistTag(publishExtraArgs); - -console.log(`Checking npm for ${versionSpecifier} from ${workspacePath}`); -const exactVersionResult = runNpm(["view", versionSpecifier, "version", "--json"]); - -if (exactVersionResult.status === 0) { - const publishedVersion = parseNpmJsonValue(exactVersionResult.stdout); - console.log(`${versionSpecifier} is already published${publishedVersion ? ` as ${publishedVersion}` : ""}; skipping npm publish.`); - process.exit(0); -} - -if (!isNpmNotFound(exactVersionResult)) { - process.stdout.write(exactVersionResult.stdout ?? ""); - process.stderr.write(exactVersionResult.stderr ?? ""); - process.exit(exactVersionResult.status ?? 1); -} - -if (distTag === "latest" && isPrerelease(pkg.version)) { - console.error(`${versionSpecifier} is a prerelease; refusing to publish it with the default latest dist-tag. Pass --tag for intentional prerelease publishing.`); - process.exit(1); -} - -if (distTag === "latest") { - const latestVersionResult = runNpm(["view", pkg.name, "version", "--json"]); - if (latestVersionResult.status === 0) { - const latestVersion = parseNpmJsonValue(latestVersionResult.stdout); - if (latestVersion && compareSemver(latestVersion, pkg.version) > 0) { - console.error( - `${versionSpecifier} is older than the npm latest ${pkg.name}@${latestVersion}; refusing to publish because npm would move the latest dist-tag backwards.`, - ); - process.exit(1); - } - } else if (!isNpmNotFound(latestVersionResult)) { - process.stdout.write(latestVersionResult.stdout ?? ""); - process.stderr.write(latestVersionResult.stderr ?? ""); - process.exit(latestVersionResult.status ?? 1); - } -} - -console.log(`${versionSpecifier} is not published yet; running npm publish.`); -const publishResult = spawnSync( - npmCommand, - ["publish", "--workspace", pkg.name, "--access", "public", "--provenance", ...publishExtraArgs], - { - cwd: rootDir, - stdio: "inherit", - }, -); - -if (publishResult.status !== 0 || publishExtraArgs.includes("--dry-run")) { - process.exit(publishResult.status ?? 1); -} - -for (let attempt = 1; attempt <= verifyAttempts; attempt += 1) { - const visibilityResult = runNpm(["view", versionSpecifier, "version", "--json"]); - if (visibilityResult.status === 0) { - console.log(`${versionSpecifier} is visible on npm (attempt ${attempt}/${verifyAttempts}).`); - process.exit(0); - } - - if (!isNpmNotFound(visibilityResult)) { - process.stdout.write(visibilityResult.stdout ?? ""); - process.stderr.write(visibilityResult.stderr ?? ""); - process.exit(visibilityResult.status ?? 1); - } - - if (attempt === verifyAttempts) { - console.error(`${versionSpecifier} is still not visible on npm after ${verifyAttempts} attempts; registry visibility verification timed out.`); - process.exit(1); - } - - await sleep(verifyDelayMs); -} diff --git a/tests/npm-publish-workspace-if-needed.test.mjs b/tests/npm-publish-workspace-if-needed.test.mjs deleted file mode 100644 index a06f5be..0000000 --- a/tests/npm-publish-workspace-if-needed.test.mjs +++ /dev/null @@ -1,304 +0,0 @@ -import assert from "node:assert/strict"; -import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { spawnSync } from "node:child_process"; -import test, { after } from "node:test"; - -const scriptPath = new URL("../scripts/npm-publish-workspace-if-needed.mjs", import.meta.url).pathname; -const packageName = "@sentiolabs/example"; - -function setupWorkspace(version = "1.2.3") { - const dir = mkdtempSync(join(tmpdir(), "pi-nexus-publish-test-")); - after(() => rmSync(dir, { recursive: true, force: true })); - mkdirSync(join(dir, "packages", "example"), { recursive: true }); - writeFileSync( - join(dir, "package.json"), - JSON.stringify({ private: true, workspaces: ["packages/*"] }, null, 2), - ); - writeFileSync( - join(dir, "packages", "example", "package.json"), - JSON.stringify({ name: packageName, version }, null, 2), - ); - - const callsPath = join(dir, "npm-calls.jsonl"); - const fakeNpmPath = join(dir, "fake-npm.mjs"); - writeFileSync( - fakeNpmPath, - `#!/usr/bin/env node -import { appendFileSync, existsSync, readFileSync } from 'node:fs'; -const callsPath = process.env.FAKE_NPM_CALLS; -const packageName = process.env.FAKE_NPM_PACKAGE_NAME; -const packageVersion = process.env.FAKE_NPM_PACKAGE_VERSION; -const args = process.argv.slice(2); -const calls = existsSync(callsPath) - ? readFileSync(callsPath, 'utf8').trim().split('\\n').filter(Boolean).map((line) => JSON.parse(line)) - : []; -appendFileSync(callsPath, JSON.stringify(args) + '\\n'); -if (args[0] === 'view' && args[1] === packageName + '@' + packageVersion) { - const publishIndex = calls.findLastIndex((call) => call[0] === 'publish'); - if (publishIndex !== -1) { - if (process.env.FAKE_NPM_VISIBILITY_ERROR) { - console.log('visibility error stdout'); - console.error('npm error code ' + process.env.FAKE_NPM_VISIBILITY_ERROR); - process.exit(7); - } - const previousChecks = calls.slice(publishIndex + 1).filter((call) => call[0] === 'view').length; - if (previousChecks >= Number(process.env.FAKE_NPM_VISIBILITY_MISSES)) { - console.log(JSON.stringify(packageVersion)); - process.exit(0); - } - console.error(process.env.FAKE_NPM_VISIBILITY_NOT_FOUND); - process.exit(1); - } - if (process.env.FAKE_NPM_EXACT_EXISTS === '1') { - console.log(JSON.stringify(packageVersion)); - process.exit(0); - } - console.error('npm error code E404'); - console.error('npm error 404 No match found for version ' + packageVersion); - process.exit(1); -} -if (args[0] === 'view' && args[1] === packageName) { - const latest = process.env.FAKE_NPM_LATEST_VERSION; - if (latest) { - console.log(JSON.stringify(latest)); - process.exit(0); - } - console.error('npm error code E404'); - console.error('npm error 404 package not found'); - process.exit(1); -} -if (args[0] === 'publish') { - process.exit(Number(process.env.FAKE_NPM_PUBLISH_EXIT)); -} -process.exit(99); -`, - ); - chmodSync(fakeNpmPath, 0o755); - - return { dir, callsPath, fakeNpmPath, version }; -} - -function runScript({ dir, callsPath, fakeNpmPath, version }, options = {}) { - return spawnSync(process.execPath, [scriptPath, packageName, ...(options.extraArgs ?? [])], { - cwd: dir, - encoding: "utf8", - timeout: options.timeout ?? 10_000, - env: { - ...process.env, - FAKE_NPM_CALLS: callsPath, - FAKE_NPM_EXACT_EXISTS: options.exactExists ? "1" : "0", - FAKE_NPM_LATEST_VERSION: options.latestVersion ?? "", - FAKE_NPM_PACKAGE_NAME: packageName, - FAKE_NPM_PACKAGE_VERSION: version, - FAKE_NPM_VISIBILITY_MISSES: String(options.visibilityMisses ?? 0), - FAKE_NPM_VISIBILITY_ERROR: options.visibilityError ?? "", - FAKE_NPM_VISIBILITY_NOT_FOUND: options.visibilityNotFound ?? "npm error code E404", - FAKE_NPM_PUBLISH_EXIT: String(options.publishExit ?? 0), - NPM_PUBLISH_VERIFY_ATTEMPTS: "3", - NPM_PUBLISH_VERIFY_DELAY_MS: "1", - ...options.verifyEnv, - NPM_PUBLISH_IF_NEEDED_NPM: fakeNpmPath, - }, - }); -} - -function readCalls(callsPath) { - if (!existsSync(callsPath)) return []; - return readFileSync(callsPath, "utf8") - .trim() - .split("\n") - .filter(Boolean) - .map((line) => JSON.parse(line)); -} - -test("publish helper skips workspace package versions already on npm", () => { - const workspace = setupWorkspace(); - - const result = runScript(workspace, { exactExists: true }); - - assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /already published/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ["view", "@sentiolabs/example@1.2.3", "version", "--json"], - ]); -}); - -test("publish helper dry-run skips post-publish visibility checks", () => { - const workspace = setupWorkspace(); - - const result = runScript(workspace, { latestVersion: "1.2.2", extraArgs: ["--dry-run"] }); - - assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /not published yet/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ["view", "@sentiolabs/example@1.2.3", "version", "--json"], - ["view", "@sentiolabs/example", "version", "--json"], - ["publish", "--workspace", "@sentiolabs/example", "--access", "public", "--provenance", "--dry-run"], - ]); -}); - -test("publish helper refuses to move npm latest backwards", () => { - const workspace = setupWorkspace(); - - const result = runScript(workspace, { latestVersion: "1.3.0", extraArgs: ["--dry-run"] }); - - assert.equal(result.status, 1); - assert.match(result.stderr, /refusing to publish/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ["view", "@sentiolabs/example@1.2.3", "version", "--json"], - ["view", "@sentiolabs/example", "version", "--json"], - ]); -}); - -test("publish helper treats stable same-core versions as newer than prereleases", () => { - const workspace = setupWorkspace("1.2.3-beta.1"); - - const result = runScript(workspace, { latestVersion: "1.2.3", extraArgs: ["--dry-run"] }); - - assert.equal(result.status, 1); - assert.match(result.stderr, /prerelease/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ["view", "@sentiolabs/example@1.2.3-beta.1", "version", "--json"], - ]); -}); - -test("publish helper allows prereleases with an explicit non-latest dist-tag", () => { - const workspace = setupWorkspace("1.2.3-beta.1"); - - const result = runScript(workspace, { latestVersion: "1.2.3", extraArgs: ["--tag", "next", "--dry-run"] }); - - assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /not published yet/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ["view", "@sentiolabs/example@1.2.3-beta.1", "version", "--json"], - ["publish", "--workspace", "@sentiolabs/example", "--access", "public", "--provenance", "--tag", "next", "--dry-run"], - ]); -}); - -function expectedPublishCalls(version = "1.2.3", extraArgs = []) { - return [ - ["view", `${packageName}@${version}`, "version", "--json"], - ["view", packageName, "version", "--json"], - ["publish", "--workspace", packageName, "--access", "public", "--provenance", ...extraArgs], - ]; -} - -for (const visibilityMisses of [0, 1, 2]) { - test(`publish helper confirms visibility after ${visibilityMisses} exact-version misses`, () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { latestVersion: "1.2.2", visibilityMisses }); - - assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /@sentiolabs\/example@1\.2\.3.*visible/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ...Array.from({ length: visibilityMisses + 1 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]), - ]); - }); -} - -for (const visibilityNotFound of ["npm error code E404", "404 Not Found", "No match found for version 1.2.3"]) { - test(`publish helper fails after the final visibility attempt for ${visibilityNotFound}`, () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { visibilityMisses: 3, visibilityNotFound }); - - assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, /@sentiolabs\/example@1\.2\.3.*not visible.*3 attempts/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ...Array.from({ length: 3 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]), - ]); - }); -} - -test("publish helper forwards non-404 visibility errors and fails without retrying", () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { visibilityError: "E401" }); - - assert.equal(result.status, 7, result.stderr); - assert.match(result.stdout, /visibility error stdout/); - assert.match(result.stderr, /npm error code E401/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ["view", `${packageName}@1.2.3`, "version", "--json"], - ]); -}); - -test("publish helper does not check visibility after a failed publish", () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { publishExit: 9 }); - - assert.equal(result.status, 9, result.stderr); - assert.deepEqual(readCalls(workspace.callsPath), expectedPublishCalls()); -}); - -test("publish helper preserves a failed dry-run exit status without checking visibility", () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { publishExit: 9, extraArgs: ["--dry-run"] }); - - assert.equal(result.status, 9, result.stderr); - assert.deepEqual(readCalls(workspace.callsPath), expectedPublishCalls("1.2.3", ["--dry-run"])); -}); - -for (const name of ["NPM_PUBLISH_VERIFY_ATTEMPTS", "NPM_PUBLISH_VERIFY_DELAY_MS"]) { - for (const value of ["", "0", "-1", "1.5", "nope", "2ms", "1e2", "0x10", " 2", "2 ", "2\n", "Infinity", "9007199254740992"]) { - test(`publish helper rejects ${name}=${JSON.stringify(value)} before publishing`, () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { verifyEnv: { [name]: value } }); - - assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, new RegExp(`${name}.*positive base-10 integer`)); - assert.equal(readCalls(workspace.callsPath).some((call) => call[0] === "publish"), false); - }); - } -} - -test("publish helper accepts positive base-10 verification overrides", () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { - visibilityMisses: 3, - verifyEnv: { NPM_PUBLISH_VERIFY_ATTEMPTS: "04", NPM_PUBLISH_VERIFY_DELAY_MS: "01" }, - }); - - assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /@sentiolabs\/example@1\.2\.3.*visible/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ...Array.from({ length: 4 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]), - ]); -}); - -for (const delayMs of [undefined, "2000", "2147483648"]) { - test(`publish helper waits between visibility attempts with delay ${delayMs ?? "default"} without timer overflow`, () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { - visibilityMisses: 1, - timeout: 1000, - verifyEnv: { NPM_PUBLISH_VERIFY_DELAY_MS: delayMs }, - }); - - assert.equal(result.error?.code, "ETIMEDOUT", result.stderr); - assert.doesNotMatch(result.stderr, /TimeoutOverflowWarning/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ["view", `${packageName}@1.2.3`, "version", "--json"], - ]); - }); -} - -test("publish helper defaults to 24 bounded visibility attempts", () => { - const workspace = setupWorkspace(); - const result = runScript(workspace, { - visibilityMisses: 24, - verifyEnv: { NPM_PUBLISH_VERIFY_ATTEMPTS: undefined }, - }); - - assert.equal(result.status, 1, result.stderr); - assert.match(result.stderr, /@sentiolabs\/example@1\.2\.3.*not visible.*24 attempts/); - assert.deepEqual(readCalls(workspace.callsPath), [ - ...expectedPublishCalls(), - ...Array.from({ length: 24 }, () => ["view", `${packageName}@1.2.3`, "version", "--json"]), - ]); -}); diff --git a/tests/workspace-contract.test.mjs b/tests/workspace-contract.test.mjs index 77d2f1a..4fccc00 100644 --- a/tests/workspace-contract.test.mjs +++ b/tests/workspace-contract.test.mjs @@ -38,7 +38,7 @@ test("release-please aggregates independent package releases into one PR", () => test("release workflow serializes runs without cancelling in-progress publishing", () => { const workflow = readText(".github/workflows/release-please.yml"); - assert.match(workflow, /^concurrency:\n group: release-please-\$\{\{ github\.ref \}\}\n cancel-in-progress: false\n\npermissions:/m); + assert.match(workflow, /^concurrency:\n group: release-please-\$\{\{ github\.ref \}\}\n cancel-in-progress: false\n\njobs:/m); assert.ok(workflow.indexOf("\non:") < workflow.indexOf("\nconcurrency:")); }); @@ -169,7 +169,7 @@ test("root documentation integrates pi-git-spice", () => { ] }`), ); - assert.match(releasing, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-git-spice/); + assert.match(releasing, /npm publish --workspace @sentiolabs\/pi-git-spice --access public --provenance/); assert.match(packageDocs, /^# `@sentiolabs\/pi-git-spice`$/m); for (const heading of ["Included resources", "Prerequisites", "Non-interactive safety", "Local development"]) { @@ -243,27 +243,76 @@ test("release-please tracks pi-scriptable-statusline as an independent package", assertReleaseManifestTracksPackage("packages/pi-scriptable-statusline"); }); -test("release workflow uses idempotent npm publishing helper", () => { +const releasePackages = [ + "pi-arc", + "pi-code-quality", + "pi-git-spice", + "pi-frontend-design", + "pi-scriptable-statusline", +]; + +function releaseWorkflowJobs(workflow) { + const jobsStart = workflow.indexOf("\njobs:\n"); + assert.notEqual(jobsStart, -1, "workflow must declare jobs"); + return [...workflow.slice(jobsStart).matchAll(/^ ([\w-]+):\n([\s\S]*?)(?=^ [\w-]+:\n|(?![\s\S]))/gm)] + .map(([, id, body]) => [id, body]); +} + +test("release workflow exposes released paths with job-scoped permissions", () => { const workflow = readText(".github/workflows/release-please.yml"); + const jobs = releaseWorkflowJobs(workflow); - assert.match(workflow, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-arc/); - assert.match(workflow, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-frontend-design/); - assert.match(workflow, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-git-spice/); - assert.match(workflow, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-scriptable-statusline/); - assert.match(workflow, /node scripts\/npm-publish-workspace-if-needed\.mjs @sentiolabs\/pi-code-quality/); - - const publishPackages = [...workflow.matchAll(/run: node scripts\/npm-publish-workspace-if-needed\.mjs (@sentiolabs\/[\w-]+)/g)] - .map((match) => match[1]); - assert.deepEqual(publishPackages, [ - "@sentiolabs/pi-arc", - "@sentiolabs/pi-code-quality", - "@sentiolabs/pi-git-spice", - "@sentiolabs/pi-frontend-design", - "@sentiolabs/pi-scriptable-statusline", - ]); + assert.deepEqual(jobs.map(([id]) => id), ["release-please", ...releasePackages.map((name) => `publish-${name}`)]); + assert.doesNotMatch(workflow.split(/^jobs:\n/m)[0], /^permissions:/m); + + const release = new Map(jobs).get("release-please"); + assert.match(release, /^ outputs:\n releases_created: \$\{\{ steps\.release\.outputs\.releases_created \}\}\n paths_released: \$\{\{ steps\.release\.outputs\.paths_released \}\}\n/m); + assert.match(release, /^ permissions:\n contents: write\n pull-requests: write\n/m); + assert.match(release, /^ - name: Release Please\n id: release\n uses: googleapis\/release-please-action@v4\n with:\n config-file: release-please-config\.json\n manifest-file: \.release-please-manifest\.json\n/m); + assert.doesNotMatch(release, /id-token:|npm publish/); +}); + +for (const name of releasePackages) { + test(`release workflow independently gates and publishes ${name}`, () => { + const workflow = readText(".github/workflows/release-please.yml"); + const job = new Map(releaseWorkflowJobs(workflow)).get(`publish-${name}`); + const workspace = `@sentiolabs/${name}`; + assert.ok(job, `missing publish-${name} job`); + + assert.deepEqual([...job.matchAll(/^ needs: (.+)$/gm)].map(([, value]) => value), ["release-please"]); + assert.deepEqual([...job.matchAll(/^ if: (.+)$/gm)].map(([, value]) => value), [ + "${{ needs.release-please.outputs.releases_created == 'true' && contains(needs.release-please.outputs.paths_released, 'packages/" + name + "') }}", + ]); + assert.match(job, /^ runs-on: ubuntu-latest$/m); + assert.match(job, /^ permissions:\n contents: read\n id-token: write\n/m); + assert.match(job, /^ env:\n NPM_CONFIG_LEGACY_PEER_DEPS: "true"\n/m); + assert.deepEqual([...job.matchAll(/^ uses: (.+)$/gm)].map(([, value]) => value), [ + "actions/checkout@v4", + "actions/setup-node@v4", + ]); + assert.match(job, /^ uses: actions\/setup-node@v4\n with:\n node-version: 24\n registry-url: https:\/\/registry\.npmjs\.org\n cache: npm\n cache-dependency-path: package-lock\.json\n/m); + assert.deepEqual([...job.matchAll(/^ - name: (.+)$/gm)].map(([, value]) => value), [ + "Checkout", + "Setup Node", + "Install dependencies", + "Run tests", + "Verify package contents", + "Publish to npm", + ]); + assert.deepEqual([...job.matchAll(/^ run: (.+)$/gm)].map(([, value]) => value), [ + "npm ci", + `npm test --workspace ${workspace}`, + `npm run pack:dry-run --workspace ${workspace}`, + `npm publish --workspace ${workspace} --access public --provenance`, + ]); + }); +} + +test("release workflow ends at npm acceptance without scanning or polling", () => { + const workflow = readText(".github/workflows/release-please.yml"); - assert.doesNotMatch(workflow, /npm publish --workspace/); - assert.doesNotMatch(workflow, /release_created|paths_released/); + assert.doesNotMatch(workflow, /npm-publish-workspace-|npm\s+view|NPM_PUBLISH_|\bsleep\b|\bretry\b/); + assert.doesNotMatch(workflow, /always\(\)|continue-on-error:/); }); test("pi-frontend-design package metadata points at the workspace package", () => {