# This workflow will run tests using node and then publish a package to the npm registry when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages

name: Node.js Package

on:
  workflow_call:

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/
      - name: Check out Etherpad core
        uses: actions/checkout@v3
        with:
          repository: ether/etherpad-lite
      - uses: pnpm/action-setup@v3
        name: Install pnpm
        with:
          version: 10
          run_install: false
      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
      - uses: actions/cache@v4
        name: Setup pnpm cache
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-
      -
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      -
        name: Bump version (patch)
        run: |
          LATEST_TAG=$(git describe --tags --abbrev=0) || exit 1
          NEW_COMMITS=$(git rev-list --count "${LATEST_TAG}"..) || exit 1
          [ "${NEW_COMMITS}" -gt 0 ] || exit 0
          git config user.name 'github-actions[bot]'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          pnpm i
          pnpm version patch
          git push --follow-tags
      # This is required if the package has a prepare script that uses something
      # in dependencies or devDependencies.
      -
        run: pnpm i
      # `npm publish` must come after `git push` otherwise there is a race
      # condition: If two PRs are merged back-to-back then master/main will be
      # updated with the commits from the second PR before the first PR's
      # workflow has a chance to push the commit generated by `npm version
      # patch`. This causes the first PR's `git push` step to fail after the
      # package has already been published, which in turn will cause all future
      # workflow runs to fail because they will all attempt to use the same
      # already-used version number. By running `npm publish` after `git push`,
      # back-to-back merges will cause the first merge's workflow to fail but
      # the second's will succeed.
      -
        run: pnpm publish
        env:
          NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
      #-
      #  name: Add package to etherpad organization
      #  run: pnpm access grant read-write etherpad:developers
      #  env:
      #    NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
