diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index ed5631a..dee34cc 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -1,49 +1,40 @@ --- name: release description: >- - Bumps package.json and jsr.json, pushes branch release/VERSION, opens a PR to - main with auto-merge, and relies on CI to publish a GitHub release after merge. - Use when the user invokes /release or /release VERSION, asks for a release PR, - or wants to ship a new semver version. + Opens a release/X.Y.Z pull request with Prepare release. Merge is manual. + After merge, CI publishes to npm and JSR and tags vX.Y.Z. Use when the user + invokes /release or /release VERSION, asks for a release PR, or wants to ship + a new semver version. --- # Release (`/release` [VERSION]) -In chat, users may type **`/release`** (patch bump) or **`/release 1.2.3`** (explicit semver). Treat that as this workflow. - -## Goal - -Cut a **release PR** from `release/` → `main` with version bumps in `package.json` and `jsr.json`. Optional **VERSION** defaults to **patch bump** from the current `package.json` version. +In chat, users may type **`/release`** (patch bump), **`/release minor`**, **`/release major`**, or **`/release 1.2.3`**. See `RELEASING.md`. Do not publish, tag, or merge unless the user asks. ## Preconditions -- Clean git working tree (no uncommitted changes). -- `git` and [`gh`](https://cli.github.com/) installed and authenticated (`gh auth login`). -- Repo default branch is `main`. -- Remote branch `release/` must not already exist. +- Notes are under `## Unreleased` in `CHANGELOG.md`. +- `gh` is authenticated. +- The workflow runs from `main`. ## Steps -1. **Resolve VERSION** (if the user did not pass one): read `package.json` `version`, bump **patch** (e.g. `0.2.1` → `0.2.2`). -2. **Run the automation script** from the repo root (preferred): +1. Resolve VERSION: explicit `X.Y.Z`, or `patch` / `minor` / `major`. Omitted means patch. +2. From the repo root: ```bash - npm run release:pr -- [VERSION] + gh workflow run "Prepare release" --ref main -f version=VERSION ``` - Or: `node scripts/create-release-pr.mjs [VERSION]`. Omit `[VERSION]` for patch bump. - -3. If the script cannot enable auto-merge, tell the user to merge the PR manually once CI passes. +3. Tell the user to merge the pull request after they have looked at the diff. Prepare release runs the version, changelog, and `npm pack` checks before it pushes, because a pull request it opens does not start `pull_request` workflows. To run pull request checks on it, close and reopen the pull request. ## After merge -Merging into `main` triggers `.github/workflows/release-on-merge.yml`, which creates GitHub release tag `v-` and release notes. That **published** release runs `publish.yml` (npm + JSR). - -## Tag convention +`.github/workflows/publish.yml` publishes to npm and JSR with OIDC, then creates tag `vVERSION` (for example `0.4.1` → `v0.4.1`) and a GitHub Release from the changelog section. -GitHub release tag: `v-${VERSION}` (e.g. `0.2.2` → tag `v-0.2.2`), matching `publish.yml` expectations. +Tags through `v-0.4.0` keep the `v-` prefix. Leave those tags in place. ## Do not -- Commit unrelated files (e.g. stray `site/` or local-only dirs) on the release branch. -- Bump only one of `package.json` / `jsr.json`; both must match for publish. +- Enable auto-merge on the release pull request. +- Publish or tag from a workstation. diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..bcd6c5e --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,87 @@ +name: Prepare release + +on: + workflow_dispatch: + inputs: + version: + description: "X.Y.Z, or patch, minor, or major" + required: true + type: string + +concurrency: + group: prepare-release + cancel-in-progress: false + +permissions: {} + +jobs: + prepare: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + pull-requests: write + steps: + - name: Require main + run: test "$GITHUB_REF" = "refs/heads/main" + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + persist-credentials: true + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + + - id: version + env: + RELEASE_VERSION: ${{ inputs.version }} + run: echo "version=$(node scripts/release.mjs plan)" >> "$GITHUB_OUTPUT" + + - name: Bump package version + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: npm version "$RELEASE_VERSION" --no-git-tag-version + + - name: Set jsr.json version + run: node scripts/release.mjs bump + + - name: Move changelog section + run: node scripts/release.mjs changelog + + - name: Create release branch + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: git checkout -b "release/${RELEASE_VERSION}" + + - name: Check release + run: node scripts/release.mjs check + + - name: Build package + run: npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" + + - name: Commit and push + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add package.json jsr.json package-lock.json CHANGELOG.md + git commit -m "chore(release): bump version to ${RELEASE_VERSION}" + git push --set-upstream origin "release/${RELEASE_VERSION}" + + - name: Open pull request + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" + gh pr create \ + --base main \ + --head "release/${RELEASE_VERSION}" \ + --title "Release ${RELEASE_VERSION}" \ + --body-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 832bc5f..51b10f7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,113 +1,99 @@ name: Publish on: - release: - types: [published] - workflow_dispatch: - # GitHub does not start new workflow runs for events caused by the default - # GITHUB_TOKEN (e.g. gh release create in another workflow). After - # "Release on merge" creates a release, trigger publish here instead. - workflow_run: - workflows: [Release on merge] - types: [completed] + push: + branches: [main] + +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false + +permissions: {} jobs: - publish: - if: >- - github.event_name != 'workflow_run' || - github.event.workflow_run.conclusion == 'success' + lookup: runs-on: ubuntu-24.04 - # Explicit job permissions: org default token scopes must not block OIDC. - # actions: write is required for setup-node's npm cache save (contents: read alone - # can restore but not reserve/write caches → "token has no writable scopes"). + timeout-minutes: 15 + outputs: + version: ${{ steps.pr.outputs.version }} permissions: contents: read - actions: write - id-token: write + pull-requests: read steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event_name == 'workflow_run' && 'main' || github.event_name == 'release' && github.ref || 'main' }} - - - name: Decide whether to publish - id: gate + - id: pr env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail - if [[ "${{ github.event_name }}" != "workflow_run" ]]; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - exit 0 - fi - VERSION="$(node -p "require('./package.json').version")" - TAG="v-${VERSION}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - else - echo "No GitHub release ${TAG} yet (or release job was skipped); skipping publish." - echo "publish=false" >> "${GITHUB_OUTPUT}" - fi + ref="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq ' + [ + .[] + | select(.merged_at != null and .base.ref == "main" and .head.repo.full_name == env.GITHUB_REPOSITORY) + | .head.ref + | select(test("^release/(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$")) + | sub("^release/"; "") + ] + | if length > 1 then error("multiple release pull requests") else (.[0] // "") end + ')" + printf 'version=%s\n' "$ref" >> "$GITHUB_OUTPUT" - # Omit registry-url: setup-node otherwise sets NODE_AUTH_TOKEN to a placeholder and npm publish uses that instead of OIDC. - # Node 24 ships npm 11.x (≥11.5.1 in current LTS line). Node 22’s npm is 10.x; Corepack `prepare npm@11` does not replace - # the toolcache `npm` binary on GitHub-hosted runners, so `npm publish` stayed on 10.x and OIDC trusted publishing never ran. - - name: Setup Node - if: steps.gate.outputs.publish == 'true' - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + publish: + needs: lookup + if: success() && needs.lookup.outputs.version != '' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - node-version: 24 - cache: npm + persist-credentials: false - - name: Assert npm supports trusted publishing (OIDC) - if: steps.gate.outputs.publish == 'true' - run: | - set -euo pipefail - ver="$(npm --version)" - echo "npm ${ver}" - node -e " - const v = process.argv[1].split('.').map(Number); - const ok = v[0] > 11 || (v[0] === 11 && (v[1] > 5 || (v[1] === 5 && (v[2] || 0) >= 1))); - if (!ok) { console.error('npm ' + process.argv[1] + ' < 11.5.1; trusted publishing OIDC requires npm >= 11.5.1'); process.exit(1); } - " "$ver" - - - name: Ensure versions match - if: steps.gate.outputs.publish == 'true' - shell: bash - run: | - set -euo pipefail - PKG_VERSION="$(node -p "require('./package.json').version")" - JSR_VERSION="$(node -p "require('./jsr.json').version")" - TAG_NAME="${{ github.event.release.tag_name }}" - if [[ -z "$TAG_NAME" ]]; then - TAG_NAME="v-${PKG_VERSION}" - fi - if [[ "$PKG_VERSION" != "$JSR_VERSION" ]]; then - echo "Version mismatch: package.json=$PKG_VERSION, jsr.json=$JSR_VERSION" - exit 1 - fi - if [[ "$TAG_NAME" != "v$PKG_VERSION" && "$TAG_NAME" != "$PKG_VERSION" && "$TAG_NAME" != "v-${PKG_VERSION}" ]]; then - echo "Release tag '$TAG_NAME' does not match version '$PKG_VERSION' (expected '$PKG_VERSION', 'v$PKG_VERSION', or 'v-${PKG_VERSION}')." - exit 1 - fi + # Omit registry-url. setup-node would set NODE_AUTH_TOKEN and npm would skip OIDC. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false - - name: Install dependencies - if: steps.gate.outputs.publish == 'true' - run: npm install --ignore-scripts --no-package-lock + - name: Check release + env: + RELEASE_HEAD_REF: release/${{ needs.lookup.outputs.version }} + run: node scripts/release.mjs check - # If NODE_AUTH_TOKEN / NPM_TOKEN are set to empty or a placeholder (repo/org Variables, - # or setup-node + registry-url), npm prefers them over OIDC and fails with ENEEDAUTH. - name: Publish to npm - if: steps.gate.outputs.publish == 'true' run: | - set -euo pipefail - if [[ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" || -z "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ]]; then - echo "::error::GitHub OIDC is unavailable (missing ACTIONS_ID_TOKEN_*). Check job permissions id-token: write and repo Settings → Actions → Workflow permissions." - exit 1 - fi unset NODE_AUTH_TOKEN NPM_TOKEN - npm publish --access public --provenance + npm publish --provenance --access public - name: Publish to JSR - if: steps.gate.outputs.publish == 'true' - run: npx jsr publish + run: npx --yes jsr@0.14.3 publish + + github-release: + needs: [lookup, publish] + if: needs.lookup.outputs.version != '' && needs.publish.result == 'success' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + - name: Create GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ needs.lookup.outputs.version }} + run: | + set -euo pipefail + node scripts/release.mjs notes > "${RUNNER_TEMP}/notes.md" + gh release view "v${VERSION}" || gh release create "v${VERSION}" \ + --target "$GITHUB_SHA" \ + --title "v${VERSION}" \ + --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/release-check.yml b/.github/workflows/release-check.yml new file mode 100644 index 0000000..b896807 --- /dev/null +++ b/.github/workflows/release-check.yml @@ -0,0 +1,35 @@ +name: Release check + +on: + pull_request: + branches: [main] + +permissions: {} + +jobs: + check: + name: Release check + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Check version and changelog + env: + RELEASE_HEAD_REF: ${{ github.head_ref }} + run: node scripts/release.mjs check + + - name: Test the release helper + run: node --test scripts/release.test.mjs + + - name: Build package + run: npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" diff --git a/.github/workflows/release-on-merge.yml b/.github/workflows/release-on-merge.yml deleted file mode 100644 index e22a1ac..0000000 --- a/.github/workflows/release-on-merge.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Release on merge - -# When a release/* PR merges into main, create a GitHub release (tag v-). -# Events from GITHUB_TOKEN do not start other workflows; publish.yml is triggered via -# workflow_run when this workflow completes (see publish.yml). - -on: - pull_request: - types: [closed] - branches: - - main - -concurrency: - group: release-on-merge-${{ github.event.pull_request.number }} - cancel-in-progress: false - -permissions: - contents: write - -jobs: - github-release: - if: >- - github.event.pull_request.merged == true && - startsWith(github.head_ref, 'release/') && - github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-24.04 - steps: - - name: Checkout merge commit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.merge_commit_sha }} - - - name: Read version - id: ver - run: | - VERSION="$(node -p "require('./package.json').version")" - echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" - - - name: Create GitHub release - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -euo pipefail - VERSION="${{ steps.ver.outputs.version }}" - TAG="v-${VERSION}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "Release ${TAG} already exists; skipping." - exit 0 - fi - gh release create "${TAG}" \ - --repo "${{ github.repository }}" \ - --title "${VERSION}" \ - --generate-notes diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e14c1f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## Unreleased + +## 0.4.0 - 2026-11-02 + +Tagged `v-0.4.0`. Notes are on that GitHub Release. diff --git a/README.md b/README.md index 8f062c6..1f27934 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ Extensions for JavaScript HTTP libraries to support **sending and receiving custom proxy headers** during HTTPS CONNECT tunneling. +See [RELEASING.md](RELEASING.md) to publish a new version. + ## The Problem When making HTTPS requests through a proxy, the connection is established via a CONNECT tunnel. During this process: diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..fdcf99f --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,41 @@ +# Releasing + +## Cut a release + +1. Add notes under `## Unreleased` in `CHANGELOG.md`. +2. Run Actions → **Prepare release** on `main`. Set `version` to `X.Y.Z`, or to `patch`, `minor`, or `major`. + + ```bash + gh workflow run "Prepare release" --ref main -f version=X.Y.Z + ``` + +3. The workflow bumps the version, moves the changelog, runs the release checks, then pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the new changelog section. Merge the pull request yourself. +4. A pull request opened with the Actions token does not start `pull_request` workflows. Prepare release runs the checks before it pushes. To run pull request checks on it, close and reopen the pull request. + +## What runs + +### Prepare release + +Creates `release/X.Y.Z` from `main`. `npm version` sets `package.json` and `package-lock.json`. `scripts/release.mjs bump` sets `jsr.json`, then the script moves `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`. The job then runs the release check and `npm pack` before the push. + +### Release check + +On pull requests into `main`, the job **Release check** runs the same version and changelog check, `node --test scripts/release.test.mjs`, and `npm pack`. For a `release/X.Y.Z` head, the branch name, `package.json`, `jsr.json`, `package-lock.json`, and a dated changelog section must match. Other pull requests check that those manifests match and that `## Unreleased` exists. + +### Publish + +A push to `main` runs **lookup**. When the merged pull request comes from this repo, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run; otherwise they are skipped. **publish** publishes with `npm publish --provenance --access public` and `npx --yes jsr@0.14.3 publish` (GitHub OIDC). A version already on npm or JSR fails that command. **github-release** then runs `gh release view` or `gh release create` for tag `vX.Y.Z`, with the changelog section as the notes. + +## One-time owner setup + +1. Under Settings → Actions → General, allow GitHub Actions to create and approve + pull requests. Prepare release needs that to open the pull request. +2. If branch protection still requires Release on merge, drop it. Don't make + Release check a required check: release PRs are opened with GITHUB_TOKEN, so + it doesn't run on them unless you close and reopen the PR. + +## Tags + +New tags are `vX.Y.Z` (for example `v0.4.1`). + +Tags through `0.4.0` used a hyphen: `v-0.2.0` through `v-0.4.0`. Those tags stay as they are. diff --git a/package.json b/package.json index 6c94ac8..cfccec3 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,6 @@ "LICENSE" ], "scripts": { - "release:pr": "node scripts/create-release-pr.mjs", "test:unit": "node --test test/test_connect_security.js test/test_ky_response.js", "test": "node test/test_proxy_headers.js core axios node-fetch got undici superagent ky wretch make-fetch-happen needle typed-rest-client", "test:run": "node run_tests.js", diff --git a/scripts/create-release-pr.mjs b/scripts/create-release-pr.mjs deleted file mode 100644 index 363a8b6..0000000 --- a/scripts/create-release-pr.mjs +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env node -/** - * Bumps package.json + jsr.json, opens release/VERSION → main PR, enables auto-merge. - * Usage: node scripts/create-release-pr.mjs [VERSION] - * If VERSION is omitted, bumps the patch segment of the current package.json version. - */ -import { execFileSync, execSync } from "node:child_process"; -import { readFileSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; - -const repoRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); - -function sh(cmd, inherit = false) { - return execSync(cmd, { - cwd: repoRoot, - encoding: "utf8", - stdio: inherit ? "inherit" : "pipe", - }).trim(); -} - -function gh(args, inherit = false) { - if (inherit) { - execFileSync("gh", args, { cwd: repoRoot, stdio: "inherit" }); - return ""; - } - return execFileSync("gh", args, { cwd: repoRoot, encoding: "utf8" }).trim(); -} - -function ensureCleanWorkingTree() { - const out = sh("git status --porcelain"); - if (out) { - throw new Error( - "Working tree is not clean. Commit or stash changes before running this script.", - ); - } -} - -function refExists(ref) { - try { - execSync(`git rev-parse --verify --quiet "${ref}"`, { - cwd: repoRoot, - stdio: "ignore", - }); - return true; - } catch { - return false; - } -} - -function remoteHeadsHas(branch) { - const out = sh(`git ls-remote --heads origin "${branch}"`); - return out.length > 0; -} - -function parseSemver(v) { - const m = String(v).match(/^(\d+)\.(\d+)\.(\d+)$/); - if (!m) { - throw new Error(`VERSION must be semver X.Y.Z (got ${JSON.stringify(v)})`); - } - return [Number(m[1]), Number(m[2]), Number(m[3])]; -} - -function bumpPatch(version) { - const [a, b, c] = parseSemver(version); - return `${a}.${b}.${c + 1}`; -} - -function cmpVersion(a, b) { - const pa = parseSemver(a); - const pb = parseSemver(b); - for (let i = 0; i < 3; i++) { - if (pa[i] > pb[i]) return 1; - if (pa[i] < pb[i]) return -1; - } - return 0; -} - -function readJson(path) { - return JSON.parse(readFileSync(path, "utf8")); -} - -function writeJson(path, obj) { - writeFileSync(path, `${JSON.stringify(obj, null, 2)}\n`, "utf8"); -} - -function main() { - process.chdir(repoRoot); - - const arg = process.argv[2]; - const pkgPath = join(repoRoot, "package.json"); - const jsrPath = join(repoRoot, "jsr.json"); - - ensureCleanWorkingTree(); - - const pkg = readJson(pkgPath); - const current = pkg.version; - const target = arg ? String(arg).trim() : bumpPatch(current); - - parseSemver(target); - if (cmpVersion(target, current) <= 0) { - throw new Error( - `New version must be greater than current ${current} (got ${target})`, - ); - } - - sh("git fetch origin main", true); - sh("git checkout main", true); - sh("git pull --ff-only origin main", true); - - const branch = `release/${target}`; - if (refExists(`refs/heads/${branch}`)) { - throw new Error( - `Local branch ${branch} already exists. Delete it or pick another version.`, - ); - } - if (remoteHeadsHas(branch)) { - throw new Error( - `Remote branch origin/${branch} already exists. Delete it or pick another version.`, - ); - } - - sh(`git checkout -b "${branch}"`, true); - - pkg.version = target; - writeJson(pkgPath, pkg); - - const jsr = readJson(jsrPath); - jsr.version = target; - writeJson(jsrPath, jsr); - - sh(`git add package.json jsr.json`, true); - sh(`git commit -m "chore(release): bump version to ${target}"`, true); - sh(`git push -u origin "${branch}"`, true); - - const body = [ - "Automated release PR.", - "", - `- Bumps \`package.json\` and \`jsr.json\` to **${target}**`, - `- Merging publishes GitHub release \`v-${target}\` and triggers npm/JSR publish (see \`.github/workflows/\`).`, - ].join("\n"); - - const prUrl = gh([ - "pr", - "create", - "--base", - "main", - "--head", - branch, - "--title", - `Release ${target}`, - "--body", - body, - ]); - - console.log(prUrl); - - try { - gh(["pr", "merge", prUrl, "--auto", "--merge"], true); - console.log("Auto-merge enabled; PR will merge when required checks pass."); - } catch { - console.warn( - "\nCould not enable auto-merge (repo may not allow it, or checks are pending). Merge the PR manually when ready.", - ); - } -} - -main(); diff --git a/scripts/release.mjs b/scripts/release.mjs new file mode 100644 index 0000000..ee4cf75 --- /dev/null +++ b/scripts/release.mjs @@ -0,0 +1,116 @@ +#!/usr/bin/env node +/** Changelog and release check: plan, bump, changelog, notes, check. */ +import { execFileSync } from "node:child_process"; +import { readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; +function parseSemver(value) { + const match = SEMVER.exec(String(value).trim()); + if (!match) throw new Error(`Version must be X.Y.Z, patch, minor, or major (got ${JSON.stringify(value)}).`); + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} +export function resolveVersion(current, input) { + const spec = String(input ?? "").trim(); + const [major, minor, patch] = parseSemver(current); + if (spec === "major") return `${major + 1}.0.0`; + if (spec === "minor") return `${major}.${minor + 1}.0`; + if (spec === "patch") return `${major}.${minor}.${patch + 1}`; + const [nextMajor, nextMinor, nextPatch] = parseSemver(spec); + const greater = nextMajor > major || (nextMajor === major && nextMinor > minor) || (nextMajor === major && nextMinor === minor && nextPatch > patch); + if (!greater) throw new Error(`New version must be greater than ${current} (got ${spec}).`); + return spec; +} +function heading(version) { + return new RegExp(`^## ${version.replaceAll(".", "\\.")} - \\d{4}-\\d{2}-\\d{2}\\s*$`); +} +function nextHeading(lines, start) { + const index = lines.findIndex((line, i) => i > start && line.startsWith("## ")); + return index < 0 ? lines.length : index; +} +export function moveUnreleased(markdown, version, date) { + const lines = markdown.split("\n"); + if (lines.some((line) => heading(version).test(line))) throw new Error(`CHANGELOG.md already has a ${version} section.`); + const start = lines.findIndex((line) => /^## Unreleased\s*$/.test(line)); + if (start < 0) throw new Error("CHANGELOG.md is missing a ## Unreleased section."); + const end = nextHeading(lines, start); + const header = lines.slice(0, start).join("\n").trim(); + const body = lines.slice(start + 1, end).join("\n").trim(); + const rest = lines.slice(end).join("\n").trim(); + const out = []; + if (header) out.push(header, ""); + out.push("## Unreleased", "", `## ${version} - ${date}`); + if (body) out.push("", body); + if (rest) out.push("", rest); + return `${out.join("\n")}\n`; +} +export function extractSection(markdown, version) { + const lines = markdown.split("\n"); + const start = lines.findIndex((line) => heading(version).test(line)); + if (start < 0) throw new Error(`CHANGELOG.md is missing a dated ${version} section.`); + return `${lines.slice(start, nextHeading(lines, start)).join("\n").trim()}\n`; +} +function manifestVersion() { + const pkg = JSON.parse(readFileSync("package.json", "utf8")).version; + const jsr = JSON.parse(readFileSync("jsr.json", "utf8")).version; + const lock = JSON.parse(readFileSync("package-lock.json", "utf8")); + const lockPackage = lock.packages[""].version; + if (pkg !== jsr || pkg !== lock.version || pkg !== lockPackage) { + throw new Error(`Version mismatch: package.json=${pkg}, jsr.json=${jsr}, package-lock.json=${lock.version}, packages[""]=${lockPackage}`); + } + parseSemver(pkg); + return pkg; +} +function bump() { + const version = JSON.parse(readFileSync("package.json", "utf8")).version; + const text = readFileSync("jsr.json", "utf8"); + const next = text.replace(/"version": "[^"]+"/, `"version": "${version}"`); + if (next === text) throw new Error("jsr.json has no version field."); + writeFileSync("jsr.json", next); +} +function check() { + const version = manifestVersion(); + const text = readFileSync("CHANGELOG.md", "utf8"); + if (!text.split("\n").some((line) => /^## Unreleased\s*$/.test(line))) { + throw new Error("CHANGELOG.md is missing a ## Unreleased section."); + } + const branch = (process.env.RELEASE_HEAD_REF ?? execFileSync("git", ["branch", "--show-current"], { encoding: "utf8" })).trim(); + if (!branch.startsWith("release/")) { + console.log(`Version manifests match at ${version}.`); + return; + } + const name = branch.slice("release/".length); + if (!SEMVER.test(name)) throw new Error(`Release branch must be release/X.Y.Z (got ${branch}).`); + if (name !== version) throw new Error(`Version ${version} does not match ${name}.`); + extractSection(text, version); + console.log(`Release check passed for ${version}.`); +} +function main() { + const command = process.argv[2]; + if (command === "plan") { + const input = process.argv[3] ?? process.env.RELEASE_VERSION; + process.stdout.write(`${resolveVersion(manifestVersion(), input)}\n`); + return; + } + if (command === "bump") return bump(); + if (command === "changelog") { + const path = "CHANGELOG.md"; + const date = new Date().toISOString().slice(0, 10); + writeFileSync(path, moveUnreleased(readFileSync(path, "utf8"), manifestVersion(), date)); + return; + } + if (command === "notes") { + process.stdout.write(extractSection(readFileSync("CHANGELOG.md", "utf8"), manifestVersion())); + return; + } + if (command === "check") return check(); + throw new Error(`Unknown command ${JSON.stringify(command)}.`); +} +const entry = process.argv[1]; +if (entry !== undefined && realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +} diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs new file mode 100644 index 0000000..e22b73b --- /dev/null +++ b/scripts/release.test.mjs @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { extractSection, moveUnreleased, resolveVersion } from "./release.mjs"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); + +test("resolveVersion bumps and rejects an older version", () => { + assert.equal(resolveVersion("1.2.3", "patch"), "1.2.4"); + assert.equal(resolveVersion("1.2.3", "minor"), "1.3.0"); + assert.equal(resolveVersion("1.2.3", "major"), "2.0.0"); + assert.equal(resolveVersion("1.2.3", "1.4.0"), "1.4.0"); + assert.throws(() => resolveVersion("1.2.3", "1.2.3"), /greater than/); + assert.throws(() => resolveVersion("1.2.3", "v1.2.4"), /X\.Y\.Z/); +}); + +test("moveUnreleased keeps the notes and the empty heading", () => { + const source = "# Changelog\n\n## Unreleased\n\n- Ship it.\n\n## 0.4.0 - 2026-11-02\n\n- Older.\n"; + const moved = moveUnreleased(source, "0.4.1", "2026-11-12"); + assert.equal(moved, "# Changelog\n\n## Unreleased\n\n## 0.4.1 - 2026-11-12\n\n- Ship it.\n\n## 0.4.0 - 2026-11-02\n\n- Older.\n"); + assert.equal(extractSection(moved, "0.4.1"), "## 0.4.1 - 2026-11-12\n\n- Ship it.\n"); + assert.throws(() => moveUnreleased(moved, "0.4.1", "2026-11-12"), /already has/); +}); + +test("check accepts this tree and rejects a mismatched release branch", () => { + const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version; + const ok = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { cwd: root, encoding: "utf8" }); + assert.equal(ok.status, 0, ok.stderr); + const release = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { + cwd: root, + encoding: "utf8", + env: { ...process.env, RELEASE_HEAD_REF: `release/${version}` }, + }); + assert.equal(release.status, 0, release.stderr); + const mismatch = spawnSync(process.execPath, ["scripts/release.mjs", "check"], { + cwd: root, + encoding: "utf8", + env: { ...process.env, RELEASE_HEAD_REF: "release/9.9.9" }, + }); + assert.equal(mismatch.status, 1); + assert.match(mismatch.stderr, /does not match 9\.9\.9/); +});