version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:latest

jobs:
  test:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            - v1-dependencies-
      - run: npm install
      # These tests require built files to test against
      - run: npm run build
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
      - run: npm run test

  # Used to publish latest
  deploy:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            - v1-dependencies-
      - run: npm install
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
      - run: npm run build
      - run:
          name: Write NPM Token to ~/.npmrc
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npx semantic-release@17.0.4

workflows:
  version: 2

  # PULL REQUEST
  test:
    jobs:
      - test:
          filters:
            branches:
              ignore:
                - master

  # MERGE TO MASTER
  build-test-deploy:
    jobs:
      - deploy:
          filters:
            branches:
              only: master
