---
# yamllint disable rule:line-length
name: "Publish to NPM"
on:  # yamllint disable-line rule:truthy
  release:
    types:
      - "published"

jobs:
  publish:
    name: Publish to NPM
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v4
        with:
          cache-dependency-path: ./package.json
          cache: "yarn"
          node-version: 18
      - uses: bahmutov/npm-install@v1
        with:
          useLockFile: false
      # Set the version in package.json to match the tag
      - name: Write release version
        run: |
          VERSION=${GITHUB_REF_NAME#v}
          echo Version: $VERSION
          echo "VERSION=$VERSION" >> $GITHUB_ENV
      # NOTE: the flag is necessary because otherwise `npm version <version>` attempts to
      # cut a git tag with that version, which fails because the git user isn't configured.
      - run: "npm version ${VERSION} --no-git-tag-version"
      - uses: JS-DevTools/npm-publish@v3
        with:
          token: ${{ secrets.NPM_TOKEN }}
          tag: ${{ steps.get_version.outputs.version }}
          access: public
  # NOTE: this publishes an alternate version that doesn't depend on protobuf-ts/runtime
  publish-js-client:
    name: Publish JS client to NPM
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v4
        with:
          node-version: 18
          cache-dependency-path: ./package.json
          cache: "yarn"
      # Install deps in base package and build into js-dist
      - uses: bahmutov/npm-install@v1
        with:
          useLockFile: false
      - name: Run build
        run: yarn build-js-client
      - uses: bahmutov/npm-install@v1
        with:
          useLockFile: false
          working-directory: ./js-dist
      # Set the version in package.json to match the tag
      - name: Write release version
        run: |
          VERSION=${GITHUB_REF_NAME#v}
          echo Version: $VERSION
          echo "VERSION=$VERSION" >> $GITHUB_ENV
      # NOTE: the flag is necessary because otherwise `npm version <version>` attempts to
      # cut a git tag with that version, which fails because the git user isn't configured.
      - run: "npm version ${VERSION} --no-git-tag-version"
        working-directory: ./js-dist
      - uses: JS-DevTools/npm-publish@v3
        with:
          token: ${{ secrets.NPM_TOKEN }}
          tag: ${{ steps.get_version.outputs.version }}
          # Point at the js-dist directory as the working directory
          package: js-dist
          access: public
