# This file is automatically added by @npmcli/template-oss. Do not edit.

name: Audit

on:
  workflow_dispatch:
  schedule:
    # "At 08:00 UTC (01:00 PT) on Monday" https://crontab.guru/#0_8_*_*_1
    - cron: "0 8 * * 1"

jobs:
  audit:
    name: Audit Dependencies
    if: github.repository_owner == 'npm'
    runs-on: ubuntu-latest
    defaults:
      run:
        shell: bash
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Setup Git User
        run: |
          git config --global user.email "npm-cli+bot@github.com"
          git config --global user.name "npm CLI robot"
      - name: Setup Node
        uses: actions/setup-node@v3
        id: node
        with:
          node-version: 20.x
          check-latest: contains('20.x', '.x')

      - name: Install Latest npm
        shell: bash
        env:
          NODE_VERSION: ${{ steps.node.outputs.node-version }}
        run: |
          MATCH=""
          SPECS=("latest" "next-10" "next-9" "next-8" "next-7" "next-6")

          echo "node@$NODE_VERSION"

          for SPEC in ${SPECS[@]}; do
            ENGINES=$(npm view npm@$SPEC --json | jq -r '.engines.node')
            echo "Checking if node@$NODE_VERSION satisfies npm@$SPEC ($ENGINES)"

            if npx semver -r "$ENGINES" "$NODE_VERSION" > /dev/null; then
              MATCH=$SPEC
              echo "Found compatible version: npm@$MATCH"
              break
            fi  
          done

          if [ -z $MATCH ]; then
            echo "Could not find a compatible version of npm for node@$NODE_VERSION"
            exit 1
          fi

          npm i --prefer-online --no-fund --no-audit -g npm@$MATCH

      - name: npm Version
        run: npm -v
      - name: Install Dependencies
        run: npm i --ignore-scripts --no-audit --no-fund --package-lock
      - name: Run Production Audit
        run: npm audit --omit=dev
      - name: Run Full Audit
        run: npm audit --audit-level=none
