Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/tracking / dist / cjs / src / core / api.js
Size: Mime:
'use strict';

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var utils = require('../helpers/utils.js');
var handlers = require('./handlers.js');
var init = require('./init.js');
var consent = require('./consent.js');

var API = {
  /**
   * Factory method for initializing @doodle/tracking library, returning an instance of an API
   *
   * @public
   * @async
   * @param {TrackingApiOptions} options - The configuration options for API client
   * @return {API} - An initialized instance of API class
   */
  init: function init$1(options) {
    var _this = this;

    // Avoid initializing twice
    if (this._isInitialized) {
      return this;
    }

    this.options = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, options), {}, {
      services: utils.sampleServices(options.services, Math.random())
    });
    this.consents = [];
    this._activeServices = [];
    this._canTrack = !utils.hasDntEnabled();
    this._consentChangeListeners = this._consentChangeListeners || [];

    try {
      consent.watchForConsent(this.options, /*#__PURE__*/function () {
        var _ref = _rollupPluginBabelHelpers.asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(activeConsents, context) {
          var activeServices;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  _this.consents = activeConsents; // Inform external consent change listeners (eg to start loading Ads).

                  _this._consentChangeListeners.forEach(function (listener) {
                    return listener(activeConsents, context);
                  });

                  if (!_this._canTrack) {
                    _context.next = 17;
                    break;
                  }

                  _context.prev = 3;
                  _context.next = 6;
                  return init.initTracking(_this.options, _this.consents, _this._activeServices);

                case 6:
                  activeServices = _context.sent;
                  _this._isInitialized = Promise.resolve(true);
                  _this._activeServices = activeServices;
                  _context.next = 15;
                  break;

                case 11:
                  _context.prev = 11;
                  _context.t0 = _context["catch"](3);
                  console.error('Error occurred during tracking initialisation: ', _context.t0);
                  _this._isInitialized = Promise.resolve(false);

                case 15:
                  _context.next = 18;
                  break;

                case 17:
                  // No tracking is allowed (DNT enabled), thus do not init the trackers at all.
                  _this._isInitialized = Promise.resolve(true);

                case 18:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[3, 11]]);
        }));

        return function (_x, _x2) {
          return _ref.apply(this, arguments);
        };
      }());
    } catch (e) {
      console.error('Error occurred trying to ask for consent: ', e);
      this._isInitialized = Promise.resolve(false);
    }

    this.init = this.init.bind(this);
    this.reset = this.reset.bind(this);
    this.track = this.track.bind(this);
    this.identify = this.identify.bind(this);
    this.page = this.page.bind(this);
    this.getConsents = this.getConsents.bind(this);
    this.hasConsent = this.hasConsent.bind(this);
    this.showConsentPreferences = this.showConsentPreferences.bind(this);
    this.changeConsentPreferencesLanguage = this.changeConsentPreferencesLanguage.bind(this);
    this.registerConsentChangeListener = this.registerConsentChangeListener.bind(this);
    return this;
  },

  /**
   * Method to be used for instance when logging out without reloading the page
   *
   * @public
   * @return {boolean} - Indicates the success of the operation
   */
  reset: function reset() {
    delete this.options._userId;
    return true;
  },

  /**
   * Client method for tracking
   *
   * It may be called either with a trackingIntent or with a trackingEl, which carries tracking data attributes
   * In case both are passed: trackingIntent is preferred
   *
   * @public
   * @async
   * @param {Object} payload - Either a trackingIntent or a trackingEl must be part of the payload
   * @param {TrackingIntent} [payload.trackingIntent] - The tracking intent passed to the API client
   * @param {HTMLElement} [payload.trackingEl] - An HTML element with tracking data attributes
   * @param {MouseEvent} [payload.event] - A click event to be cancelled in case of same tab links
   * @return {Promise<Boolean>} returns true when all enabled destination services succeed or if any fail return false.
   */
  track: function track(_ref2) {
    var trackingIntent = _ref2.trackingIntent,
        trackingEl = _ref2.trackingEl,
        event = _ref2.event;

    if (!this._canTrack) {
      return Promise.resolve(false);
    }

    return handlers.handleTrack({
      trackingIntent: trackingIntent,
      trackingEl: trackingEl,
      event: event
    }, this.options, this.consents);
  },

  /**
   * Client method for user identification
   *
   * @public
   * @async
   * @param {Object} [payload] - Either a trackingIntent or a trackingEl must be part of the payload
   * @param {TrackingIntent} [payload.trackingIntent] - The tracking intent passed to the API client
   * @param {HTMLElement} [payload.trackingEl] - An HTML element with tracking data attributes
   * @return {Promise<boolean>}
   */
  identify: function identify(_ref3) {
    var trackingIntent = _ref3.trackingIntent,
        trackingEl = _ref3.trackingEl;

    if (!this._canTrack) {
      return Promise.resolve(false);
    }

    return handlers.handleIdentify({
      trackingIntent: trackingIntent,
      trackingEl: trackingEl
    }, this.options, this.consents);
  },

  /**
   * Client method for page identification
   *
   * @public
   * @async
   * @param {Object} [payload] - Either a trackingIntent or a trackingEl must be part of the payload
   * @param {TrackingIntent} [payload.trackingIntent] - The tracking intent passed to the API client
   * @param {HTMLElement} [payload.trackingEl] - An HTML element with tracking data attributes
   * @return {Promise<boolean>}
   */
  page: function page(_ref4) {
    var trackingIntent = _ref4.trackingIntent,
        trackingEl = _ref4.trackingEl;

    if (!this._canTrack) {
      return Promise.resolve(false);
    }

    return handlers.handlePage({
      trackingIntent: trackingIntent,
      trackingEl: trackingEl
    }, this.options, this.consents);
  },

  /**
   * Returns the currently active consents.
   * @public
   * @returns {string[]} The active consent categories.
   */
  getConsents: function getConsents() {
    return this.consents || [];
  },

  /**
   * Returns if the provided consent category ID has active consent.
   * @param {string} consentCategoryId - The consent category ID
   */
  hasConsent: function hasConsent(consentCategoryId) {
    return consent.hasConsent(consentCategoryId, this.getConsents());
  },

  /**
   * Show the consent preferences dialog.
   * @public
   */
  showConsentPreferences: function showConsentPreferences() {
    consent.handleShowConsentPreferences();
  },

  /**
   * Change the language of the consent preferences dialog.
   * @params {string} locale - The language/locale to switch to (eg. `de`, `fr`).
   * @public
   */
  changeConsentPreferencesLanguage: function changeConsentPreferencesLanguage(locale) {
    consent.handleChangeConsentPreferencesLanguage(locale);
  },

  /**
   * Registers a listener for consent changes.
   * @param {ConsentCallback} listener - The listener to register.
   */
  registerConsentChangeListener: function registerConsentChangeListener(listener) {
    if (!this._consentChangeListeners) {
      this._consentChangeListeners = [];
    }

    this._consentChangeListeners.push(listener);
  }
};

module.exports = API;
//# sourceMappingURL=api.js.map