publish:
  image: node:12
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - package.json
  script:
    - npm ci
    - npm run build
    - echo //registry.npmjs.org/:_authToken=$NPM_TOKEN > .npmrc
    # Extract a few values from package.json
    - NPM_PACKAGE_NAME=$(node -p "require('./package.json').name")
    - NPM_PACKAGE_VERSION=$(node -p "require('./package.json').version")
    # Compare the version in package.json to all published versions.
    # If the package.json version has not yet been published, run `npm publish`.
    - |
      if [[ $(npm view "${NPM_PACKAGE_NAME}" versions) != *"'${NPM_PACKAGE_VERSION}'"* ]]; then
        npm publish --access public
      else
        echo "Version ${NPM_PACKAGE_VERSION} of ${NPM_PACKAGE_NAME} has already been published, so no new version has been published."
      fi
