name: Release

# A change to the library code (src/) or its types (types/) on main makes a release: the version is
# bumped, dist/ rebuilt, CHANGELOG.md updated, and a tagged GitHub release is
# published with the minified files, then the package is published to npm
# through npm trusted publishing (no token). Patch by default; label the merged PR
# "release: minor" or "release: major" for a bigger bump.

on:
  push:
    branches: [main]
    paths:
      - 'src/**'
      - 'types/**'
  workflow_dispatch:
    inputs:
      bump:
        description: Version bump
        type: choice
        options: [patch, minor, major]
        default: patch

permissions:
  contents: write
  pull-requests: read
  issues: read
  id-token: write # npm provenance: links each npm version to this workflow run.

concurrency:
  group: release
  cancel-in-progress: false

jobs:
  release:
    runs-on: ubuntu-latest
    # The release commit itself also touches src/ (version banners); skip it.
    if: "!startsWith(github.event.head_commit.message, 'Release v')"
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
          # Pushes the release commit and tag with the "release-bot" deploy key,
          # which the "Protect main" ruleset lets bypass the pull request rule.
          # Without the secret it falls back to the workflow token.
          ssh-key: ${{ secrets.RELEASE_DEPLOY_KEY }}

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

      # Install scripts aren't needed for the build, and this job holds a write token.
      - run: npm ci --ignore-scripts

      # A run waits in the concurrency queue while an earlier one releases, so
      # main may have moved since the commit that triggered this run. Release
      # from the latest main; if its tip is already a release, the earlier run
      # included this change and there is nothing left to do.
      - name: Sync with the latest main
        id: sync
        run: |
          git fetch origin main
          git checkout -B main origin/main
          if git log -1 --format=%s | grep -q '^Release v'; then
            echo "Latest main is already a release; nothing to do."
            echo "skip=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Choose the version bump
        id: bump
        if: steps.sync.outputs.skip != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
          INPUT_BUMP: ${{ inputs.bump }}
        run: |
          bump="${INPUT_BUMP:-patch}"
          if [ "${{ github.event_name }}" = "push" ]; then
            labels="$(gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" --jq '[.[0].labels[]?.name] | join(",")' || true)"
            case ",$labels," in
              *",release: major,"*) bump=major ;;
              *",release: minor,"*) bump=minor ;;
            esac
          fi
          echo "bump=$bump" >> "$GITHUB_OUTPUT"

      - name: Bump version and update the changelog
        id: release
        if: steps.sync.outputs.skip != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: .github/scripts/release.sh "${{ steps.bump.outputs.bump }}"

      - name: Build
        if: steps.sync.outputs.skip != 'true'
        run: npm run build

      - name: Commit, tag and push
        if: steps.sync.outputs.skip != 'true'
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add package.json package-lock.json src dist CHANGELOG.md
          git commit -m "Release ${{ steps.release.outputs.tag }}"
          git tag "${{ steps.release.outputs.tag }}"
          # Atomic: the branch and the tag land together or not at all, so a
          # rejected push never leaves a stray tag behind.
          git push --atomic origin HEAD:main "${{ steps.release.outputs.tag }}"

      - name: Publish the GitHub release
        if: steps.sync.outputs.skip != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          notes="${{ steps.release.outputs.notes_file }}"
          printf '\n**Download:** `foldbox.min.js` (or the ES module `foldbox.mjs`) and `foldbox.min.css` below, or the readable files in `src/`.\n' >> "$notes"
          gh release create "${{ steps.release.outputs.tag }}" \
            --title "Foldbox ${{ steps.release.outputs.version }}" \
            --notes-file "$notes" \
            dist/foldbox.min.js dist/foldbox.mjs dist/foldbox.min.css

      # Last, so a failing npm publish never blocks the GitHub release (retry
      # with the "Publish to npm" workflow). npm trusted publishing: npm checks
      # this workflow's GitHub identity, so no token is stored. It needs npm
      # 11.5.1 or later, newer than the one Node 22 ships with.
      - name: Publish to npm
        if: steps.sync.outputs.skip != 'true'
        run: |
          npm install -g npm@11 --ignore-scripts
          npm publish --provenance --access public --ignore-scripts
