image: node:20.11.0-buster

definitions:
  steps:
    - step: &trivy_scan
        name: 'Trivy vulnerability scan'
        image: atlassian/default-image:5
        script:
          # Set up npm authentication
          - printf "//`node -p \"require('url').parse('https://registry.npmjs.org').host\"`/:_authToken=$NPM_TOKEN" >> .npmrc
          # Install npm dependencies to ensure package-lock.json is up to date
          - npm ci
          # Install Trivy using apt-get
          - apt-get update
          - apt-get install -y wget gnupg lsb-release
          - wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | apt-key add -
          - echo "deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | tee -a /etc/apt/sources.list.d/trivy.list
          - apt-get update
          - apt-get install -y trivy=${TRIVY_VERSION}
          # Run Trivy vulnerability scan on npm packages
          - trivy fs --scanners vuln --exit-code 1 --severity HIGH,CRITICAL --ignore-unfixed .
    - step: &lint_and_build
        name: 'Lint and build the NestJS package'
        caches:
          - node
        script:
          - printf "//`node -p \"require('url').parse('https://registry.npmjs.org').host\"`/:_authToken=$NPM_TOKEN" >> ~/.npmrc
          - npm ci
          - npm run lint
          - npm run build
    - step: &lint_build_and_publish
        name: 'Lint, Build and Publish'
        script:
          - printf "//`node -p \"require('url').parse('https://registry.npmjs.org').host\"`/:_authToken=$NPM_TOKEN" >> ~/.npmrc
          - npm ci
          - npm run lint
          - npm run build
          - npm publish

pipelines:
  branches:
    main:
      - step: *lint_build_and_publish
  pull-requests:
    '*':
      - step: *trivy_scan
      - step: *lint_and_build
