From 37900ab6f7f5491a168b5ce6cbe63ab286f5cfe3 Mon Sep 17 00:00:00 2001 From: itvi-1234 Date: Thu, 3 Dec 2026 23:52:49 +0530 Subject: [PATCH] Publish the plugin packages to npm like the extensions repository Stage a new package's first release with a stage-only token, publish later releases through npm trusted publishing, and skip versions already on npm so running again is safe. Replaces the old release workflow. --- .github/workflows/ci.yml | 3 + .github/workflows/publish-npm.yml | 91 ++++++++++++++++++ .github/workflows/release.yml | 78 ---------------- backend/package.json | 2 +- docs/releases.md | 55 ++++++++++- package.json | 2 +- scripts/publish-npm.mjs | 150 ++++++++++++++++++++++++++++++ scripts/publish-npm.test.mjs | 96 +++++++++++++++++++ 8 files changed, 395 insertions(+), 82 deletions(-) create mode 100644 .github/workflows/publish-npm.yml delete mode 100644 .github/workflows/release.yml create mode 100644 scripts/publish-npm.mjs create mode 100644 scripts/publish-npm.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5aa9ca3..2b869e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,3 +29,6 @@ jobs: - run: npm ci - run: npm test - run: npm run build + - name: Test the publish script + if: matrix.dir == '.' + run: node --test scripts/ diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml new file mode 100644 index 0000000..be59f6a --- /dev/null +++ b/.github/workflows/publish-npm.yml @@ -0,0 +1,91 @@ +name: Publish to npm + +# Publishes the frontend and backend plugin packages at the version in their +# package.json files, the same way the extensions repository publishes its +# TypeScript bindings. Run it by hand from main; dry_run builds and checks +# without publishing. See scripts/publish-npm.mjs and docs/releases.md. +# +# A package's first release is staged with the NPM_STAGE_TOKEN secret, a +# stage-only token, and a maintainer approves it on npmjs.com. Later releases +# use npm trusted publishing: npm accepts this workflow file's OIDC identity, +# so no token is needed. Renaming this file breaks that trust. + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Build and check both packages without publishing anything' + type: boolean + default: true + +permissions: + contents: read + +concurrency: + group: publish-npm + cancel-in-progress: false + +jobs: + publish: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + # The tag and GitHub release for a published version. + contents: write + # npm trusted publishing. + id-token: write + env: + EXECUTE: ${{ !inputs.dry_run }} + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js for npm trusted publishing + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + + # npm stage publish needs npm 11.15.0 or later. + - name: Install npm with staged publishing + run: npm install --global npm@11.15.0 + + - name: Test the publish script + run: node --test scripts/ + + - name: Build and check both packages, then publish or stage them + id: publish + env: + NPM_STAGE_TOKEN: ${{ secrets.NPM_STAGE_TOKEN }} + run: | + if [[ "$EXECUTE" == true ]]; then + node scripts/publish-npm.mjs --execute + else + node scripts/publish-npm.mjs + fi + + - name: Generate the OpenAPI specification + if: steps.publish.outputs.released == 'true' + env: + VERSION: ${{ steps.publish.outputs.version }} + run: | + cd backend + # npm ci again: the backend was skipped when only the frontend had a new version. + npm ci + npm run openapi:generate -- "$VERSION" + + - name: Tag the release and create the GitHub release + if: steps.publish.outputs.released == 'true' + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.publish.outputs.version }} + run: | + set -euo pipefail + if gh release view "v$VERSION" > /dev/null 2>&1; then + echo "Release v$VERSION already exists." + exit 0 + fi + gh release create "v$VERSION" backend/dist/openapi.yaml --target "$GITHUB_SHA" --generate-notes diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 82f1ed6..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,78 +0,0 @@ -name: Release - -on: - push: - tags: - - 'v*' - -permissions: - contents: read - -jobs: - release: - runs-on: ubuntu-latest - permissions: - contents: write - concurrency: - group: release-${{ github.ref }} - env: - GH_TOKEN: ${{ github.token }} - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 - with: - node-version: 24 - registry-url: https://registry.npmjs.org - - - name: Get release version from tag - id: version - run: | - tag="${GITHUB_REF_NAME}" - version="${tag#v}" - - if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "::error::Invalid release tag: $tag. Expected vX.Y.Z." - exit 1 - fi - - echo "version=$version" >> "$GITHUB_OUTPUT" - echo "Releasing version $version" - - - name: Publish both packages - env: - VERSION: ${{ steps.version.outputs.version }} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - run: | - for dir in . backend; do - ( - cd "$dir" - - name=$(npm pkg get name | tr -d '"') - - if npm view "$name@$VERSION" version >/dev/null 2>&1; then - echo "$name@$VERSION already published, skipping" - exit 0 - fi - - npm ci - npm version "$VERSION" --no-git-tag-version - npm pkg set main=dist/index.js types=dist/index.d.ts - npm run build - npm publish - ) - done - - - name: Generate OpenAPI specification - env: - VERSION: ${{ steps.version.outputs.version }} - run: | - cd backend - npm ci - npm run openapi:generate -- "$VERSION" - - - name: Create GitHub release - run: | - gh release create "$GITHUB_REF_NAME" backend/dist/openapi.yaml \ - --generate-notes \ - --verify-tag diff --git a/backend/package.json b/backend/package.json index f37a218..2fb5b3f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "@runtimeconditions/plugin-runtime-conditions-backend", - "version": "0.0.0", + "version": "0.1.0", "license": "MIT", "repository": { "type": "git", diff --git a/docs/releases.md b/docs/releases.md index 7b38573..fb092b8 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -1,5 +1,56 @@ # Releases -Merging a `feat`, `fix`, `perf`, `revert`, or breaking change to `main` publishes both packages to npm at the same version, tags the merge commit `vX.Y.Z`, and creates a GitHub release. The release also includes the backend's `openapi.yaml`. Other changes, such as docs or CI, do not release. +Both packages, `@runtimeconditions/plugin-runtime-conditions` and +`@runtimeconditions/plugin-runtime-conditions-backend`, are published to npm at +the same version, the way the extensions repository publishes its bindings. -Versions follow semantic versioning and come from the PR titles described in [CONTRIBUTING.md](../CONTRIBUTING.md). Publishing uses npm trusted publishing, so no token is stored. `CONTRIBUTING.md` lists the one-time setup. \ No newline at end of file +## Releasing a version + +1. In a pull request, set the next version in both `package.json` and + `backend/package.json`. They must be the same. Follow semantic versioning: + a fix is a patch, a new feature a minor version, and a breaking change a + major version. +2. After the merge, open **Actions → Publish to npm → Run workflow** on `main`. + Leave **dry_run** ticked first: it builds and checks both packages and + publishes nothing. Then run it again with **dry_run** unticked. +3. The run publishes each package whose version is not on npm yet, tags the + commit `vX.Y.Z`, and creates a GitHub release with the backend's + `openapi.yaml`. A version that is already on npm is skipped, so running the + workflow again is safe. + +## How each package is published + +| On npm | What the run does | +| --- | --- | +| The package does not exist | Stages the first release with the `NPM_STAGE_TOKEN` secret. A maintainer approves it on npmjs.com under **Staged Packages** (asks for 2FA). | +| Only the staged placeholder (`0.0.0-stage`) | Skips it: the first release still waits for approval. | +| The version is already there | Skips it. | +| Anything else | Publishes through npm trusted publishing. No token is used. | + +The logic is in `scripts/publish-npm.mjs`, tested with `node --test scripts/`. + +## One-time setup + +1. **Stage-only token.** On npmjs.com, create a granular access token with + **Read and write (stage only)** for the `@runtimeconditions` packages, and + save it as the `NPM_STAGE_TOKEN` repository secret. It can only stage + releases, never publish them, so it stays useful for any future first + release. +2. **First release.** Run the workflow; both packages are staged. Approve both + on npmjs.com. +3. **Trusted publisher.** Once the packages exist, add this workflow as their + trusted publisher (asks for 2FA): + + ```sh + for p in @runtimeconditions/plugin-runtime-conditions @runtimeconditions/plugin-runtime-conditions-backend; do + npm trust github "$p" --file publish-npm.yml --repo runtimeconditions/backstage-plugin \ + --allow-publish --allow-stage-publish --yes + sleep 2 + done + ``` + + npm drops a trusted publisher that is not used within 2 days, so add it + just before the next release rather than right after the first. + +Renaming `.github/workflows/publish-npm.yml` breaks the trusted publisher; +add it again with the new file name. diff --git a/package.json b/package.json index e29152e..c1201b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@runtimeconditions/plugin-runtime-conditions", - "version": "0.0.0", + "version": "0.1.0", "license": "MIT", "repository": { "type": "git", diff --git a/scripts/publish-npm.mjs b/scripts/publish-npm.mjs new file mode 100644 index 0000000..31a0840 --- /dev/null +++ b/scripts/publish-npm.mjs @@ -0,0 +1,150 @@ +// Publishes the frontend and backend plugin packages to npm, the same way the +// extensions repository publishes its TypeScript bindings. +// +// node scripts/publish-npm.mjs dry run: build and check, publish nothing +// node scripts/publish-npm.mjs --execute real run +// +// Both packages publish the version in their package.json, which must be the +// same. For each package: +// +// - the version is already on npm: skipped, so running again is safe; +// - the package is not on npm yet: its first release is staged with the +// NPM_STAGE_TOKEN secret, a stage-only token, and a maintainer approves it on +// npmjs.com under Staged Packages; +// - only the staged placeholder is on npm: the first release still waits for +// approval, so it is skipped; +// - otherwise: published through npm trusted publishing (OIDC), with no token. +// +// Every package is looked up before anything is published, so a missing token +// stops the run before it has published only one of the two. + +import { execFileSync } from 'node:child_process'; +import { appendFileSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export const PACKAGES = ['.', 'backend']; +export const STAGE_PLACEHOLDER = '0.0.0-stage'; +export const STAGE_TOKEN = 'NPM_STAGE_TOKEN'; +const WORKFLOW = 'publish-npm.yml'; +const REPOSITORY = 'runtimeconditions/backstage-plugin'; + +export function summarize(message) { + console.log(message); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${message}\n\n`); +} + +export function writeOutput(name, value) { + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`); +} + +export function readPackage(root, dir) { + const manifest = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')); + return { dir, name: manifest.name, version: manifest.version }; +} + +/** The version both packages publish. They must agree, and 0.0.0 is not a release. */ +export function releaseVersion(packages) { + const versions = [...new Set(packages.map(item => item.version))]; + if (versions.length !== 1) { + throw new Error(`the packages have different versions (${versions.join(', ')}); give both the same version`); + } + const [version] = versions; + if (!/^\d+\.\d+\.\d+$/.test(version) || version === '0.0.0') { + throw new Error(`version ${version} is not a release; set the next version in both package.json files`); + } + return version; +} + +/** The versions npm lists for a package, or null when the package does not exist. */ +export function npmVersions(name, run = execFileSync) { + try { + const output = run('npm', ['view', name, 'versions', '--json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + const versions = JSON.parse(output || '[]'); + return Array.isArray(versions) ? versions : [versions]; + } catch (error) { + if (String(error.stderr ?? '').includes('E404')) return null; + throw new Error(`could not read ${name} from npm: ${String(error.stderr ?? error.message).trim()}`); + } +} + +/** What a run does with one package: skip it, stage its first release, wait for approval, or publish it. */ +export function decide(version, versions) { + if (versions === null) return 'stage'; + if (versions.includes(version)) return 'skip'; + if (versions.every(item => item === STAGE_PLACEHOLDER)) return 'waiting'; + return 'publish'; +} + +export function trustCommand(names) { + return names + .map(name => `npm trust github ${name} --file ${WORKFLOW} --repo ${REPOSITORY} --allow-publish --allow-stage-publish --yes`) + .join('\n'); +} + +export function main(argv = process.argv.slice(2), root = process.cwd(), run = execFileSync, env = process.env) { + const execute = argv.includes('--execute'); + const packages = PACKAGES.map(dir => readPackage(root, dir)); + const version = releaseVersion(packages); + const plan = packages.map(item => ({ ...item, action: decide(version, npmVersions(item.name, run)) })); + + if (execute && plan.some(item => item.action === 'stage') && !env[STAGE_TOKEN]) { + const names = plan.filter(item => item.action === 'stage').map(item => item.name).join(', '); + throw new Error(`${names} not on npm yet. A first release is staged with the stage-only token in the ${STAGE_TOKEN} secret, which is not set.`); + } + + const shell = (command, args, dir, extraEnv = {}) => + run(command, args, { cwd: join(root, dir), stdio: 'inherit', env: { ...env, ...extraEnv } }); + let released = false; + for (const item of plan) { + const label = `${item.name}@${version}`; + if (item.action === 'skip') { + summarize(`${label} is already on npm; skipped.`); + continue; + } + if (item.action === 'waiting') { + summarize(`${item.name} has a staged first release waiting for approval on npmjs.com (Staged Packages); skipped.`); + continue; + } + shell('npm', ['ci'], item.dir); + // The published package points at the compiled files, not the TypeScript sources. + shell('npm', ['pkg', 'set', 'main=dist/index.js', 'types=dist/index.d.ts'], item.dir); + shell('npm', ['run', 'build'], item.dir); + shell('npm', ['pack', '--dry-run'], item.dir); + if (!execute) { + summarize(`Built and checked ${label}; dry run, nothing was published (it would ${item.action === 'stage' ? 'stage its first release' : 'publish'}).`); + continue; + } + if (item.action === 'stage') { + shell('npm', ['stage', 'publish', '--access', 'public'], item.dir, { NODE_AUTH_TOKEN: env[STAGE_TOKEN] }); + summarize(`Staged ${label} as its first release. Approve it on npmjs.com under Staged Packages (asks for 2FA).`); + } else { + try { + shell('npm', ['publish', '--access', 'public'], item.dir); + } catch (error) { + // npm never takes a version twice; another run may have published it moments ago. + if ((npmVersions(item.name, run) ?? []).includes(version)) { + summarize(`${label} was published by another run meanwhile; skipped.`); + continue; + } + summarize( + `npm refused ${label}. If the package has no trusted publisher for this workflow yet, add one (asks for 2FA) and run again:\n\n\`\`\`sh\n${trustCommand([item.name])}\n\`\`\``, + ); + throw error; + } + summarize(`Published ${label}.`); + } + released = true; + } + writeOutput('version', version); + writeOutput('released', String(released && execute)); + return { version, plan, released: released && execute }; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + try { + main(); + } catch (error) { + console.error(`Publishing failed: ${error.message}`); + process.exit(1); + } +} diff --git a/scripts/publish-npm.test.mjs b/scripts/publish-npm.test.mjs new file mode 100644 index 0000000..312516f --- /dev/null +++ b/scripts/publish-npm.test.mjs @@ -0,0 +1,96 @@ +// Run with: node --test scripts/ +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import { decide, main, npmVersions, releaseVersion, STAGE_PLACEHOLDER, trustCommand } from './publish-npm.mjs'; + +const FRONTEND = '@runtimeconditions/plugin-runtime-conditions'; +const BACKEND = '@runtimeconditions/plugin-runtime-conditions-backend'; + +function checkout(frontend = '0.1.0', backend = '0.1.0') { + const root = mkdtempSync(join(tmpdir(), 'publish-npm-')); + mkdirSync(join(root, 'backend')); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: FRONTEND, version: frontend })); + writeFileSync(join(root, 'backend/package.json'), JSON.stringify({ name: BACKEND, version: backend })); + return root; +} + +/** A fake command runner: npm view answers from `registry`, every other command is recorded. */ +function runner(registry, { failPublish = new Set() } = {}) { + const calls = []; + const run = (command, args) => { + if (args[0] === 'view') { + const versions = registry[args[1]]; + if (versions === undefined) throw Object.assign(new Error('not found'), { stderr: 'npm error code E404' }); + return JSON.stringify(versions); + } + calls.push(`${command} ${args.join(' ')}`); + if (args[0] === 'publish' && failPublish.size) { + const name = [...failPublish][0]; + failPublish.delete(name); + throw new Error('E403'); + } + return ''; + }; + return { run, calls }; +} + +test('both packages must share a real version', () => { + assert.equal(releaseVersion([{ version: '0.2.0' }, { version: '0.2.0' }]), '0.2.0'); + assert.throws(() => releaseVersion([{ version: '0.2.0' }, { version: '0.3.0' }]), /different versions/); + assert.throws(() => releaseVersion([{ version: '0.0.0' }, { version: '0.0.0' }]), /not a release/); +}); + +test('each package gets the right action', () => { + assert.equal(decide('0.1.0', null), 'stage'); + assert.equal(decide('0.1.0', [STAGE_PLACEHOLDER]), 'waiting'); + assert.equal(decide('0.1.0', ['0.1.0']), 'skip'); + assert.equal(decide('0.2.0', [STAGE_PLACEHOLDER, '0.1.0']), 'publish'); +}); + +test('a missing package reads as null and other npm errors stop', () => { + assert.equal(npmVersions('x', runner({}).run), null); + const broken = () => { + throw Object.assign(new Error('boom'), { stderr: 'network down' }); + }; + assert.throws(() => npmVersions('x', broken), /could not read x from npm/); +}); + +test('a dry run builds and checks but never publishes', () => { + const { run, calls } = runner({}); + const result = main([], checkout(), run, {}); + assert.equal(result.released, false); + assert.ok(calls.includes('npm run build')); + assert.ok(!calls.some(call => call.includes('publish'))); +}); + +test('a first release is staged with the stage token, and nothing runs without it', () => { + assert.throws(() => main(['--execute'], checkout(), runner({}).run, {}), /NPM_STAGE_TOKEN secret, which is not set/); + const { run, calls } = runner({}); + const result = main(['--execute'], checkout(), run, { NPM_STAGE_TOKEN: 'stage-token' }); + assert.equal(calls.filter(call => call === 'npm stage publish --access public').length, 2); + assert.equal(result.released, true); +}); + +test('later releases publish, and versions already out are skipped', () => { + const { run, calls } = runner({ [FRONTEND]: ['0.1.0'], [BACKEND]: ['0.1.0', '0.2.0'] }); + main(['--execute'], checkout('0.2.0', '0.2.0'), run, {}); + assert.equal(calls.filter(call => call === 'npm publish --access public').length, 1); +}); + +test('a staged first release waiting for approval is skipped', () => { + const { run, calls } = runner({ [FRONTEND]: [STAGE_PLACEHOLDER], [BACKEND]: [STAGE_PLACEHOLDER] }); + const result = main(['--execute'], checkout(), run, {}); + assert.equal(result.released, false); + assert.ok(!calls.some(call => call.includes('publish'))); +}); + +test('a refused publish explains the trust command', () => { + const registry = { [FRONTEND]: ['0.1.0'], [BACKEND]: ['0.1.0'] }; + const { run } = runner(registry, { failPublish: new Set([FRONTEND]) }); + assert.throws(() => main(['--execute'], checkout('0.2.0', '0.2.0'), run, {}), /E403/); + assert.match(trustCommand([FRONTEND]), /npm trust github @runtimeconditions\/plugin-runtime-conditions --file publish-npm.yml/); +});