version: 2
references:
  default_container_config: &default_container_config
    docker:
      - image: node:12

  attach_workspace: &attach_workspace
    attach_workspace:
      at: ~/project

  npm_cache_key: &npm_cache_key v1-dependency-npm-{{ checksum "package-lock.json" }}

  restore_node_modules: &restore_node_modules
    restore_cache:
      keys:
        - *npm_cache_key
        - v1-dependency-npm-

  cache_node_modules: &cache_node_modules
    save_cache:
      key: *npm_cache_key
      paths:
        - ./node_modules/

  only_version_tags: &only_version_tags
    tags:
      only: /^v.*$/

jobs:
  install:
    <<: *default_container_config
    steps:
      - checkout
      - run:
          name: Upgrade npm
          command: npm i -g npm
      - *restore_node_modules
      - run:
          name: Install dependencies
          command: npm ci
      - *cache_node_modules
      - persist_to_workspace:
          root: .
          paths:
            - .

  test:
    <<: *default_container_config
    steps:
      - *attach_workspace
      - run:
          name: Run tests
          command: npm test

  release_npm:
    <<: *default_container_config
    steps:
      - *attach_workspace
      - run:
          name: Setup npm credentials
          command: echo "//registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN}" > ${HOME}/.npmrc
      - run:
          name: Publish npm package
          command: ./node_modules/.bin/npm-prepublish --verbose && npm publish --access public --unsafe-perm

workflows:
  version: 2
  build-and-release:
    jobs:
      - install:
          filters:
            <<: *only_version_tags
      - test:
          requires:
            - install
          filters:
            <<: *only_version_tags
      - release_npm:
          requires:
            - install
            - test
          filters:
            <<: *only_version_tags
            branches:
              ignore: /.*/
