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 / services / avo / destinations.js
Size: Mime:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var url = require('../../helpers/url.js');
var doodleDataLayer = require('../../helpers/doodleDataLayer.js');

var _excluded = ["type", "userId"],
    _excluded2 = ["name", "path", "referrer", "title", "url"];
/**
 * Maps Avo logEvent properties to a format Doodle Data Layer can understand.
 * @param {string} eventName - The event name
 * @param {object} eventProperties - The properties of the event.
 * @returns {object} - The event data in Doodle Data Layer format.
 */

function mapAvoLogEventToDoodleDataLayer(eventName, eventProperties) {
  var type = eventProperties.type,
      _eventProperties$user = eventProperties.userId,
      userId = _eventProperties$user === void 0 ? '' : _eventProperties$user,
      restProperties = _rollupPluginBabelHelpers.objectWithoutProperties(eventProperties, _excluded);

  return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({
    timestamp: new Date().toISOString(),
    event: eventName,
    type: type,
    user_id: userId || undefined
  }, url.getUtmParams()), {}, {
    properties: _rollupPluginBabelHelpers.objectSpread2({}, restProperties)
  });
}
/**
 * Maps Avo Identify Event/Action to a format Doodle Data Layer can understand.
 * @param {string} userId - The Users Id
 * @param {object} userProperties - Additional user properties
 * @returns {object} - The event data in Doodle Data Layer format.
 */


function mapAvoIdentifyEventToDoodleDataLayer(userId) {
  var userProperties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return {
    timestamp: new Date().toISOString(),
    user_id: userId,
    properties: userProperties
  };
}
/**
 * Maps Avo Log Page View Action/Event to a format Doodle Data Layer can understand.
 * @param {string} pageName - The page name
 * @param {object }pageProperties - Additional page properties
 * @returns {object} - The event data in Doodle Data Layer format.
 */


function mapAvoPageEventToDoodleDataLayer(pageName) {
  var pageProperties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  // eslint-disable-next-line no-unused-vars
  pageProperties.name;
      var path = pageProperties.path,
      referrer = pageProperties.referrer,
      title = pageProperties.title,
      url = pageProperties.url,
      properties = _rollupPluginBabelHelpers.objectWithoutProperties(pageProperties, _excluded2);

  return {
    timestamp: new Date().toISOString(),
    name: pageName,
    path: path,
    referrer: referrer,
    title: title,
    url: url,
    properties: properties
  };
}
/**
 * Custom No-Op destination, that can be used as a stand-in if configuration of doodleDataLayerDestination fails.
 * @type CustomAvoDestination
 * @see https://www.avo.app/docs/implementation/start-custom-destination#a-namejavascripta-javascript
 */


var noopDestination = {
  // eslint-disable-next-line no-unused-vars
  make: function make(env) {},
  // eslint-disable-next-line no-unused-vars
  logEvent: function logEvent(eventName, eventProperties) {},
  // eslint-disable-next-line no-unused-vars
  setUserProperties: function setUserProperties(userId, userProperties) {},
  // eslint-disable-next-line no-unused-vars
  identify: function identify(userId) {},
  unidentify: function unidentify() {},
  // eslint-disable-next-line no-unused-vars
  revenue: function revenue(amount, eventProperties) {},
  // eslint-disable-next-line no-unused-vars
  page: function page(pageName, eventProperties) {}
};
/**
 * Custom svc-data-layer destination for Avo.
 * @type CustomAvoDestination
 * @see https://www.avo.app/docs/implementation/start-custom-destination#a-namejavascripta-javascript
 */

var doodleDataLayerDestination = {
  svcDataLayerApi: null,
  clientId: null,
  userId: null,
  userProperties: {},

  /**
   * Configure the custom destination based on the passed in environment. Called during Avo init.
   * @param {string} env - The environment name
   */
  // eslint-disable-next-line no-unused-vars
  make: function make(env) {// No setup here, we rely on svcDataLayerApi and clientId
  },

  /**
   * Handles the actual logging of the event. Called by Avo when there's a Log Event attached on an event.
   * @async
   * @param {string} eventName - The name of the event.
   * @param {object} eventProperties - Additional properties of the event.
   */
  logEvent: function logEvent(eventName, eventProperties) {
    var _this = this;

    return _rollupPluginBabelHelpers.asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var destinationData, trackingApiOptions;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              destinationData = mapAvoLogEventToDoodleDataLayer(eventName, eventProperties);
              trackingApiOptions = _this.getApiOptions();
              _context.next = 4;
              return doodleDataLayer.trackDoodleDataLayer(destinationData, trackingApiOptions);

            case 4:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }))();
  },

  /**
   * Sets additional properties for an (identified) user.
   * @param {string} userId - The users ID to which to attache the properties
   * @param {object} userProperties - Additional user properties.
   */
  setUserProperties: function setUserProperties(userId, userProperties) {
    if (!userId) {
      return;
    }

    this.userId = userId;
    this.userProperties = userProperties || {};
  },

  /**
   * Identifies a user.
   * @async
   * @param {string} userId - The users ID.
   */
  identify: function identify(userId) {
    var _this2 = this;

    return _rollupPluginBabelHelpers.asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var destinationData, trackingApiOptions;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (userId) {
                _context2.next = 3;
                break;
              }

              console.warn('Cannot identify a user without a valid user ID. Please make sure you are using the identify() call to identify users.');
              return _context2.abrupt("return");

            case 3:
              _this2.userId = userId;
              destinationData = mapAvoIdentifyEventToDoodleDataLayer(userId, _this2.userProperties);
              trackingApiOptions = _this2.getApiOptions();
              _context2.next = 8;
              return doodleDataLayer.identifyDoodleDataLayer(destinationData, trackingApiOptions);

            case 8:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }))();
  },

  /**
   * Detach identifying properties from subsequent events
   */
  unidentify: function unidentify() {
    this.userId = null;
    this.userProperties = {};
  },

  /**
   * Handle revenue related analytics. Called when a Log Revenue action is configured.
   * @param {number} amount - The amount of revenue.
   * @param {object} eventProperties - Additional event properties.
   */
  // eslint-disable-next-line no-unused-vars
  revenue: function revenue(amount, eventProperties) {
    console.error("The 'revenue' call is not yet supported on the Doodle Data Layer destination for Avo.");
  },

  /**
   * Handle page related analytics/actions. Called when a Log Page View action is configured.
   * @async
   * @param {string} pageName - The name of the page
   * @param {object} eventProperties - Additional event properties.
   */
  page: function page(pageName, eventProperties) {
    var _this3 = this;

    return _rollupPluginBabelHelpers.asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var destinationData, trackingApiOptions;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              if (pageName) {
                _context3.next = 3;
                break;
              }

              console.warn('Cannot log a page view without a valid page name. Please make sure you are using the page() call to log page views.');
              return _context3.abrupt("return");

            case 3:
              destinationData = mapAvoPageEventToDoodleDataLayer(pageName, eventProperties);
              trackingApiOptions = _this3.getApiOptions();
              _context3.next = 7;
              return doodleDataLayer.pageDoodleDataLayer(destinationData, trackingApiOptions);

            case 7:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }))();
  },

  /**
   * Constructs the tracking API options used by sendToDoodleDataLayerInner.
   * @returns {TrackingApiOptions} - The tracking API options.
   */
  getApiOptions: function getApiOptions() {
    return {
      clientId: this.clientId,
      env: {
        svcDataLayerApi: this.svcDataLayerApi
      }
    };
  }
};
/**
 * Factory method to create a parametrized Doodle Data Layer destination for Avo.
 * @param {string} svcDataLayerApi - The endpoint of the svc-data-layer API.
 * @param {string} clientId - The ID of the client (the caller of this library).
 * @returns {CustomAvoDestination} - The parametrized destination.
 */

function createDoodleDataLayerDestination(svcDataLayerApi, clientId) {
  if (!svcDataLayerApi) {
    throw new TypeError('Please add svcDataLayerApi in your environment config. It is required for the Doodle Data Layer Destination to work.');
  }

  if (!clientId) {
    throw new TypeError('Please specify a clientId for the Doodle Data Layer destination.');
  }

  var parametrized = _rollupPluginBabelHelpers.objectSpread2({}, doodleDataLayerDestination);

  parametrized.svcDataLayerApi = svcDataLayerApi;
  parametrized.clientId = clientId;
  return parametrized;
}
/**
 * Returns all enabled custom Avo destinations.
 * @param {TrackingApiOptions} options - The API client's options
 * @returns {Array.<CustomAvoDestination>} - The Avo destinations
 */


function getAvoDestinations(_ref) {
  var clientId = _ref.clientId,
      _ref$env = _ref.env,
      env = _ref$env === void 0 ? {
    svcDataLayerApi: ''
  } : _ref$env;
  var destinations = [];

  if (clientId && env.svcDataLayerApi) {
    destinations.push(createDoodleDataLayerDestination(env.svcDataLayerApi, clientId));
  } else {
    console.warn('The clientId and svcDataLayerApi properties are required for the Doodle Data Layer Avo destination to work. The Doodle Data Layer Avo destination will be disabled and a No-Op destination will be used instead.');
    destinations.push(noopDestination);
  }

  return destinations;
}

exports.createDoodleDataLayerDestination = createDoodleDataLayerDestination;
exports.doodleDataLayerDestination = doodleDataLayerDestination;
exports.getAvoDestinations = getAvoDestinations;
exports.mapAvoIdentifyEventToDoodleDataLayer = mapAvoIdentifyEventToDoodleDataLayer;
exports.mapAvoLogEventToDoodleDataLayer = mapAvoLogEventToDoodleDataLayer;
exports.mapAvoPageEventToDoodleDataLayer = mapAvoPageEventToDoodleDataLayer;
exports.noopDestination = noopDestination;
//# sourceMappingURL=destinations.js.map