diff --git a/.changeset/config.json b/.changeset/config.json index 7355dc14..e7e97b23 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -5,7 +5,7 @@ "fixed": [], "linked": [], "access": "public", - "baseBranch": "main", + "baseBranch": "maintenance/v1", "updateInternalDependencies": "patch", "ignore": [ "@reflag/tsconfig", diff --git a/.github/workflows/publish-cli-v1.yml b/.github/workflows/publish-cli-v1.yml deleted file mode 100644 index b561c1b1..00000000 --- a/.github/workflows/publish-cli-v1.yml +++ /dev/null @@ -1,109 +0,0 @@ -name: Release CLI v1 - -on: - pull_request: - branches: [maintenance/v1] - paths: - - releases/cli-v1.json - - .github/workflows/publish-cli-v1.yml - - scripts/cli-v1-release*.mjs - push: - branches: [maintenance/v1] - paths: [releases/cli-v1.json] - -concurrency: cli-v1-release-${{ github.ref }} - -permissions: - contents: read - -jobs: - build: - name: Validate CLI v1 release - runs-on: ubuntu-latest - outputs: - version: ${{ steps.request.outputs.version }} - publish: ${{ steps.request.outputs.publish }} - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - run: corepack enable - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 - with: - node-version-file: .nvmrc - package-manager-cache: false - - name: Read the release request - id: request - run: node scripts/cli-v1-release.mjs request >> "$GITHUB_OUTPUT" - - name: Require a changed request on the protected v1 branch for publication - if: github.event_name == 'push' && steps.request.outputs.publish == 'true' - env: - BEFORE_SHA: ${{ github.event.before }} - run: | - if [[ "$GITHUB_REF" != refs/heads/maintenance/v1 || "$GITHUB_REF_PROTECTED" != true ]]; then - echo 'CLI v1 can only be published from the protected maintenance/v1 branch.' >&2 - exit 1 - fi - git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA" - changed=$(git diff --name-only "$BEFORE_SHA" "$GITHUB_SHA" -- releases/cli-v1.json) - if [[ "$changed" != releases/cli-v1.json ]]; then - echo 'A live release requires a new release request.' >&2 - exit 1 - fi - - name: Build, test, and pack only the CLI - run: | - node --test scripts/cli-v1-release.test.mjs - yarn install --immutable - yarn workspace @reflag/cli test - yarn workspace @reflag/cli build - yarn workspace @reflag/cli pack --out "$RUNNER_TEMP/reflag-cli.tgz" - - name: Check the packed version and npm latest tag - env: - CLI_VERSION: ${{ steps.request.outputs.version }} - run: | - set -o pipefail - tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs check - npm publish "$RUNNER_TEMP/reflag-cli.tgz" --registry https://registry.npmjs.org --access public --tag latest --ignore-scripts --dry-run - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - if: github.event_name == 'push' && steps.request.outputs.publish == 'true' - with: - name: reflag-cli-v1 - path: ${{ runner.temp }}/reflag-cli.tgz - if-no-files-found: error - overwrite: true - - publish: - name: Publish CLI v1 to npm latest - needs: build - if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance/v1' && needs.build.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: cli-v1-release - permissions: - contents: read - id-token: write - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - persist-credentials: false - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 - with: - node-version-file: .nvmrc - registry-url: https://registry.npmjs.org - package-manager-cache: false - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - name: reflag-cli-v1 - path: ${{ runner.temp }} - - name: Recheck the branch and npm latest, then publish the verified tarball - env: - CLI_VERSION: ${{ needs.build.outputs.version }} - run: | - set -o pipefail - head=$(git ls-remote --exit-code origin refs/heads/maintenance/v1 | cut -f1) - if [[ "$GITHUB_REF_PROTECTED" != true || "$head" != "$GITHUB_SHA" ]]; then - echo 'The release commit must still be the head of the protected maintenance/v1 branch.' >&2 - exit 1 - fi - tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs check - npm publish "$RUNNER_TEMP/reflag-cli.tgz" --registry https://registry.npmjs.org --access public --tag latest --ignore-scripts diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..0b18ee6f --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,102 @@ +name: Release v1 packages + +on: + push: + branches: [maintenance/v1] + pull_request: + branches: [maintenance/v1] + paths: + - releases/v1.json + - scripts/v1-release*.mjs + - .github/workflows/publish.yml + - .changeset/config.json + - package.json + +concurrency: release-v1-${{ github.ref }} + +permissions: + contents: read + +jobs: + version: + name: Open or update the v1 version PR + if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance/v1' + runs-on: ubuntu-latest + outputs: + has-changesets: ${{ steps.changesets.outputs.hasChangesets }} + steps: + - name: Require a protected branch + run: test "$GITHUB_REF_PROTECTED" = true + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - run: corepack enable + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version-file: .nvmrc + cache: yarn + - run: test ! -e .changeset/pre.json && yarn install --immutable + - uses: changesets/action@3841a0683d3cfa6dae0f9bb335290003010fe3f0 # v1.9.0 + id: changesets + with: + version: yarn version-v1-packages + title: Version Packages (v1) + commit: Version Packages (v1) + branch: maintenance/v1 + commitMode: github-api + github-token: ${{ secrets.CHANGESETS_BOT_TOKEN }} + + validate: + name: Validate the v1 npm release plan + needs: version + if: ${{ !cancelled() && (github.event_name == 'pull_request' || (needs.version.result == 'success' && needs.version.outputs.has-changesets == 'false')) }} + runs-on: ubuntu-latest + outputs: + pending: ${{ steps.plan.outputs.pending }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - run: corepack enable + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version-file: .nvmrc + package-manager-cache: false + - run: node --test scripts/v1-release.test.mjs + - name: Compare approved versions to unpublished npm versions + id: plan + run: node scripts/v1-release.mjs check >> "$GITHUB_OUTPUT" + + publish: + name: Publish stable v1 packages to npm latest + needs: validate + if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance/v1' && needs.validate.outputs.pending == 'true' && vars.V1_PUBLISH_ENABLED == 'true' + runs-on: ubuntu-latest + environment: npm-v1-release + permissions: + contents: write + id-token: write + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - run: corepack enable + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version-file: .nvmrc + registry-url: https://registry.npmjs.org + scope: "@reflag" + package-manager-cache: false + - run: yarn install --immutable + - run: yarn build + - name: Require the current protected v1 commit + shell: bash + run: | + head=$(git ls-remote --exit-code origin refs/heads/maintenance/v1 | cut -f1) + test "$GITHUB_REF_PROTECTED" = true && test "$head" = "$GITHUB_SHA" + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + - uses: changesets/action@3841a0683d3cfa6dae0f9bb335290003010fe3f0 # v1.9.0 + with: + publish: yarn publish-v1-packages + commitMode: github-api diff --git a/package.json b/package.json index f322f1b8..325ba690 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,9 @@ "lint": "yarn oxlint .", "lint:ci": "yarn oxlint .", "version-packages": "changeset version && YARN_ENABLE_IMMUTABLE_INSTALLS=false yarn install", + "version-v1-packages": "yarn version-packages && node scripts/v1-release.mjs plan", "release-packages": "yarn build && yarn release", + "publish-v1-packages": "node scripts/v1-release.mjs check && yarn release --tag latest", "release": "changeset publish", "docs": "./docs.sh", "lint:fix": "yarn oxlint --fix .", diff --git a/releases/cli-v1.json b/releases/cli-v1.json deleted file mode 100644 index e37bf6f9..00000000 --- a/releases/cli-v1.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "version": "1.0.5" -} diff --git a/releases/v1.json b/releases/v1.json new file mode 100644 index 00000000..fac98ea8 --- /dev/null +++ b/releases/v1.json @@ -0,0 +1,3 @@ +{ + "@reflag/cli": "1.0.5" +} diff --git a/scripts/cli-v1-release.mjs b/scripts/cli-v1-release.mjs deleted file mode 100644 index 598fdd75..00000000 --- a/scripts/cli-v1-release.mjs +++ /dev/null @@ -1,85 +0,0 @@ -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const packageName = "@reflag/cli"; -const stableV1 = /^1\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; - -export function parseReleaseRequest(request) { - if ( - !request || - typeof request.version !== "string" || - !stableV1.test(request.version) || - (Object.hasOwn(request, "publish") && - typeof request.publish !== "boolean") || - Object.keys(request).some((key) => key !== "version" && key !== "publish") - ) { - throw new Error( - "Expected a stable CLI v1 version and an optional publish boolean", - ); - } - return { version: request.version, publish: request.publish ?? false }; -} - -export function assertCliV1Release(manifest, requestedVersion, latest) { - if (manifest.name !== packageName || manifest.private) { - throw new Error(`Expected the public ${packageName} package`); - } - if ( - typeof requestedVersion !== "string" || - !stableV1.test(requestedVersion) || - manifest.version !== requestedVersion - ) { - throw new Error( - "The requested stable CLI v1 version must match the packaged version", - ); - } - - const current = typeof latest === "string" && stableV1.exec(latest); - if (!current) { - throw new Error( - `Refusing to update npm latest: '${latest}' is not a stable CLI v1 version`, - ); - } - const expected = `1.${current[1]}.${BigInt(current[2]) + 1n}`; - if (requestedVersion !== expected) { - throw new Error( - `Expected the next CLI v1 patch (${expected}), not ${requestedVersion}`, - ); - } -} - -if ( - process.argv[1] && - resolve(process.argv[1]) === fileURLToPath(import.meta.url) -) { - switch (process.argv[2]) { - case "request": { - const { version, publish } = parseReleaseRequest( - JSON.parse(readFileSync("releases/cli-v1.json", "utf8")), - ); - console.log(`version=${version}\npublish=${publish}`); - break; - } - case "check": { - const manifest = JSON.parse(readFileSync(0, "utf8")); - const response = await fetch( - `https://registry.npmjs.org/-/package/${encodeURIComponent(packageName)}/dist-tags`, - { signal: AbortSignal.timeout(10_000), cache: "no-store" }, - ); - if (!response.ok) { - throw new Error( - `Could not read npm dist-tags (HTTP ${response.status})`, - ); - } - const { latest, next } = await response.json(); - assertCliV1Release(manifest, process.env.CLI_VERSION, latest); - console.log( - `Verified ${packageName} can move npm latest from ${latest} to ${manifest.version} (next: ${next ?? "unset"})`, - ); - break; - } - default: - throw new Error("Expected request or check"); - } -} diff --git a/scripts/cli-v1-release.test.mjs b/scripts/cli-v1-release.test.mjs deleted file mode 100644 index 8b70ef94..00000000 --- a/scripts/cli-v1-release.test.mjs +++ /dev/null @@ -1,86 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; - -import { assertCliV1Release, parseReleaseRequest } from "./cli-v1-release.mjs"; - -const cli = { name: "@reflag/cli", version: "1.0.5" }; - -test("defaults to a dry run unless explicitly asked to publish", () => { - for (const request of [ - { version: cli.version }, - { version: cli.version, publish: false }, - ]) { - assert.deepEqual(parseReleaseRequest(request), { - version: cli.version, - publish: false, - }); - } - assert.deepEqual( - parseReleaseRequest({ version: cli.version, publish: true }), - { - version: cli.version, - publish: true, - }, - ); -}); - -test("rejects malformed release requests", () => { - for (const request of [ - null, - {}, - { version: "1.0.5-next.0", publish: true }, - { version: "2.0.0", publish: true }, - { version: "1.0.5\n", publish: true }, - { version: cli.version, publish: "true" }, - { version: cli.version, publish: null }, - { version: cli.version, tag: "next" }, - ]) { - assert.throws( - () => parseReleaseRequest(request), - /Expected a stable CLI v1 version/, - ); - } -}); - -test("accepts the next stable CLI v1 patch", () => { - assert.doesNotThrow(() => assertCliV1Release(cli, "1.0.5", "1.0.4")); -}); - -test("does not let a maintenance release move latest if it no longer points at a stable v1", () => { - for (const latest of [undefined, "0.9.9", "1.0.4-next.1", "2.0.0"]) { - assert.throws( - () => assertCliV1Release(cli, "1.0.5", latest), - /not a stable CLI v1/, - ); - } -}); - -test("rejects skipped patches, already released versions, and downgrades", () => { - for (const latest of ["1.0.3", "1.0.5", "1.0.6", "1.1.1"]) { - assert.throws( - () => assertCliV1Release(cli, "1.0.5", latest), - /Expected the next CLI v1 patch/, - ); - } -}); - -test("rejects unconfirmed, prerelease, and different package versions", () => { - for (const version of [undefined, "1.0.6", "1.0.5-next.0", "2.0.0"]) { - assert.throws( - () => assertCliV1Release(cli, version, "1.0.4"), - /must match the packaged version/, - ); - } -}); - -test("rejects building a different or private package", () => { - for (const manifest of [ - { ...cli, name: "@reflag/node-sdk" }, - { ...cli, private: true }, - ]) { - assert.throws( - () => assertCliV1Release(manifest, "1.0.5", "1.0.4"), - /Expected the public @reflag\/cli package/, - ); - } -}); diff --git a/scripts/v1-release.mjs b/scripts/v1-release.mjs new file mode 100644 index 00000000..003342c5 --- /dev/null +++ b/scripts/v1-release.mjs @@ -0,0 +1,151 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const planPath = "releases/v1.json"; +const npmRegistry = "https://registry.npmjs.org"; +const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +export function extendReleasePlan(plan, packages, previousVersion) { + return Object.fromEntries( + packages + .filter( + ({ name, version, path }) => + plan[name] === version || previousVersion(path) !== version, + ) + .map(({ name, version }) => [name, version]) + .sort(([a], [b]) => a.localeCompare(b)), + ); +} + +export async function checkReleasePlan( + plan, + packages, + { isPublished, latest }, +) { + const local = new Map(packages.map(({ name, version }) => [name, version])); + for (const [name, version] of Object.entries(plan)) { + if ( + typeof version !== "string" || + !stableVersion.test(version) || + local.get(name) !== version + ) { + throw new Error( + `Approved version ${name}@${version} does not match a stable public workspace version`, + ); + } + } + + const results = await Promise.all( + packages.map(async ({ name, version }) => { + if (await isPublished(name, version)) return null; + if (!Object.hasOwn(plan, name)) { + throw new Error(`Unapproved unpublished version: ${name}@${version}`); + } + const current = await latest(name); + const stable = typeof current === "string" && stableVersion.exec(current); + const expected = stable + ? `${stable[1]}.${stable[2]}.${BigInt(stable[3]) + 1n}` + : null; + if (version !== expected) { + throw new Error( + `Refusing ${name}@${version}: npm latest is ${current}; expected its next stable patch`, + ); + } + return `${name}@${version}`; + }), + ); + return results.filter(Boolean).sort(); +} + +function readWorkspaces() { + return execFileSync("yarn", ["workspaces", "list", "--json"], { + encoding: "utf8", + }) + .trim() + .split("\n") + .map((line) => JSON.parse(line)) + .flatMap(({ location }) => { + const path = `${location}/package.json`; + const { + name, + version, + private: isPrivate, + } = JSON.parse(readFileSync(path, "utf8")); + return isPrivate ? [] : [{ name, version, path }]; + }); +} + +async function registryGet(path) { + return fetch(`${npmRegistry}/${path}`, { + cache: "no-store", + signal: AbortSignal.timeout(10_000), + }); +} + +const registry = { + async isPublished(name, version) { + const response = await registryGet( + `${encodeURIComponent(name)}/${encodeURIComponent(version)}`, + ); + await response.body?.cancel(); + if (response.ok) return true; + if (response.status === 404) return false; + throw new Error( + `Could not check ${name}@${version} (HTTP ${response.status})`, + ); + }, + async latest(name) { + const response = await registryGet( + `-/package/${encodeURIComponent(name)}/dist-tags`, + ); + if (!response.ok) + throw new Error( + `Could not read tags for ${name} (HTTP ${response.status})`, + ); + return (await response.json()).latest; + }, +}; + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + if (existsSync(".changeset/pre.json")) { + throw new Error( + "The v1 workflow must not run in Changesets prerelease mode", + ); + } + const plan = JSON.parse(readFileSync(planPath, "utf8")); + if (!plan || typeof plan !== "object" || Array.isArray(plan)) { + throw new Error(`Expected a package-to-version map in ${planPath}`); + } + const packages = readWorkspaces(); + switch (process.argv[2]) { + case "plan": { + const updated = extendReleasePlan( + plan, + packages, + (path) => + JSON.parse( + execFileSync("git", ["show", `HEAD:${path}`], { encoding: "utf8" }), + ).version, + ); + writeFileSync(planPath, `${JSON.stringify(updated, null, 2)}\n`); + break; + } + case "check": { + const pending = await checkReleasePlan(plan, packages, registry); + console.error( + pending.length + ? `Approved npm latest candidates:\n${pending.join("\n")}` + : "No unpublished v1 releases", + ); + console.log(`pending=${pending.length > 0}`); + break; + } + default: + throw new Error("Expected plan or check"); + } +} diff --git a/scripts/v1-release.test.mjs b/scripts/v1-release.test.mjs new file mode 100644 index 00000000..169ed7a3 --- /dev/null +++ b/scripts/v1-release.test.mjs @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { checkReleasePlan, extendReleasePlan } from "./v1-release.mjs"; + +const cli = { + name: "@reflag/cli", + version: "1.0.5", + path: "packages/cli/package.json", +}; +const sdk = { + name: "@reflag/node-sdk", + version: "1.8.4", + path: "packages/node-sdk/package.json", +}; +const plan = { [cli.name]: cli.version, [sdk.name]: sdk.version }; +const registry = { + isPublished: async () => false, + latest: async (name) => (name === cli.name ? "1.0.4" : "1.8.3"), +}; + +test("keeps the already versioned CLI and adds versions changed by Changesets", () => { + const previous = { [cli.path]: cli.version, [sdk.path]: "1.8.3" }; + assert.deepEqual( + extendReleasePlan( + { [cli.name]: cli.version }, + [cli, sdk], + (path) => previous[path], + ), + plan, + ); +}); + +test("approves only the next stable patches in the release plan", async () => { + assert.deepEqual(await checkReleasePlan(plan, [cli, sdk], registry), [ + "@reflag/cli@1.0.5", + "@reflag/node-sdk@1.8.4", + ]); +}); + +test("does not republish an approved version that is already on npm", async () => { + const pending = await checkReleasePlan(plan, [cli, sdk], { + ...registry, + isPublished: async (name) => name === cli.name, + }); + assert.deepEqual(pending, ["@reflag/node-sdk@1.8.4"]); +}); + +test("rejects an unrelated unpublished workspace", async () => { + await assert.rejects( + checkReleasePlan({ [sdk.name]: sdk.version }, [cli, sdk], registry), + /Unapproved unpublished version: @reflag\/cli@1\.0\.5/, + ); +}); + +test("rejects a plan that differs from the checked-out packages or specifies a prerelease", async () => { + for (const version of ["1.0.6", "1.0.5-next.0"]) { + await assert.rejects( + checkReleasePlan({ ...plan, [cli.name]: version }, [cli, sdk], registry), + /does not match a stable public workspace/, + ); + } +}); + +test("does not move latest backward or skip a patch", async () => { + for (const latest of [ + undefined, + "0.9.9", + "2.0.0", + "1.0.5", + "1.0.3", + "1.0.4-next.0", + ]) { + await assert.rejects( + checkReleasePlan({ [cli.name]: cli.version }, [cli], { + ...registry, + latest: async () => latest, + }), + /expected its next stable patch/, + ); + } +});