# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs

name: Node.js CI

on:
    push:
        branches: ['main']
    release:
        types: [published]


jobs:
    build:
        runs-on: ubuntu-latest
        env:
            GH_TOKEN: ${{ secrets.GH_TOKEN }}
            NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        strategy:
            matrix:
                node-version: ['18.x']

        steps:
            - uses: actions/checkout@v4
            - name: Use Node.js ${{ matrix.node-version }}
              uses: actions/setup-node@v4
              with:
                  node-version: ${{ matrix.node-version }}
                  cache: 'npm'
            - name: Install dependencies
              run: npm install
            - name: Generate certificates and upload
              run: node genrate.js
            - name: Run full workflow test
              run: npm test
            - name: Publish to npm on release
              if: github.event_name == 'release'
              run: |
                  if [ -z "$NODE_AUTH_TOKEN" ]; then
                    echo "NPM_TOKEN secret not configured, skipping publish"
                    exit 0
                  fi
                  # publishBoth.js uses npm_config__authToken which npm 10 ignores.
                  # Write a .npmrc with the auth token as a workaround.
                  echo "//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}" > .npmrc
                  export NPM_TOKEN="$NODE_AUTH_TOKEN"
                  npm run publish:packages
                  rm -f .npmrc
