All files segmentWrapper.js

94.34% Statements 50/53
90.48% Branches 19/21
86.67% Functions 13/15
97.96% Lines 48/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                3x   3x       3x   3x           41x                   3x   41x 9x 9x   9x           32x 32x 32x 32x                           3x         41x       41x         41x                       3x     41x 41x   41x 41x   41x           41x                                                       3x 41x 41x 41x   41x         41x 41x 41x       41x 31x 31x 30x     10x       41x     41x                     3x                       3x 6x 6x 6x     6x   6x               3x      
import {syncPixels} from './syncPixels'
import {getPageReferrer, updatePageReferrer} from './referrer'
import {getConfig} from './config'
import {getAdobeMCVisitorID} from './adobeRepository.js'
import {checkGdprIsAccepted, getGdprPrivacyValue} from './tcf'
import {getIsDMPReady} from './adobeDMP'
 
/* Default properties to be sent on all trackings */
const DEFAULT_PROPERTIES = {platform: 'web'}
/* Disabled integrations when no GDPR Privacy Value is true */
export const INTEGRATIONS_WHEN_NO_CONSENTS = {
  All: false
}
/* ServerSide Forwarding values */
const SSF = {enabled: 0, disabled: 1}
/* Static anonymousId for users that has not accepted consents */
const SEGMENT_ID_USER_WITHOUT_CONSENTS = 'anonymous_user'
 
/**
 * Get default properties using the constant and the window.__mpi object if available
 * @returns {{[key:string]: any}} Default properties to attach to track
 */
export const getDefaultProperties = () => ({
  ...DEFAULT_PROPERTIES,
  ...getConfig('defaultProperties')
})
 
/**
 * Get user traits from global analytics object and put in the object
 * @param {string} gdprPrivacyValue Determine if we have user consents
 * @returns {object} User traits with to add
 */
const getUserTraits = async gdprPrivacyValue => {
  // If user has not accepted GDPR then we should use a static anonymousId
  if (!checkGdprIsAccepted(gdprPrivacyValue)) {
    window.analytics.reset()
    window.analytics.setAnonymousId(SEGMENT_ID_USER_WITHOUT_CONSENTS)
 
    return {
      anonymousId: SEGMENT_ID_USER_WITHOUT_CONSENTS
    }
  }
 
  // If we have user consents, then create the user using anonymousId cookie
  return new Promise(resolve => {
    window.analytics.ready(() => {
      const user = window.analytics.user()
      resolve({
        anonymousId: user.anonymousId(),
        userId: user.id()
      })
    })
  })
}
 
/**
 * Get all needed integrations depending on the gdprPrivacy value.
 * One of them is the AdobeMarketingCloudVisitorId for Adobe Analytics integration.
 * @param {string} gdprPrivacyValue Tell if user has consents to be tracked
 * @returns {Promise<object>} Integrations that we need to use on the track
 */
const getTrackIntegrations = async gdprPrivacyValue => {
  /**
   * If user has rejected consents we still use the Adobe Analytics Integration
   * but we can't create MarketingCloudVisitorId so we just pass `true`
   */
  const adobeAnalyticsIntegration = checkGdprIsAccepted(gdprPrivacyValue)
    ? {marketingCloudVisitorId: await getAdobeMCVisitorID()}
    : true
 
  const restOfIntegrations = checkGdprIsAccepted(gdprPrivacyValue)
    ? {}
    : INTEGRATIONS_WHEN_NO_CONSENTS
 
  // if we don't have the user consents we remove all the integrations but Adobe Analytics
  return {
    ...restOfIntegrations,
    'Adobe Analytics': adobeAnalyticsIntegration,
    'Amazon Lambda': true
  }
}
 
/**
 * Get data like traits and integrations to be added to the context object
 * @param {object} context Context object with all the actual info
 * @returns {Promise<object>} New context with all the previous info and the new one
 */
export const decorateContextWithNeededData = async (context = {}) => {
  // we extract from the context if is a page in order
  // to use the correct referrer
  const {isPageTrack} = context
  const referrer = getPageReferrer({isPageTrack})
 
  const gdprPrivacyValue = await getGdprPrivacyValue()
  const isGdprAccepted = checkGdprIsAccepted(gdprPrivacyValue)
 
  const [integrations, isDMPReady, userTraits] = await Promise.all([
    getTrackIntegrations(gdprPrivacyValue),
    getIsDMPReady(),
    getUserTraits(gdprPrivacyValue)
  ])
 
  return {
    ...context,
    ...(!isGdprAccepted && {ip: '0.0.0.0'}), // anonymizing ip if user has no consents
    gdpr_privacy: gdprPrivacyValue,
    integrations: {
      ...context.integrations,
      ...integrations
    },
    page: {
      ...context.page,
      referrer
    },
    traits: {
      ...context.traits,
      ssf: isDMPReady ? SSF.enabled : SSF.disabled,
      ...userTraits
    }
  }
}
 
/**
 * The track method lets you record any actions your users perform.
 * @param {string} event The name of the event you’re tracking
 * @param {object} [properties] A dictionary of properties for the event.
 * @param {object} [context] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const track = (event, properties, context = {}, callback) =>
  new Promise((resolve, reject) => {
    const initTrack = async () => {
      const newContext = await decorateContextWithNeededData(context)
 
      const newProperties = {
        ...getDefaultProperties(),
        ...properties
      }
 
      const newCallback = async (...args) => {
        if (callback) callback(...args) // eslint-disable-line standard/no-callback-literal
        const [gdprPrivacyValue, isDMPReady] = await Promise.all([
          getGdprPrivacyValue(),
          getIsDMPReady()
        ])
        if (isDMPReady && checkGdprIsAccepted(gdprPrivacyValue)) {
          const marketingCloudVisitorId = await getAdobeMCVisitorID()
          return syncPixels(marketingCloudVisitorId)
            .then(() => resolve(...args))
            .catch(reject)
        } else {
          resolve()
        }
      }
 
      window.analytics.track(event, newProperties, newContext, newCallback)
    }
 
    initTrack()
  })
 
/**
 * Associate your users and their actions to a recognizable userId and traits.
 * @param {string} userId Id to identify the user.
 * @param {object} traits A dictionary of traits you know about the user, like their email or name.
 * @param {object} [options] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const identify = (userId, traits, options, callback) =>
  Promise.resolve(window.analytics.identify(userId, traits, options, callback))
 
/**
 * Record whenever a user sees a page of your website, along with any optional properties about the page.
 * It updates automatically the referrer from the context on SPA navigations.
 * @param {string} event The name of the event you’re tracking
 * @param {object=} properties A dictionary of properties for the event.
 * @param {object} [context] A dictionary of options.
 * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
 * @returns {Promise}
 */
const page = (event, properties, context = {}, callback) => {
  const pageCallback = (...args) => {
    Iif (callback) callback(...args) // eslint-disable-line standard/no-callback-literal
    updatePageReferrer()
  }
  // we put a flag on context to know this track is a page
  context.isPageTrack = true
 
  return track(event, properties, context, pageCallback)
}
 
/**
 * Resets the id, including anonymousId, and clear traits for the currently identified user and group.
 * NOTE: Only clears the cookies and localStorage set by analytics.
 * @returns {Promise}
 */
const reset = () => Promise.resolve(window.analytics.reset())
 
export default {page, identify, track, reset}