name: Publish npm

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag to publish (e.g. v0.1.11)'
        required: true

jobs:
  publish:
    runs-on: ubuntu-22.04
    permissions:
      contents: read
    steps:
      - name: Resolve tag
        id: tag
        run: echo "value=${{ github.event.release.tag_name || inputs.tag }}" >> "$GITHUB_OUTPUT"

      - name: Download release artifacts
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh release download "${{ steps.tag.outputs.value }}" --repo "${{ github.repository }}" --pattern "*-npm-package.tar.gz" --dir artifacts

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Publish to npm
        run: npm publish ./artifacts/*-npm-package.tar.gz --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
