name: publish

on:
  workflow_run:
    workflows: [test]
    types: [completed]
    branches: [main]

concurrency:
  group: publish
  cancel-in-progress: true

jobs:
  publish:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    permissions:
      contents: read
      id-token: write
      packages: write
    steps:
      # Set everything up
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
          submodules: 'recursive'
      - uses: actions/setup-node@v4
        with:
          node-version: 22

      # Run tests and whatnot
      - run: npm install
      - run: npm run build

      # Publish to npm registry
      - run: npm set //registry.npmjs.org/:_authToken ${{ secrets.NPM_TOKEN }}
      - run: npm config set registry https://registry.npmjs.org
      - run: npm exec npm@latest -- publish --provenance --access public --tag latest

      # Publish to github registry
      - run: npm set //npm.pkg.github.com/:_authToken ${{ github.token }}
      - run: npm config set registry https://npm.pkg.github.com
      # note: remove this after we can release as @engine262/engine262 on npm
      - run: node -e "let pkg=require('./package.json'); pkg.name='@engine262/engine262'; require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2));"
      - run: npm publish --access=public

      # Push build to to gh-pages
      - run: |
          git config --global user.email "gha@example.com"
          git config --global user.name "GHA"
          git remote add github "https://$GITHUB_ACTOR:$BETTER_GITHUB_TOKEN@github.com/$GITHUB_REPOSITORY.git"

          git fetch github
          git checkout gh-pages

          cp -r lib/* .
          git add engine262.*
          git add inspector.*
          git commit -m "autobuild" || exit 0 # exit silently if nothing changed
          git push -u github gh-pages
        env:
          BETTER_GITHUB_TOKEN: ${{secrets.BETTER_GITHUB_TOKEN}}
