From b106cb9bf70b577ed821545f08de7a65b285134e Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Fri, 27 Nov 2026 11:47:25 -0600 Subject: [PATCH] Publish to npm automatically when a version lands on main --- .github/workflows/publish.yml | 79 ++++++++++++++++++++++++++++++++--- CONTRIBUTING.md | 9 ++-- package.json | 2 +- scripts/publish-plan.mjs | 64 ++++++++++++++++++++++++++++ scripts/publish-plan.test.mjs | 67 +++++++++++++++++++++++++++++ 5 files changed, 209 insertions(+), 12 deletions(-) create mode 100644 scripts/publish-plan.mjs create mode 100644 scripts/publish-plan.test.mjs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index bd92089..90c9189 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,16 +1,33 @@ name: Publish +# Publishes to npm when a version bump lands on main. Merging a "Prepare Node +# SDK x.y.z" PR is the release: this job publishes every package whose version +# npm does not have yet, then tags vX.Y.Z and creates the GitHub release. +# +# Authentication is npm trusted publishing (OIDC from this workflow), so there +# is no token to expire. NPM_TOKEN is the fallback until every package has a +# trusted publisher configured on npmjs.com. +# +# Safe to re-run: packages already on npm are skipped, and the tag and release +# are created only if they are missing. + on: push: - tags: - - 'v*' + branches: [main] + paths: + - 'packages/*/package.json' + workflow_dispatch: + +concurrency: + group: publish + cancel-in-progress: false jobs: publish: name: Publish to npm runs-on: ubuntu-latest permissions: - contents: read + contents: write id-token: write steps: - uses: actions/checkout@v5 @@ -19,8 +36,58 @@ jobs: node-version: 22 cache: 'npm' registry-url: 'https://registry.npmjs.org' - - run: npm ci - - run: npm run build - - run: npm publish --workspaces --access public + # Trusted publishing needs npm 11.5.1 or later. + - run: npm install -g npm@^11.5.1 + + - name: Find versions npm does not have + id: plan + run: | + node scripts/publish-plan.mjs > "$RUNNER_TEMP/plan.json" + cat "$RUNNER_TEMP/plan.json" + echo "version=$(node -p "require(process.env.RUNNER_TEMP + '/plan.json').version")" >> "$GITHUB_OUTPUT" + echo "dirs=$(node -p "require(process.env.RUNNER_TEMP + '/plan.json').packages.map(p => p.dir).join(' ')")" >> "$GITHUB_OUTPUT" + + - name: Build and test + if: steps.plan.outputs.dirs != '' + run: | + npm ci + npm run build + npm test + + - name: Publish + if: steps.plan.outputs.dirs != '' env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + DIRS: ${{ steps.plan.outputs.dirs }} + run: | + for dir in $DIRS; do + echo "::group::publish $dir" + npm publish --workspace "$dir" --access public --provenance + echo "::endgroup::" + done + + - name: Confirm the registry has every package + run: | + for i in 1 2 3 4 5 6 7 8 9 10; do + left=$(node scripts/publish-plan.mjs | node -p "JSON.parse(require('fs').readFileSync(0, 'utf8')).packages.length") + [ "$left" = "0" ] && exit 0 + echo "$left package(s) not visible yet; waiting" + sleep 30 + done + node scripts/publish-plan.mjs + exit 1 + + - name: Tag and release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.plan.outputs.version }} + run: | + tag="v$VERSION" + if ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + git tag "$tag" "$GITHUB_SHA" + git push origin "$tag" + fi + if ! gh release view "$tag" >/dev/null 2>&1; then + notes=$(awk -v v="$VERSION" '$0 ~ "^## \\[" v "\\]" {on=1; next} on && /^## \[/ {exit} on' CHANGELOG.md) + gh release create "$tag" --title "$tag" --notes "${notes:-All packages at $VERSION.}" --verify-tag + fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e466b07..c5250e5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -215,11 +215,10 @@ export function analyzeRequest(metadata: RequestMetadata): LocalAnalysis { (For maintainers only) -1. Update version in all package.json files -2. Update CHANGELOG.md -3. Create a git tag -4. Push to GitHub -5. Publish to npm +1. Open a "Prepare Node SDK x.y.z" pull request that sets the same version in every `packages/*/package.json` (and the `@webdecoy/node` dependency ranges) and adds the CHANGELOG entry. +2. Merge it. The Publish workflow runs on the push to `main`, builds and tests, publishes every package whose version npm does not have yet, checks the registry, then tags `vx.y.z` and creates the GitHub release from the CHANGELOG entry. + +Publishing authenticates with npm trusted publishing from `.github/workflows/publish.yml`. If a run fails partway, re-run it: packages already on npm are skipped. ## Getting Help diff --git a/package.json b/package.json index 2c08974..1770c2d 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "build": "turbo run build", "dev": "turbo run dev", "lint": "turbo run lint", - "test": "turbo run test && npm run test:playground && npm run test:signed-agent", + "test": "turbo run test && npm run test:playground && npm run test:signed-agent && node --test scripts/publish-plan.test.mjs", "clean": "turbo run clean && rm -rf node_modules", "format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"", "check:edge": "npm run check:edge -w @webdecoy/node -w @webdecoy/nextjs -w @webdecoy/hono", diff --git a/scripts/publish-plan.mjs b/scripts/publish-plan.mjs new file mode 100644 index 0000000..ad40e7d --- /dev/null +++ b/scripts/publish-plan.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +// Which public packages have a version that npm does not have yet. +// +// The publish workflow runs this on every push to main. A package whose +// package.json version is already on the registry is skipped, so a re-run +// after a partial failure publishes only what is missing, and a push that +// bumps nothing publishes nothing. +// +// Prints JSON: { version, packages: [{ name, dir }] }, in publish order +// (the core SDK first, then the packages that depend on it). +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +const ORDER = ['@webdecoy/node', '@webdecoy/client']; + +export function publishOrder(names) { + return [...names].sort((a, b) => { + const ia = ORDER.indexOf(a); + const ib = ORDER.indexOf(b); + return (ia === -1 ? ORDER.length : ia) - (ib === -1 ? ORDER.length : ib) || a.localeCompare(b); + }); +} + +export function readPackages(root) { + return readdirSync(join(root, 'packages'), { withFileTypes: true }) + .filter((d) => d.isDirectory()) + .map((d) => { + const dir = join('packages', d.name); + const pkg = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')); + return { name: pkg.name, version: pkg.version, private: pkg.private === true, dir }; + }) + .filter((p) => !p.private); +} + +async function published(name, version, fetchImpl) { + const res = await fetchImpl(`https://registry.npmjs.org/${name.replace('/', '%2f')}/${version}`, { + headers: { accept: 'application/json' }, + }); + if (res.status === 404) return false; + if (!res.ok) throw new Error(`registry answered ${res.status} for ${name}@${version}`); + return true; +} + +export async function plan(root, fetchImpl = fetch) { + const pkgs = readPackages(root); + const versions = new Set(pkgs.map((p) => p.version)); + if (versions.size !== 1) { + throw new Error(`packages disagree on the version: ${pkgs.map((p) => `${p.name}@${p.version}`).join(', ')}`); + } + const [version] = versions; + const missing = []; + for (const p of pkgs) { + if (!(await published(p.name, p.version, fetchImpl))) missing.push(p); + } + const byName = new Map(missing.map((p) => [p.name, p])); + return { + version, + packages: publishOrder(byName.keys()).map((n) => ({ name: n, dir: byName.get(n).dir })), + }; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + console.log(JSON.stringify(await plan(process.cwd()))); +} diff --git a/scripts/publish-plan.test.mjs b/scripts/publish-plan.test.mjs new file mode 100644 index 0000000..de8d1bc --- /dev/null +++ b/scripts/publish-plan.test.mjs @@ -0,0 +1,67 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { plan, publishOrder } from './publish-plan.mjs'; + +function repo(pkgs) { + const root = mkdtempSync(join(tmpdir(), 'publish-plan-')); + for (const [dir, pkg] of Object.entries(pkgs)) { + mkdirSync(join(root, 'packages', dir), { recursive: true }); + writeFileSync(join(root, 'packages', dir, 'package.json'), JSON.stringify(pkg)); + } + return root; +} + +const registry = (have) => async (url) => { + const [, name, version] = url.match(/npmjs\.org\/(.+)\/([^/]+)$/); + return { status: have.has(`${decodeURIComponent(name)}@${version}`) ? 200 : 404, ok: true }; +}; + +test('publishes only the versions npm does not have, core SDK first', async () => { + const root = repo({ + express: { name: '@webdecoy/express', version: '1.2.0' }, + webdecoy: { name: '@webdecoy/node', version: '1.2.0' }, + client: { name: '@webdecoy/client', version: '1.2.0' }, + }); + const result = await plan(root, registry(new Set(['@webdecoy/client@1.2.0']))); + assert.equal(result.version, '1.2.0'); + assert.deepEqual(result.packages.map((p) => p.name), ['@webdecoy/node', '@webdecoy/express']); +}); + +test('a push that bumps nothing publishes nothing', async () => { + const root = repo({ webdecoy: { name: '@webdecoy/node', version: '1.2.0' } }); + const result = await plan(root, registry(new Set(['@webdecoy/node@1.2.0']))); + assert.deepEqual(result.packages, []); +}); + +test('private packages are never published', async () => { + const root = repo({ + webdecoy: { name: '@webdecoy/node', version: '1.2.0' }, + internal: { name: '@webdecoy/internal', version: '1.2.0', private: true }, + }); + const result = await plan(root, registry(new Set())); + assert.deepEqual(result.packages.map((p) => p.name), ['@webdecoy/node']); +}); + +test('refuses when packages disagree on the version', async () => { + const root = repo({ + webdecoy: { name: '@webdecoy/node', version: '1.2.0' }, + express: { name: '@webdecoy/express', version: '1.1.0' }, + }); + await assert.rejects(plan(root, registry(new Set())), /disagree/); +}); + +test('a registry error stops the plan rather than publishing blind', async () => { + const root = repo({ webdecoy: { name: '@webdecoy/node', version: '1.2.0' } }); + await assert.rejects(plan(root, async () => ({ status: 503, ok: false })), /503/); +}); + +test('order puts the core SDK and client ahead of adapters', () => { + assert.deepEqual(publishOrder(['@webdecoy/hono', '@webdecoy/client', '@webdecoy/node']), [ + '@webdecoy/node', + '@webdecoy/client', + '@webdecoy/hono', + ]); +});