name: Publish to npm

# Publishes an existing release to npm by hand: for a release made before npm
# publishing was set up, or one whose npm step failed. New releases are
# published by the release workflow on their own.

on:
  workflow_dispatch:
    inputs:
      tag:
        description: Release tag to publish (such as v1.2.0)
        required: true
        type: string

permissions:
  contents: read
  id-token: write # npm provenance: links the npm version to this workflow run.

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Check the tag
        env:
          TAG: ${{ inputs.tag }}
        run: |
          if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
            echo "::error::'$TAG' is not a release tag such as v1.2.0."
            exit 1
          fi

      - uses: actions/checkout@v7
        with:
          ref: refs/tags/${{ inputs.tag }}

      - uses: actions/setup-node@v7
        with:
          node-version: 22
          registry-url: https://registry.npmjs.org

      # The tag holds the built dist/ files, so nothing needs installing.
      # npm trusted publishing (no token) needs npm 11.5.1 or later.
      - name: Publish
        env:
          TAG: ${{ inputs.tag }}
        run: |
          version="$(node -p "require('./package.json').version")"
          if [ "v$version" != "$TAG" ]; then
            echo "::error::package.json at $TAG says $version."
            exit 1
          fi
          npm install -g npm@11 --ignore-scripts
          npm publish --provenance --access public --ignore-scripts
