version: 2.1

jobs:
    build:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - restore_cache:
                  keys:
                      - dependency-cache-1-{{ checksum "package-lock.json" }}

            - run: npm install

            - save_cache:
                  paths:
                      - node_modules
                  key: dependency-cache-1-{{ checksum "package-lock.json" }}

            - persist_to_workspace:
                  root: "."
                  paths:
                      - ./*
                      - node_modules
                      - package-lock.json
                      - src

    compile:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - attach_workspace:
                  at: "."

            - run: npm run compile

            - persist_to_workspace:
                  root: "."
                  paths:
                      - src

    eslint:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - attach_workspace:
                  at: "."

            - run: npm run eslint

    publish:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - attach_workspace:
                  at: "."

            - run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc

            - run: npm publish || exit 0

    prettier:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - attach_workspace:
                  at: "."

            - run: npm run prettier --check

    test:
        docker:
            - image: circleci/node:latest

        working_directory: ~/repo

        steps:
            - checkout

            - attach_workspace:
                  at: "."

            - run: npm run test:ci

workflows:
    version: 2
    commit:
        jobs:
            - build
            - eslint:
                  requires:
                      - build
            - publish:
                  filters:
                      branches:
                          only: main
                  requires:
                      - compile
            - prettier:
                  requires:
                      - build
            - test:
                  requires:
                      - build
            - compile:
                  requires:
                      - build
