name: TypeScript

on:
  push:
    branches:
      - main
  pull_request:
  release:
    types: [published]

jobs:
  detect-packages:
    runs-on: ubuntu-latest
    outputs:
      packages: ${{ steps.find-packages.outputs.packages }}
    steps:
      - uses: actions/checkout@v4
      - name: Find JS packages
        id: find-packages
        working-directory: src
        run: |
          PACKAGES=$(find . -name package.json -not -path "*/node_modules/*" -exec dirname {} \; | sed 's/^\.\///' | jq -R -s -c 'split("\n")[:-1]')
          echo "packages=$PACKAGES" >> $GITHUB_OUTPUT

  build:
    needs: [detect-packages]
    strategy:
      matrix:
        package: ${{ fromJson(needs.detect-packages.outputs.packages) }}
    name: Build ${{ matrix.package }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        working-directory: src/${{ matrix.package }}
        run: npm ci

      - name: Build package
        working-directory: src/${{ matrix.package }}
        run: npm run build

  publish:
    runs-on: ubuntu-latest
    needs: [build, detect-packages]
    if: github.event_name == 'release'
    environment: release

    strategy:
      matrix:
        package: ${{ fromJson(needs.detect-packages.outputs.packages) }}
    name: Publish ${{ matrix.package }}

    permissions:
      contents: read
      id-token: write

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          registry-url: "https://registry.npmjs.org"

      - name: Install dependencies
        working-directory: src/${{ matrix.package }}
        run: npm ci

      - name: Publish package
        working-directory: src/${{ matrix.package }}
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
