@ohos-ports/s-ui-segment-wrapper 0.0.0-stage → 5.4.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +269 -2
  2. package/lib/config.js +20 -0
  3. package/lib/events.js +3 -0
  4. package/lib/index.js +82 -0
  5. package/lib/middlewares/destination/optimizelySiteAttribute.js +17 -0
  6. package/lib/middlewares/source/campaignContext.js +10 -0
  7. package/lib/middlewares/source/defaultContextProperties.js +11 -0
  8. package/lib/middlewares/source/optimizelyUserId.js +15 -0
  9. package/lib/middlewares/source/pageData.js +42 -0
  10. package/lib/middlewares/source/pageReferrer.js +102 -0
  11. package/lib/middlewares/source/userScreenInfo.js +12 -0
  12. package/lib/middlewares/source/userTraits.js +48 -0
  13. package/lib/repositories/googleRepository.js +272 -0
  14. package/lib/repositories/xandrRepository.js +42 -0
  15. package/lib/segmentWrapper.js +364 -0
  16. package/lib/tcf.js +230 -0
  17. package/lib/universalId.js +48 -0
  18. package/lib/utils/checkAnonymousId.js +9 -0
  19. package/lib/utils/cookies.js +50 -0
  20. package/lib/utils/ga4Detection.js +18 -0
  21. package/lib/utils/hashEmail.js +24 -0
  22. package/lib/utils/patchAnalytics.js +36 -0
  23. package/lib/utils/storage.js +17 -0
  24. package/package.json +39 -4
  25. package/src/config.js +25 -0
  26. package/src/events.js +3 -0
  27. package/src/index.js +96 -0
  28. package/src/middlewares/destination/optimizelySiteAttribute.js +22 -0
  29. package/src/middlewares/source/campaignContext.js +12 -0
  30. package/src/middlewares/source/defaultContextProperties.js +15 -0
  31. package/src/middlewares/source/optimizelyUserId.js +20 -0
  32. package/src/middlewares/source/pageData.js +45 -0
  33. package/src/middlewares/source/pageReferrer.js +125 -0
  34. package/src/middlewares/source/userScreenInfo.js +11 -0
  35. package/src/middlewares/source/userTraits.js +41 -0
  36. package/src/repositories/googleRepository.js +251 -0
  37. package/src/repositories/xandrRepository.js +48 -0
  38. package/src/segmentWrapper.js +338 -0
  39. package/src/tcf.js +263 -0
  40. package/src/universalId.js +51 -0
  41. package/src/utils/checkAnonymousId.js +10 -0
  42. package/src/utils/cookies.js +56 -0
  43. package/src/utils/ga4Detection.js +22 -0
  44. package/src/utils/hashEmail.js +33 -0
  45. package/src/utils/patchAnalytics.js +46 -0
  46. package/src/utils/storage.js +18 -0
  47. package/src-umd/index.js +8 -0
  48. package/umd/index.js +1 -0
@@ -0,0 +1,272 @@
1
+ import _async_to_generator from "@swc/helpers/src/_async_to_generator.mjs";
2
+ import _extends from "@swc/helpers/src/_extends.mjs";
3
+ import _ts_generator from "@swc/helpers/src/_ts_generator.mjs";
4
+ import { dispatchEvent } from "@s-ui/js/lib/events/index.js";
5
+ import { getConfig } from "../config.js";
6
+ import { EVENTS } from "../events.js";
7
+ import { utils } from "../middlewares/source/pageReferrer.js";
8
+ import { isGA4DestinationEnabled } from "../utils/ga4Detection.js";
9
+ var FIELDS = {
10
+ clientId: "client_id",
11
+ sessionId: "session_id"
12
+ };
13
+ export var DEFAULT_DATA_LAYER_NAME = "dataLayer";
14
+ export var CONSENT_STATES = {
15
+ granted: "granted",
16
+ denied: "denied"
17
+ };
18
+ var CONSENT_STATE_GRANTED_VALUE = 1;
19
+ var CONSENT_STATE_DENIED_VALUE = 2;
20
+ var STC = {
21
+ QUERY: "stc",
22
+ SPLIT_SYMBOL: "-",
23
+ CAMPAIGN_SPLIT_SYMBOL: ":"
24
+ };
25
+ var UTM_CAMPAIGN = "utm_campaign";
26
+ var UTM_MEDIUM = "utm_medium";
27
+ var UTM_SOURCE = "utm_source";
28
+ var UTM_CONTENT = "utm_content";
29
+ var UTM_CAMPAIGN_ID = "utm_id";
30
+ var UTM_TERM = "utm_term";
31
+ var STC_MEDIUM_TRANSFORMATIONS = {
32
+ aff: "affiliate",
33
+ dis: "display",
34
+ em: "email",
35
+ met: "paid-metasearch",
36
+ sem: "paid-search",
37
+ rt: "retargeting",
38
+ sm: "social-media",
39
+ sp: "paid-social",
40
+ pn: "push-notification",
41
+ cs: "cross-sites"
42
+ };
43
+ var STC_INVALID_CONTENT = "na";
44
+ var DEFAULT_GA_INIT_EVENT = "sui";
45
+ var EMPTY_STC = {
46
+ medium: null,
47
+ source: null,
48
+ campaign: null
49
+ };
50
+ var loadScript = /*#__PURE__*/ _async_to_generator(function(src) {
51
+ return _ts_generator(this, function(_state) {
52
+ return [
53
+ 2,
54
+ new Promise(function(resolve, reject) {
55
+ var script = document.createElement("script");
56
+ script.src = src;
57
+ script.onload = resolve;
58
+ script.onerror = reject;
59
+ document.head.appendChild(script);
60
+ })
61
+ ];
62
+ });
63
+ });
64
+ export var loadGoogleAnalytics = /*#__PURE__*/ _async_to_generator(function() {
65
+ var googleAnalyticsMeasurementId, dataLayerName, gtagScript;
66
+ return _ts_generator(this, function(_state) {
67
+ googleAnalyticsMeasurementId = getConfig("googleAnalyticsMeasurementId");
68
+ dataLayerName = getConfig("googleAnalyticsDataLayer") || DEFAULT_DATA_LAYER_NAME;
69
+ // Check we have the needed config to load the script
70
+ if (!googleAnalyticsMeasurementId) return [
71
+ 2,
72
+ Promise.resolve(false)
73
+ ];
74
+ gtagScript = "https://www.googletagmanager.com/gtag/js?id=" + googleAnalyticsMeasurementId + "&l=" + dataLayerName;
75
+ // Load it and retrieve the `clientId` from Google
76
+ return [
77
+ 2,
78
+ loadScript(gtagScript)
79
+ ];
80
+ });
81
+ });
82
+ // Trigger GA init event just once per session.
83
+ // Only in LEGACY mode (manual GA4 initialization)
84
+ var triggerGoogleAnalyticsInitEvent = function(sessionId) {
85
+ // Don't trigger if using Segment destination (new mode)
86
+ if (isGA4DestinationEnabled()) return;
87
+ var ref;
88
+ var eventName = (ref = getConfig("googleAnalyticsInitEvent")) != null ? ref : DEFAULT_GA_INIT_EVENT;
89
+ var eventPrefix = "ga_event_" + eventName + "_";
90
+ var eventKey = "" + eventPrefix + sessionId;
91
+ if (typeof window.gtag === "undefined") return;
92
+ // Check if the event has already been sent in this session.
93
+ if (!localStorage.getItem(eventKey)) {
94
+ // If not, send it.
95
+ window.gtag("event", eventName);
96
+ // eslint-disable-next-line no-console
97
+ console.log('Sending GA4 event "' + eventName + '" for the session "' + sessionId + '"');
98
+ // And then save a new GA session hit in local storage.
99
+ localStorage.setItem(eventKey, "true");
100
+ dispatchEvent({
101
+ eventName: EVENTS.GA4_INIT_EVENT_SENT,
102
+ detail: {
103
+ eventName: eventName,
104
+ sessionId: sessionId
105
+ }
106
+ });
107
+ }
108
+ // Clean old GA sessions hits from the storage.
109
+ Object.keys(localStorage).forEach(function(key) {
110
+ if (key.startsWith(eventPrefix) && key !== eventKey) {
111
+ localStorage.removeItem(key);
112
+ }
113
+ });
114
+ };
115
+ var getGoogleField = /*#__PURE__*/ _async_to_generator(function(field) {
116
+ var googleAnalyticsMeasurementId;
117
+ return _ts_generator(this, function(_state) {
118
+ googleAnalyticsMeasurementId = getConfig("googleAnalyticsMeasurementId");
119
+ // If `googleAnalyticsMeasurementId` is not present, don't load anything.
120
+ if (!googleAnalyticsMeasurementId) return [
121
+ 2,
122
+ Promise.resolve()
123
+ ];
124
+ return [
125
+ 2,
126
+ new Promise(function(resolve) {
127
+ // If it is, get it from `gtag`.
128
+ window.gtag == null ? void 0 : window.gtag("get", googleAnalyticsMeasurementId, field, resolve);
129
+ })
130
+ ];
131
+ });
132
+ });
133
+ export var trackingTagsTypes = {
134
+ STC: "stc",
135
+ UTM: "utm"
136
+ };
137
+ export var getCampaignDetails = function(param) {
138
+ var ref = param === void 0 ? {} : param, _needsTransformation = ref.needsTransformation, needsTransformation = _needsTransformation === void 0 ? true : _needsTransformation;
139
+ var ref1 = readQueryParams(), medium = ref1.medium, source = ref1.source, campaign = ref1.campaign, content = ref1.content, term = ref1.term;
140
+ if (!medium || !source || !campaign) return null;
141
+ var ref2 = campaign.split(STC.CAMPAIGN_SPLIT_SYMBOL), id = ref2[0], name = ref2[1];
142
+ if (!id && !name) return null;
143
+ var needsContent = typeof content !== "undefined" && content !== STC_INVALID_CONTENT;
144
+ return {
145
+ campaign: _extends({
146
+ medium: needsTransformation && STC_MEDIUM_TRANSFORMATIONS[medium] || medium
147
+ }, typeof name !== "undefined" && {
148
+ id: id
149
+ }, {
150
+ name: name != null ? name : id,
151
+ source: source
152
+ }, needsContent && {
153
+ content: content
154
+ }, typeof term !== "undefined" && {
155
+ term: term
156
+ })
157
+ };
158
+ };
159
+ function readQueryParams() {
160
+ var search = utils.getActualQueryString();
161
+ var searchParams = new URLSearchParams(search);
162
+ return getConfig("trackingTagsType") === trackingTagsTypes.UTM ? readFromUtm(searchParams) : readFromStc(searchParams);
163
+ }
164
+ function readFromStc(searchParams) {
165
+ if (!hasStc(searchParams)) return EMPTY_STC;
166
+ var stc = searchParams.get(STC.QUERY);
167
+ var ref = stc.split(STC.SPLIT_SYMBOL), medium = ref[0], source = ref[1], campaign = ref[2], content = ref[3], term = ref[4];
168
+ return {
169
+ medium: medium,
170
+ source: source,
171
+ campaign: campaign,
172
+ content: content,
173
+ term: term
174
+ };
175
+ }
176
+ function hasStc(searchParams) {
177
+ return searchParams.has(STC.QUERY);
178
+ }
179
+ function readFromUtm(searchParams) {
180
+ var campaignId = searchParams.get(UTM_CAMPAIGN_ID);
181
+ var campaignName = searchParams.get(UTM_CAMPAIGN);
182
+ var medium = searchParams.get(UTM_MEDIUM);
183
+ var source = searchParams.get(UTM_SOURCE);
184
+ var content = searchParams.get(UTM_CONTENT);
185
+ var term = searchParams.get(UTM_TERM);
186
+ var campaign = campaignId ? "" + campaignId + STC.CAMPAIGN_SPLIT_SYMBOL + campaignName : campaignName;
187
+ // Fallback to STC if any mandatory UTM fields are missing
188
+ var missingAnyMandatoryFields = !medium || !source || !campaign;
189
+ if (missingAnyMandatoryFields && hasStc(searchParams)) {
190
+ return readFromStc(searchParams);
191
+ }
192
+ return {
193
+ campaign: campaign,
194
+ medium: medium,
195
+ source: source,
196
+ content: content,
197
+ term: term
198
+ };
199
+ }
200
+ export var getGoogleClientId = /*#__PURE__*/ _async_to_generator(function() {
201
+ return _ts_generator(this, function(_state) {
202
+ return [
203
+ 2,
204
+ getGoogleField(FIELDS.clientId)
205
+ ];
206
+ });
207
+ });
208
+ export var getGoogleSessionId = /*#__PURE__*/ _async_to_generator(function() {
209
+ var sessionId;
210
+ return _ts_generator(this, function(_state) {
211
+ switch(_state.label){
212
+ case 0:
213
+ return [
214
+ 4,
215
+ getGoogleField(FIELDS.sessionId)
216
+ ];
217
+ case 1:
218
+ sessionId = _state.sent();
219
+ triggerGoogleAnalyticsInitEvent(sessionId);
220
+ return [
221
+ 2,
222
+ sessionId
223
+ ];
224
+ }
225
+ });
226
+ });
227
+ // Unified consent state getter.
228
+ // Returns GRANTED, DENIED or undefined (default / unknown / unavailable).
229
+ export function getGoogleConsentValue(consentType) {
230
+ if (consentType === void 0) consentType = "analytics_storage";
231
+ try {
232
+ var ref, ref1;
233
+ var value = (ref = window.google_tag_data) == null ? void 0 : (ref1 = ref.ics) == null ? void 0 : ref1.getConsentState == null ? void 0 : ref1.getConsentState(consentType);
234
+ if (value === CONSENT_STATE_GRANTED_VALUE) return CONSENT_STATES.granted;
235
+ if (value === CONSENT_STATE_DENIED_VALUE) return CONSENT_STATES.denied;
236
+ return undefined;
237
+ } catch (error) {
238
+ // GTM bug when first rejection happens: keep default undefined instead of forcing DENIED
239
+ return undefined;
240
+ }
241
+ }
242
+ var ref;
243
+ // Backwards compatibility alias (previous getConsentState behavior now unified but default is undefined)
244
+ export var getConsentState = function() {
245
+ return (ref = getGoogleConsentValue()) != null ? ref : CONSENT_STATES.denied;
246
+ };
247
+ export var setGoogleUserId = function(userId) {
248
+ var googleAnalyticsMeasurementId = getConfig("googleAnalyticsMeasurementId");
249
+ if (!googleAnalyticsMeasurementId || !userId) return;
250
+ window.gtag == null ? void 0 : window.gtag("set", "user_id", userId);
251
+ };
252
+ /**
253
+ * Send consents to Google Consent Mode.
254
+ *
255
+ * @param {'default' | 'update'} mode Mode for the consent update
256
+ * @param {object} consents Consents object to be sent to Google Consent Mode.
257
+ * Defaults used when not provided:
258
+ * {
259
+ * analytics_storage: 'denied',
260
+ * ad_user_data: 'denied',
261
+ * ad_personalization: 'denied',
262
+ * ad_storage: 'denied'
263
+ * }
264
+ */ export var sendGoogleConsents = function(mode, consents) {
265
+ if (mode === void 0) mode = "default";
266
+ window.gtag == null ? void 0 : window.gtag("consent", mode, consents || {
267
+ analytics_storage: CONSENT_STATES.denied,
268
+ ad_user_data: CONSENT_STATES.denied,
269
+ ad_personalization: CONSENT_STATES.denied,
270
+ ad_storage: CONSENT_STATES.denied
271
+ });
272
+ };
@@ -0,0 +1,42 @@
1
+ import { readCookie, removeCookie, saveCookie } from "../utils/cookies.js";
2
+ import { isClient, setConfig } from "../config.js";
3
+ import { USER_GDPR } from "../tcf.js";
4
+ var XANDR_ID_SERVER_URL = "https://secure.adnxs.com/getuidj?consent=1";
5
+ var XANDR_ID_COOKIE = "adit-xandr-id";
6
+ var USER_OPTED_OUT_XANDR_ID_VALUE = 0;
7
+ /**
8
+ * [Xandr API Docs]{@link https://docs.xandr.com/bundle/invest_invest-standard/page/topics/user-id-mapping-with-getuid-and-mapuid.html}
9
+ * @returns {String|null} a valid xandrId value
10
+ */ export function getXandrId(param) {
11
+ var gdprPrivacyValueAdvertising = param.gdprPrivacyValueAdvertising;
12
+ if (!isClient) return null;
13
+ if (gdprPrivacyValueAdvertising !== USER_GDPR.ACCEPTED) {
14
+ removeCookie(XANDR_ID_COOKIE);
15
+ return null;
16
+ }
17
+ // 0 is invalid. Negative numbers seems to be invalid too.
18
+ var checkValid = function(xandrId) {
19
+ return xandrId && Number(xandrId) > USER_OPTED_OUT_XANDR_ID_VALUE;
20
+ };
21
+ var storedXandrId = readCookie(XANDR_ID_COOKIE);
22
+ var isValidXandrId = checkValid(storedXandrId);
23
+ if (!isValidXandrId) {
24
+ getRemoteXandrId().then(function(xandrId) {
25
+ if (typeof xandrId === "string") {
26
+ saveCookie(XANDR_ID_COOKIE, xandrId);
27
+ }
28
+ });
29
+ }
30
+ setConfig("xandrId", storedXandrId);
31
+ return isValidXandrId ? storedXandrId : null;
32
+ }
33
+ function getRemoteXandrId() {
34
+ if (!isClient) return Promise.resolve(null);
35
+ return window.fetch(XANDR_ID_SERVER_URL, {
36
+ credentials: "include"
37
+ }).then(function(response) {
38
+ return response.json();
39
+ }).then(function(json) {
40
+ return json == null ? void 0 : json.uid;
41
+ });
42
+ }
@@ -0,0 +1,364 @@
1
+ // @ts-check
2
+ import _async_to_generator from "@swc/helpers/src/_async_to_generator.mjs";
3
+ import _extends from "@swc/helpers/src/_extends.mjs";
4
+ import _to_consumable_array from "@swc/helpers/src/_to_consumable_array.mjs";
5
+ import _ts_generator from "@swc/helpers/src/_ts_generator.mjs";
6
+ import { CONSENT_STATES, getConsentState, getGoogleClientId, getGoogleConsentValue, getGoogleSessionId, sendGoogleConsents, setGoogleUserId } from "./repositories/googleRepository.js";
7
+ import { getXandrId } from "./repositories/xandrRepository.js";
8
+ import { getConfig } from "./config.js";
9
+ import { USER_GDPR, CMP_TRACK_EVENT, checkAnalyticsGdprIsAccepted, getGdprPrivacyValue } from "./tcf.js";
10
+ import { isGA4DestinationEnabled } from "./utils/ga4Detection.js";
11
+ /* Default properties to be sent on all trackings */ var DEFAULT_PROPERTIES = {
12
+ platform: "web"
13
+ };
14
+ /* Disabled integrations when no GDPR Privacy Value is true */ export var INTEGRATIONS_WHEN_NO_CONSENTS = {
15
+ All: false
16
+ };
17
+ export var INTEGRATIONS_WHEN_NO_CONSENTS_CMP_SUBMITTED = {
18
+ All: true
19
+ };
20
+ var getUserId = function(userId) {
21
+ var prefix = getConfig("userIdPrefix");
22
+ if (!prefix) {
23
+ return userId;
24
+ }
25
+ if (typeof userId === "number" || typeof userId === "string" && !userId.startsWith(prefix)) {
26
+ return "" + prefix + userId;
27
+ }
28
+ return userId;
29
+ };
30
+ /**
31
+ * Get default properties using the constant and the window.__mpi object if available
32
+ * @returns {{[key:string]: any}} Default properties to attach to track
33
+ */ export var getDefaultProperties = function() {
34
+ return _extends({}, DEFAULT_PROPERTIES, getConfig("defaultProperties"));
35
+ };
36
+ /**
37
+ * Get all needed integrations depending on the gdprPrivacy value.
38
+ * @param {object} param - Object with the gdprPrivacyValue and if it's a CMP Submitted event
39
+ */ var getTrackIntegrations = /*#__PURE__*/ _async_to_generator(function(param) {
40
+ var gdprPrivacyValue, event, isGdprAccepted, restOfIntegrations, useSegmentGA4Destination, sessionId, clientId, error;
41
+ return _ts_generator(this, function(_state) {
42
+ switch(_state.label){
43
+ case 0:
44
+ gdprPrivacyValue = param.gdprPrivacyValue, event = param.event;
45
+ isGdprAccepted = checkAnalyticsGdprIsAccepted(gdprPrivacyValue);
46
+ restOfIntegrations = getRestOfIntegrations({
47
+ isGdprAccepted: isGdprAccepted,
48
+ event: event
49
+ });
50
+ useSegmentGA4Destination = isGA4DestinationEnabled();
51
+ if (useSegmentGA4Destination) {
52
+ // New behavior: let Segment handle GA4
53
+ return [
54
+ 2,
55
+ _extends({}, restOfIntegrations, {
56
+ "Google Analytics 4 Web": true
57
+ })
58
+ ];
59
+ }
60
+ _state.label = 1;
61
+ case 1:
62
+ _state.trys.push([
63
+ 1,
64
+ 4,
65
+ ,
66
+ 5
67
+ ]);
68
+ return [
69
+ 4,
70
+ getGoogleSessionId()
71
+ ];
72
+ case 2:
73
+ sessionId = _state.sent();
74
+ return [
75
+ 4,
76
+ getGoogleClientId()
77
+ ];
78
+ case 3:
79
+ clientId = _state.sent();
80
+ return [
81
+ 3,
82
+ 5
83
+ ];
84
+ case 4:
85
+ error = _state.sent();
86
+ console.error("[segment-wrapper] Failed to retrieve GA4 session/client IDs. Events will be sent without session attribution.", error);
87
+ return [
88
+ 3,
89
+ 5
90
+ ];
91
+ case 5:
92
+ return [
93
+ 2,
94
+ _extends({}, restOfIntegrations, {
95
+ "Google Analytics 4": clientId && sessionId ? {
96
+ clientId: clientId,
97
+ sessionId: sessionId
98
+ } : true
99
+ })
100
+ ];
101
+ }
102
+ });
103
+ });
104
+ /**
105
+ * Get Rest of integrations depending on the gdprPrivacy value and if it's a CMP Submitted event
106
+ * @param {object} param - Object with the isGdprAccepted and if it's a CMP Submitted event
107
+ * @returns {object} integrations
108
+ */ export var getRestOfIntegrations = function(param) {
109
+ var isGdprAccepted = param.isGdprAccepted, event = param.event;
110
+ var isCMPSubmittedEvent = event === "CMP Submitted";
111
+ if (isCMPSubmittedEvent) {
112
+ return INTEGRATIONS_WHEN_NO_CONSENTS_CMP_SUBMITTED;
113
+ }
114
+ return isGdprAccepted ? {} : INTEGRATIONS_WHEN_NO_CONSENTS;
115
+ };
116
+ /**
117
+ * It returns externalIds to add to context
118
+ *
119
+ * @param {Object} param
120
+ * @param {Object} param.context previous context
121
+ * @param {String} param.xandrId xandrId to be included
122
+ * @returns
123
+ */ var getExternalIds = function(param) {
124
+ var context = param.context, xandrId = param.xandrId;
125
+ var shouldSendXandrId = getConfig("sendXandrId") !== false;
126
+ var isValidXandrId = xandrId && parseInt(xandrId) !== 0;
127
+ if (!shouldSendXandrId || !isValidXandrId) {
128
+ return {};
129
+ }
130
+ var SEGMENT_COLLECTION = "users";
131
+ var SEGMENT_ENCODING = "none";
132
+ var SEGMENT_TYPE = "xandr_id";
133
+ var externalIds = _to_consumable_array((context == null ? void 0 : context.externalIds) || []).concat([
134
+ {
135
+ collection: SEGMENT_COLLECTION,
136
+ encoding: SEGMENT_ENCODING,
137
+ id: xandrId,
138
+ type: SEGMENT_TYPE
139
+ }
140
+ ]);
141
+ var uniqueExternalIds = externalIds.filter(function(param, index) {
142
+ var idFilter = param.id, typeFilter = param.type;
143
+ return index === externalIds.findIndex(function(param) {
144
+ var idFind = param.id, typeFind = param.type;
145
+ return idFilter === idFind && typeFilter === typeFind;
146
+ });
147
+ });
148
+ return {
149
+ externalIds: uniqueExternalIds
150
+ };
151
+ };
152
+ /**
153
+ * Get consent value for Google Consent Mode
154
+ * @param {string} gdprValue
155
+ * @returns {string} consent value
156
+ */ var getConsentValue = function(gdprValue) {
157
+ return gdprValue === USER_GDPR.ACCEPTED ? CONSENT_STATES.granted : CONSENT_STATES.denied;
158
+ };
159
+ /**
160
+ * Get data like traits and integrations to be added to the context object
161
+ * @param {object} context Context object with all the actual info
162
+ * @returns {Promise<object>} New context with all the previous info and the new one
163
+ */ export var decorateContextWithNeededData = /*#__PURE__*/ _async_to_generator(function(param) {
164
+ var _event, event, _context, context, _properties, properties, gdprPrivacyValue, ref, gdprPrivacyValueAnalytics, gdprPrivacyValueAdvertising, isGdprAccepted, useSegmentGA4Destination, ref1, integrations, xandrId, _integrations, contextIntegrations, ref2, ref3, ref4, ref5, googleConsents, _VERSION, baseContext;
165
+ return _ts_generator(this, function(_state) {
166
+ switch(_state.label){
167
+ case 0:
168
+ _event = param.event, event = _event === void 0 ? "" : _event, _context = param.context, context = _context === void 0 ? {} : _context, _properties = param.properties, properties = _properties === void 0 ? {} : _properties;
169
+ return [
170
+ 4,
171
+ getGdprPrivacyValue()
172
+ ];
173
+ case 1:
174
+ gdprPrivacyValue = _state.sent();
175
+ ref = gdprPrivacyValue || {}, gdprPrivacyValueAnalytics = ref.analytics, gdprPrivacyValueAdvertising = ref.advertising;
176
+ isGdprAccepted = checkAnalyticsGdprIsAccepted(gdprPrivacyValue);
177
+ useSegmentGA4Destination = isGA4DestinationEnabled();
178
+ return [
179
+ 4,
180
+ Promise.all([
181
+ getTrackIntegrations({
182
+ gdprPrivacyValue: gdprPrivacyValue,
183
+ event: event
184
+ }),
185
+ getXandrId({
186
+ gdprPrivacyValueAdvertising: gdprPrivacyValueAdvertising
187
+ })
188
+ ])
189
+ ];
190
+ case 2:
191
+ ref1 = _state.sent(), integrations = ref1[0], xandrId = ref1[1];
192
+ contextIntegrations = !isGdprAccepted ? _extends({}, (_integrations = context.integrations) != null ? _integrations : {}, {
193
+ Personas: false,
194
+ Webhooks: true,
195
+ Webhook: true
196
+ }) : context.integrations;
197
+ googleConsents = {
198
+ analytics_storage: useSegmentGA4Destination ? getConsentValue(gdprPrivacyValueAnalytics) : (ref2 = getGoogleConsentValue("analytics_storage")) != null ? ref2 : getConsentValue(gdprPrivacyValueAnalytics),
199
+ ad_storage: useSegmentGA4Destination ? getConsentValue(gdprPrivacyValueAdvertising) : (ref3 = getGoogleConsentValue("ad_storage")) != null ? ref3 : getConsentValue(gdprPrivacyValueAdvertising),
200
+ ad_user_data: useSegmentGA4Destination ? getConsentValue(gdprPrivacyValueAdvertising) : (ref4 = getGoogleConsentValue("ad_user_data")) != null ? ref4 : getConsentValue(gdprPrivacyValueAdvertising),
201
+ ad_personalization: useSegmentGA4Destination ? getConsentValue(gdprPrivacyValueAdvertising) : (ref5 = getGoogleConsentValue("ad_personalization")) != null ? ref5 : getConsentValue(gdprPrivacyValueAdvertising)
202
+ };
203
+ baseContext = _extends({}, context, !isGdprAccepted && {
204
+ ip: "0.0.0.0"
205
+ }, getExternalIds({
206
+ context: context,
207
+ xandrId: xandrId
208
+ }), {
209
+ clientVersion: "segment-wrapper@" + ((_VERSION = "5.4.0") != null ? _VERSION : "0.0.0"),
210
+ gdpr_privacy: gdprPrivacyValueAnalytics,
211
+ gdpr_privacy_advertising: gdprPrivacyValueAdvertising,
212
+ integrations: _extends({}, contextIntegrations, integrations)
213
+ });
214
+ // Legacy behavior: add analytics_storage and google_consents to context
215
+ if (!useSegmentGA4Destination) {
216
+ baseContext.analytics_storage = getConsentState();
217
+ baseContext.google_consents = googleConsents;
218
+ }
219
+ return [
220
+ 2,
221
+ {
222
+ context: baseContext,
223
+ properties: useSegmentGA4Destination ? _extends({}, properties, {
224
+ // New mode: add google_consents to properties
225
+ google_consents: googleConsents
226
+ }) : properties
227
+ }
228
+ ];
229
+ }
230
+ });
231
+ });
232
+ /**
233
+ * The track method lets you record any actions your users perform.
234
+ * @param {string} event The name of the event you’re tracking
235
+ * @param {object} [properties] A dictionary of properties for the event.
236
+ * @param {object} [context] A dictionary of options.
237
+ * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
238
+ * @returns {Promise}
239
+ */ var track = function(event, properties, context, callback) {
240
+ if (context === void 0) context = {};
241
+ return new Promise(function(resolve) {
242
+ var initTrack = /*#__PURE__*/ _async_to_generator(function() {
243
+ var baseProperties, ref, newContext, decoratedProperties, newCallback, useSegmentGA4Destination, needsConsentManagement;
244
+ return _ts_generator(this, function(_state) {
245
+ switch(_state.label){
246
+ case 0:
247
+ baseProperties = _extends({}, getDefaultProperties(), properties);
248
+ return [
249
+ 4,
250
+ decorateContextWithNeededData({
251
+ context: context,
252
+ event: event,
253
+ properties: baseProperties
254
+ })
255
+ ];
256
+ case 1:
257
+ ref = _state.sent(), newContext = ref.context, decoratedProperties = ref.properties;
258
+ newCallback = /*#__PURE__*/ _async_to_generator(function() {
259
+ var _len, args, _key, ref, gdprPrivacyValue;
260
+ var _arguments = arguments;
261
+ return _ts_generator(this, function(_state) {
262
+ switch(_state.label){
263
+ case 0:
264
+ for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
265
+ args[_key] = _arguments[_key];
266
+ }
267
+ if (callback) callback.apply(void 0, args) // eslint-disable-line n/no-callback-literal
268
+ ;
269
+ return [
270
+ 4,
271
+ Promise.all([
272
+ getGdprPrivacyValue()
273
+ ])
274
+ ];
275
+ case 1:
276
+ ref = _state.sent(), gdprPrivacyValue = ref[0];
277
+ if (checkAnalyticsGdprIsAccepted(gdprPrivacyValue)) {
278
+ resolve.apply(void 0, args);
279
+ } else {
280
+ resolve();
281
+ }
282
+ return [
283
+ 2
284
+ ];
285
+ }
286
+ });
287
+ });
288
+ useSegmentGA4Destination = isGA4DestinationEnabled();
289
+ needsConsentManagement = getConfig("googleAnalyticsConsentManagement");
290
+ // Legacy behavior: send consents to GTM
291
+ if (!useSegmentGA4Destination && needsConsentManagement && event === CMP_TRACK_EVENT) {
292
+ sendGoogleConsents("update", newContext.google_consents);
293
+ }
294
+ window.analytics.track(event, decoratedProperties, _extends({}, newContext, {
295
+ context: {
296
+ integrations: _extends({}, newContext.integrations)
297
+ }
298
+ }), newCallback);
299
+ return [
300
+ 2
301
+ ];
302
+ }
303
+ });
304
+ });
305
+ initTrack();
306
+ });
307
+ };
308
+ /**
309
+ * Associate your users and their actions to a recognizable userId and traits.
310
+ * @param {string} userIdParam Id to identify the user.
311
+ * @param {object} traits A dictionary of traits you know about the user, like their email or name.
312
+ * @param {object} [options] A dictionary of options.
313
+ * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
314
+ * @returns {Promise}
315
+ */ var identify = /*#__PURE__*/ _async_to_generator(function(userIdParam, traits, options, callback) {
316
+ var gdprPrivacyValue, userId;
317
+ return _ts_generator(this, function(_state) {
318
+ switch(_state.label){
319
+ case 0:
320
+ return [
321
+ 4,
322
+ getGdprPrivacyValue()
323
+ ];
324
+ case 1:
325
+ gdprPrivacyValue = _state.sent();
326
+ userId = getUserId(userIdParam);
327
+ // Legacy behavior: set user ID in gtag
328
+ if (!isGA4DestinationEnabled()) {
329
+ setGoogleUserId(userId);
330
+ }
331
+ return [
332
+ 2,
333
+ window.analytics.identify(userId, checkAnalyticsGdprIsAccepted(gdprPrivacyValue) ? traits : {}, options, callback)
334
+ ];
335
+ }
336
+ });
337
+ });
338
+ /**
339
+ * Record whenever a user sees a page of your website, along with any optional properties about the page.
340
+ * @param {string} event The name of the event you’re tracking
341
+ * @param {object=} properties A dictionary of properties for the event.
342
+ * @param {object} [context] A dictionary of options.
343
+ * @param {function} [callback] A function executed after a short timeout, giving the browser time to make outbound requests first.
344
+ * @returns {Promise}
345
+ */ var page = function(event, properties, context, callback) {
346
+ if (context === void 0) context = {};
347
+ // we put a flag on context to know this track is a page
348
+ context.isPageTrack = true;
349
+ // just call track again but the with the proper context
350
+ return track(event, properties, context, callback);
351
+ };
352
+ /**
353
+ * Resets the id, including anonymousId, and clear traits for the currently identified user and group.
354
+ * NOTE: Only clears the cookies and localStorage set by analytics.
355
+ * @returns {Promise}
356
+ */ var reset = function() {
357
+ return Promise.resolve(window.analytics.reset());
358
+ };
359
+ export default {
360
+ page: page,
361
+ identify: identify,
362
+ track: track,
363
+ reset: reset
364
+ };