@metamask-previews/analytics-controller 2.1.0-preview-abca9bcea → 3.0.0-preview-0a30e47

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 (97) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/{AnalyticsController-method-action-types.d.mts → AnalyticsController-method-action-types.d.ts} +2 -2
  3. package/dist/AnalyticsController-method-action-types.d.ts.map +1 -0
  4. package/dist/{AnalyticsController-method-action-types.mjs → AnalyticsController-method-action-types.js} +1 -1
  5. package/dist/AnalyticsController-method-action-types.js.map +1 -0
  6. package/dist/{AnalyticsController.d.cts → AnalyticsController.d.ts} +9 -9
  7. package/dist/AnalyticsController.d.ts.map +1 -0
  8. package/dist/AnalyticsController.js +1193 -0
  9. package/dist/AnalyticsController.js.map +1 -0
  10. package/dist/AnalyticsLogger.d.ts +4 -0
  11. package/dist/AnalyticsLogger.d.ts.map +1 -0
  12. package/dist/{AnalyticsLogger.mjs → AnalyticsLogger.js} +2 -2
  13. package/dist/AnalyticsLogger.js.map +1 -0
  14. package/dist/{AnalyticsPlatformAdapter.types.d.mts → AnalyticsPlatformAdapter.types.d.ts} +2 -2
  15. package/dist/AnalyticsPlatformAdapter.types.d.ts.map +1 -0
  16. package/dist/AnalyticsPlatformAdapter.types.js +2 -0
  17. package/dist/AnalyticsPlatformAdapter.types.js.map +1 -0
  18. package/dist/{AnalyticsPlatformAdapterSetupError.d.cts → AnalyticsPlatformAdapterSetupError.d.ts} +1 -1
  19. package/dist/AnalyticsPlatformAdapterSetupError.d.ts.map +1 -0
  20. package/dist/{AnalyticsPlatformAdapterSetupError.mjs → AnalyticsPlatformAdapterSetupError.js} +2 -1
  21. package/dist/AnalyticsPlatformAdapterSetupError.js.map +1 -0
  22. package/dist/{EventFragment.types.d.cts → EventFragment.types.d.ts} +2 -2
  23. package/dist/EventFragment.types.d.ts.map +1 -0
  24. package/dist/EventFragment.types.js +2 -0
  25. package/dist/EventFragment.types.js.map +1 -0
  26. package/dist/{analyticsControllerStateValidator.d.mts → analyticsControllerStateValidator.d.ts} +2 -2
  27. package/dist/analyticsControllerStateValidator.d.ts.map +1 -0
  28. package/dist/{analyticsControllerStateValidator.mjs → analyticsControllerStateValidator.js} +1 -1
  29. package/dist/analyticsControllerStateValidator.js.map +1 -0
  30. package/dist/{index.d.cts → index.d.ts} +11 -11
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +7 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/{selectors.cjs → selectors.d.ts} +17 -18
  35. package/dist/selectors.d.ts.map +1 -0
  36. package/dist/{selectors.mjs → selectors.js} +1 -1
  37. package/dist/selectors.js.map +1 -0
  38. package/package.json +18 -22
  39. package/dist/AnalyticsController-method-action-types.cjs +0 -7
  40. package/dist/AnalyticsController-method-action-types.cjs.map +0 -1
  41. package/dist/AnalyticsController-method-action-types.d.cts +0 -185
  42. package/dist/AnalyticsController-method-action-types.d.cts.map +0 -1
  43. package/dist/AnalyticsController-method-action-types.d.mts.map +0 -1
  44. package/dist/AnalyticsController-method-action-types.mjs.map +0 -1
  45. package/dist/AnalyticsController.cjs +0 -991
  46. package/dist/AnalyticsController.cjs.map +0 -1
  47. package/dist/AnalyticsController.d.cts.map +0 -1
  48. package/dist/AnalyticsController.d.mts +0 -431
  49. package/dist/AnalyticsController.d.mts.map +0 -1
  50. package/dist/AnalyticsController.mjs +0 -987
  51. package/dist/AnalyticsController.mjs.map +0 -1
  52. package/dist/AnalyticsLogger.cjs +0 -8
  53. package/dist/AnalyticsLogger.cjs.map +0 -1
  54. package/dist/AnalyticsLogger.d.cts +0 -5
  55. package/dist/AnalyticsLogger.d.cts.map +0 -1
  56. package/dist/AnalyticsLogger.d.mts +0 -5
  57. package/dist/AnalyticsLogger.d.mts.map +0 -1
  58. package/dist/AnalyticsLogger.mjs.map +0 -1
  59. package/dist/AnalyticsPlatformAdapter.types.cjs +0 -3
  60. package/dist/AnalyticsPlatformAdapter.types.cjs.map +0 -1
  61. package/dist/AnalyticsPlatformAdapter.types.d.cts +0 -144
  62. package/dist/AnalyticsPlatformAdapter.types.d.cts.map +0 -1
  63. package/dist/AnalyticsPlatformAdapter.types.d.mts.map +0 -1
  64. package/dist/AnalyticsPlatformAdapter.types.mjs +0 -2
  65. package/dist/AnalyticsPlatformAdapter.types.mjs.map +0 -1
  66. package/dist/AnalyticsPlatformAdapterSetupError.cjs +0 -17
  67. package/dist/AnalyticsPlatformAdapterSetupError.cjs.map +0 -1
  68. package/dist/AnalyticsPlatformAdapterSetupError.d.cts.map +0 -1
  69. package/dist/AnalyticsPlatformAdapterSetupError.d.mts +0 -8
  70. package/dist/AnalyticsPlatformAdapterSetupError.d.mts.map +0 -1
  71. package/dist/AnalyticsPlatformAdapterSetupError.mjs.map +0 -1
  72. package/dist/EventFragment.types.cjs +0 -3
  73. package/dist/EventFragment.types.cjs.map +0 -1
  74. package/dist/EventFragment.types.d.cts.map +0 -1
  75. package/dist/EventFragment.types.d.mts +0 -111
  76. package/dist/EventFragment.types.d.mts.map +0 -1
  77. package/dist/EventFragment.types.mjs +0 -2
  78. package/dist/EventFragment.types.mjs.map +0 -1
  79. package/dist/analyticsControllerStateValidator.cjs +0 -36
  80. package/dist/analyticsControllerStateValidator.cjs.map +0 -1
  81. package/dist/analyticsControllerStateValidator.d.cts +0 -17
  82. package/dist/analyticsControllerStateValidator.d.cts.map +0 -1
  83. package/dist/analyticsControllerStateValidator.d.mts.map +0 -1
  84. package/dist/analyticsControllerStateValidator.mjs.map +0 -1
  85. package/dist/index.cjs +0 -15
  86. package/dist/index.cjs.map +0 -1
  87. package/dist/index.d.cts.map +0 -1
  88. package/dist/index.d.mts +0 -11
  89. package/dist/index.d.mts.map +0 -1
  90. package/dist/index.mjs +0 -7
  91. package/dist/index.mjs.map +0 -1
  92. package/dist/selectors.cjs.map +0 -1
  93. package/dist/selectors.d.cts +0 -15
  94. package/dist/selectors.d.cts.map +0 -1
  95. package/dist/selectors.d.mts +0 -15
  96. package/dist/selectors.d.mts.map +0 -1
  97. package/dist/selectors.mjs.map +0 -1
@@ -1,987 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _AnalyticsController_instances, _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_isEventQueuePersistenceEnabled, _AnalyticsController_isPreConsentQueueEnabled, _AnalyticsController_isGeolocationEnabled, _AnalyticsController_isEventFragmentsEnabled, _AnalyticsController_initPromise, _AnalyticsController_locationResolvePromise, _AnalyticsController_locationContext, _AnalyticsController_performInit, _AnalyticsController_maybeResolveLocation, _AnalyticsController_resolveLocationContext, _AnalyticsController_withLocationContext, _AnalyticsController_sendOrQueueTrackEvent, _AnalyticsController_sendOrQueueIdentifyEvent, _AnalyticsController_sendOrQueueViewEvent, _AnalyticsController_enqueueEvent, _AnalyticsController_sendQueuedEvent, _AnalyticsController_replayQueuedEvents, _AnalyticsController_removeQueuedEvent, _AnalyticsController_clearQueuedEvents, _AnalyticsController_enqueuePreConsentEvent, _AnalyticsController_replayPreConsentEvents, _AnalyticsController_enrichPreConsentEvent, _AnalyticsController_clearPreConsentEvents, _AnalyticsController_reconcilePreConsentEvents, _AnalyticsController_reconcileEventFragments, _AnalyticsController_purgeStaleEventFragments, _AnalyticsController_getEventFragment, _AnalyticsController_setEventFragment, _AnalyticsController_removeEventFragment, _AnalyticsController_clearEventFragments, _AnalyticsController_shouldIgnoreEventFragmentCall, _AnalyticsController_emitEventFragment, _AnalyticsController_isAnalyticsCaptureAllowed;
13
- import { BaseController } from "@metamask/base-controller";
14
- import $lodash from "lodash";
15
- const { cloneDeep } = $lodash;
16
- import { v4 as uuid } from "uuid";
17
- import { validateAnalyticsControllerState } from "./analyticsControllerStateValidator.mjs";
18
- import { projectLogger as log } from "./AnalyticsLogger.mjs";
19
- import { analyticsControllerSelectors } from "./selectors.mjs";
20
- // === GENERAL ===
21
- /**
22
- * The name of the {@link AnalyticsController}, used to namespace the
23
- * controller's actions and events and to namespace the controller's state data
24
- * when composed with other controllers.
25
- */
26
- export const controllerName = 'AnalyticsController';
27
- /**
28
- * Maximum age of a persisted event fragment, measured from
29
- * {@link AnalyticsEventFragment.lastUpdated}.
30
- *
31
- * Fragments older than this are discarded during {@link AnalyticsController.init}
32
- * without emitting a success or failure event. Confirmation journeys that span a
33
- * restart are expected to resume within this window; abandoned ones must not keep
34
- * `properties` or `sensitiveProperties` in storage indefinitely.
35
- */
36
- export const EVENT_FRAGMENT_MAX_AGE = 24 * 60 * 60 * 1000;
37
- /**
38
- * Returns default values for AnalyticsController state.
39
- *
40
- * Note: analyticsId is NOT included - it's an identity that must be
41
- * provided by the platform (generated once on first run, then persisted).
42
- *
43
- * @returns Default state without analyticsId
44
- */
45
- export function getDefaultAnalyticsControllerState() {
46
- return {
47
- optedIn: false,
48
- consentDecisionMade: false,
49
- };
50
- }
51
- /**
52
- * The metadata for each property in {@link AnalyticsControllerState}.
53
- *
54
- * Both `optedIn` and `analyticsId` are persisted (`persist: true`).
55
- * The platform must supply a valid UUIDv4 `analyticsId` on first run.
56
- */
57
- const analyticsControllerMetadata = {
58
- optedIn: {
59
- includeInStateLogs: true,
60
- persist: true,
61
- includeInDebugSnapshot: true,
62
- usedInUi: true,
63
- },
64
- analyticsId: {
65
- includeInStateLogs: true,
66
- persist: true,
67
- includeInDebugSnapshot: true,
68
- usedInUi: false,
69
- },
70
- eventQueue: {
71
- includeInStateLogs: false,
72
- persist: true,
73
- includeInDebugSnapshot: false,
74
- usedInUi: false,
75
- },
76
- consentDecisionMade: {
77
- includeInStateLogs: true,
78
- persist: true,
79
- includeInDebugSnapshot: true,
80
- usedInUi: true,
81
- },
82
- preConsentEventQueue: {
83
- includeInStateLogs: false,
84
- persist: true,
85
- includeInDebugSnapshot: false,
86
- usedInUi: false,
87
- },
88
- eventFragments: {
89
- includeInStateLogs: false,
90
- persist: true,
91
- includeInDebugSnapshot: false,
92
- usedInUi: false,
93
- },
94
- };
95
- // === MESSENGER ===
96
- const MESSENGER_EXPOSED_METHODS = [
97
- 'trackEvent',
98
- 'identify',
99
- 'trackView',
100
- 'optIn',
101
- 'optOut',
102
- 'resetConsentDecision',
103
- 'createEventFragment',
104
- 'upsertEventFragment',
105
- 'updateEventFragment',
106
- 'getEventFragmentById',
107
- 'deleteEventFragment',
108
- 'finalizeEventFragment',
109
- ];
110
- /**
111
- * Returns whether a value is a non-array object.
112
- *
113
- * @param value - The value to check.
114
- * @returns True if the value is a record.
115
- */
116
- function isRecord(value) {
117
- return value !== null && typeof value === 'object' && !Array.isArray(value);
118
- }
119
- /**
120
- * Returns whether a JSON value is a non-array object.
121
- *
122
- * @param value - The value to check.
123
- * @returns True if the value is a JSON record.
124
- */
125
- function isJsonRecord(value) {
126
- return value !== null && typeof value === 'object' && !Array.isArray(value);
127
- }
128
- /**
129
- * Builds the analytics location context from geolocation data, keeping only
130
- * the fields the geolocation API was able to determine.
131
- *
132
- * @param geolocation - The geolocation data to convert.
133
- * @returns The location context, or `undefined` when no field is known.
134
- */
135
- function buildLocationContext(geolocation) {
136
- const locationContext = {
137
- ...(geolocation.country === null
138
- ? {}
139
- : { country_code: geolocation.country }),
140
- ...(geolocation.region === null ? {} : { region: geolocation.region }),
141
- ...(geolocation.timezone === null
142
- ? {}
143
- : { timezone: geolocation.timezone }),
144
- };
145
- return Object.keys(locationContext).length === 0
146
- ? undefined
147
- : locationContext;
148
- }
149
- /**
150
- * Returns whether a value is a valid persisted analytics event.
151
- *
152
- * @param value - The value to check.
153
- * @returns True if the value is a queued analytics event.
154
- */
155
- function isAnalyticsQueuedEvent(value) {
156
- if (!isRecord(value)) {
157
- return false;
158
- }
159
- if (typeof value.messageId !== 'string' ||
160
- typeof value.timestamp !== 'string') {
161
- return false;
162
- }
163
- if (value.type === 'track') {
164
- return (typeof value.eventName === 'string' &&
165
- (value.properties === undefined || isRecord(value.properties)) &&
166
- (value.context === undefined || isRecord(value.context)));
167
- }
168
- if (value.type === 'identify') {
169
- return (typeof value.userId === 'string' &&
170
- (value.traits === undefined || isRecord(value.traits)) &&
171
- (value.context === undefined || isRecord(value.context)));
172
- }
173
- if (value.type === 'view') {
174
- return (typeof value.name === 'string' &&
175
- (value.properties === undefined || isRecord(value.properties)) &&
176
- (value.context === undefined || isRecord(value.context)));
177
- }
178
- return false;
179
- }
180
- /**
181
- * Returns whether a value is a valid persisted event fragment.
182
- *
183
- * @param value - The value to check.
184
- * @returns True if the value is an event fragment.
185
- */
186
- function isAnalyticsEventFragment(value) {
187
- if (!isRecord(value)) {
188
- return false;
189
- }
190
- return (typeof value.id === 'string' &&
191
- typeof value.createdAt === 'number' &&
192
- typeof value.lastUpdated === 'number' &&
193
- isRecord(value.properties) &&
194
- isRecord(value.sensitiveProperties) &&
195
- (value.initialEvent === undefined ||
196
- typeof value.initialEvent === 'string') &&
197
- (value.successEvent === undefined ||
198
- typeof value.successEvent === 'string') &&
199
- (value.failureEvent === undefined ||
200
- typeof value.failureEvent === 'string') &&
201
- (value.context === undefined || isRecord(value.context)) &&
202
- (value.persist === undefined || typeof value.persist === 'boolean'));
203
- }
204
- /**
205
- * Merges a payload into an event fragment.
206
- *
207
- * `properties`, `sensitiveProperties` and `context` are merged one level deep,
208
- * so a key written twice is replaced rather than combined. This keeps array
209
- * values predictable: writing a shorter array replaces the longer one instead
210
- * of leaving stale trailing entries behind.
211
- *
212
- * @param fragment - The fragment to merge into.
213
- * @param payload - The payload to merge.
214
- * @returns A new fragment with the payload applied.
215
- */
216
- function mergeEventFragment(fragment, payload) {
217
- const context = mergeEventFragmentContext(fragment.context, payload.context);
218
- return {
219
- ...fragment,
220
- properties: { ...fragment.properties, ...(payload.properties ?? {}) },
221
- sensitiveProperties: {
222
- ...fragment.sensitiveProperties,
223
- ...(payload.sensitiveProperties ?? {}),
224
- },
225
- ...(context === undefined ? {} : { context }),
226
- lastUpdated: Date.now(),
227
- };
228
- }
229
- /**
230
- * Merges two optional analytics contexts, preserving `undefined` when neither
231
- * side has one so an empty context is never sent.
232
- *
233
- * @param base - The context to merge into.
234
- * @param override - The context whose fields win.
235
- * @returns The merged context, or `undefined` when both sides are unset.
236
- */
237
- function mergeEventFragmentContext(base, override) {
238
- if (base === undefined && override === undefined) {
239
- return undefined;
240
- }
241
- return { ...(base ?? {}), ...(override ?? {}) };
242
- }
243
- /**
244
- * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).
245
- * It provides a unified interface for tracking events, identifying users, and managing
246
- * analytics preferences while delegating platform-specific implementation to an
247
- * {@link AnalyticsPlatformAdapter}.
248
- *
249
- * This controller follows the MetaMask controller pattern and integrates with the
250
- * messenger system to allow other controllers and components to track analytics events.
251
- * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.
252
- *
253
- * The controller persists `optedIn` and `analyticsId` when composed with a persisted
254
- * store. The platform must supply a valid `analyticsId` on first launch.
255
- */
256
- export class AnalyticsController extends BaseController {
257
- /**
258
- * Constructs an AnalyticsController instance.
259
- *
260
- * @param options - Controller options
261
- * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.
262
- * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.
263
- * @param options.messenger - Messenger used to communicate with BaseController
264
- * @param options.platformAdapter - Platform adapter implementation for tracking
265
- * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
266
- * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
267
- * @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled
268
- * @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled
269
- * @param options.isEventFragmentsEnabled - Whether the event fragments feature is enabled
270
- * @throws Error if state.analyticsId is missing or not a valid UUIDv4
271
- * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
272
- */
273
- constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, isPreConsentQueueEnabled = false, isGeolocationEnabled = false, isEventFragmentsEnabled = false, }) {
274
- const initialState = {
275
- ...getDefaultAnalyticsControllerState(),
276
- ...state,
277
- };
278
- validateAnalyticsControllerState(initialState, platformAdapter.skipUUIDv4Check === true);
279
- super({
280
- name: controllerName,
281
- metadata: analyticsControllerMetadata,
282
- state: initialState,
283
- messenger,
284
- });
285
- _AnalyticsController_instances.add(this);
286
- _AnalyticsController_platformAdapter.set(this, void 0);
287
- _AnalyticsController_isAnonymousEventsFeatureEnabled.set(this, void 0);
288
- _AnalyticsController_isEventQueuePersistenceEnabled.set(this, void 0);
289
- _AnalyticsController_isPreConsentQueueEnabled.set(this, void 0);
290
- _AnalyticsController_isGeolocationEnabled.set(this, void 0);
291
- _AnalyticsController_isEventFragmentsEnabled.set(this, void 0);
292
- /**
293
- * The in-flight (or settled) initialization promise. Set on the first
294
- * {@link init} call and returned by subsequent calls so overlapping callers
295
- * await the same work rather than observing a premature completion.
296
- */
297
- _AnalyticsController_initPromise.set(this, void 0);
298
- /**
299
- * The in-flight (or settled) geolocation resolution, if any. Its presence
300
- * marks that resolution has been started, so it runs at most once.
301
- */
302
- _AnalyticsController_locationResolvePromise.set(this, void 0);
303
- _AnalyticsController_locationContext.set(this, void 0);
304
- __classPrivateFieldSet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, isAnonymousEventsFeatureEnabled, "f");
305
- __classPrivateFieldSet(this, _AnalyticsController_isEventQueuePersistenceEnabled, isEventQueuePersistenceEnabled, "f");
306
- __classPrivateFieldSet(this, _AnalyticsController_isPreConsentQueueEnabled, isPreConsentQueueEnabled, "f");
307
- __classPrivateFieldSet(this, _AnalyticsController_isGeolocationEnabled, isGeolocationEnabled, "f");
308
- __classPrivateFieldSet(this, _AnalyticsController_isEventFragmentsEnabled, isEventFragmentsEnabled, "f");
309
- __classPrivateFieldSet(this, _AnalyticsController_platformAdapter, platformAdapter, "f");
310
- __classPrivateFieldSet(this, _AnalyticsController_initPromise, undefined, "f");
311
- __classPrivateFieldSet(this, _AnalyticsController_locationResolvePromise, undefined, "f");
312
- this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
313
- log('AnalyticsController initialized and ready', {
314
- enabled: analyticsControllerSelectors.selectEnabled(this.state),
315
- optedIn: this.state.optedIn,
316
- consentDecisionMade: this.state.consentDecisionMade,
317
- analyticsId: this.state.analyticsId,
318
- eventQueuePersistenceEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f"),
319
- preConsentQueueEnabled: __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f"),
320
- geolocationEnabled: __classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f"),
321
- eventFragmentsEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f"),
322
- });
323
- }
324
- /**
325
- * Initialize the controller by calling the platform adapter's
326
- * onSetupCompleted lifecycle hook and replaying any queued events. This
327
- * method must be called after construction to complete the setup process.
328
- *
329
- * When geolocation enrichment is enabled (`isGeolocationEnabled`), geolocation
330
- * is resolved only for a user who is already opted in; for undecided or
331
- * opted-out users it is deferred until they opt in (see {@link optIn}), so a
332
- * user's location is never requested before they consent to analytics. In
333
- * either case the `GeolocationController` and its
334
- * `GeolocationController:getGeolocationData` action must be registered before
335
- * resolution occurs, or enrichment is skipped for the session (a message is
336
- * logged, see {@link #resolveLocationContext}).
337
- *
338
- * Safe to call more than once: the first call performs initialization and
339
- * subsequent calls return the same in-flight (or settled) promise.
340
- *
341
- * @returns A promise that resolves once initialization has completed.
342
- */
343
- init() {
344
- // Cache the in-flight promise so repeated or overlapping calls share a
345
- // single initialization and all await the same completion (rather than an
346
- // early call observing a finished init while work is still pending).
347
- __classPrivateFieldSet(this, _AnalyticsController_initPromise, __classPrivateFieldGet(this, _AnalyticsController_initPromise, "f") ?? __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_performInit).call(this), "f");
348
- return __classPrivateFieldGet(this, _AnalyticsController_initPromise, "f");
349
- }
350
- /**
351
- * Track an analytics event.
352
- *
353
- * Events are only tracked if analytics is enabled.
354
- *
355
- * @param event - Analytics event with properties and sensitive properties
356
- * @param context - Optional platform-specific context forwarded to the platform adapter.
357
- */
358
- trackEvent(event, context) {
359
- // An event captured while the user is still undecided is held in the
360
- // pre-consent queue (see #sendOrQueueTrackEvent) instead of being
361
- // delivered, and replayed if they later opt in.
362
- if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
363
- return;
364
- }
365
- // if event does not have properties, send event without properties
366
- // and return to prevent any additional processing
367
- if (!event.hasProperties) {
368
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, undefined, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
369
- return;
370
- }
371
- // Track regular properties first if anonymous events feature is enabled
372
- if (__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f")) {
373
- // Note: Even if regular properties object is empty, we still send it to ensure
374
- // an event with user ID is tracked.
375
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
376
- ...event.properties,
377
- }, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
378
- }
379
- const hasSensitiveProperties = Object.keys(event.sensitiveProperties).length > 0;
380
- if (!__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f") || hasSensitiveProperties) {
381
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
382
- ...event.properties,
383
- ...event.sensitiveProperties,
384
- ...(hasSensitiveProperties && { anonymous: true }),
385
- },
386
- // When the anonymous events feature is enabled, this payload is the
387
- // anonymous one and must carry no geolocation. When the feature is
388
- // disabled, this is the single identified payload, so it is enriched.
389
- __classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f")
390
- ? context
391
- : __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
392
- }
393
- }
394
- /**
395
- * Identify a user for analytics.
396
- *
397
- * @param traits - User traits/properties
398
- * @param context - Optional platform-specific context forwarded to the platform adapter.
399
- */
400
- identify(traits, context) {
401
- if (!analyticsControllerSelectors.selectEnabled(this.state)) {
402
- return;
403
- }
404
- // Delegate to platform adapter using the current analytics ID
405
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueIdentifyEvent).call(this, this.state.analyticsId, traits, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
406
- }
407
- /**
408
- * Track a page or screen view.
409
- *
410
- * @param name - The identifier/name of the page or screen being viewed (e.g., "home", "settings", "wallet")
411
- * @param properties - Optional properties associated with the view
412
- * @param context - Optional platform-specific context forwarded to the platform adapter.
413
- */
414
- trackView(name, properties, context) {
415
- if (!analyticsControllerSelectors.selectEnabled(this.state)) {
416
- return;
417
- }
418
- // Delegate to platform adapter
419
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueViewEvent).call(this, name, properties, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
420
- }
421
- /**
422
- * Create an event fragment.
423
- *
424
- * A fragment accumulates properties across a user journey so that several
425
- * parts of a client can contribute to the same set of events without
426
- * re-deriving them. Declaring `successEvent` and `failureEvent` turns the
427
- * fragment into a funnel that {@link finalizeEventFragment} closes. Declaring
428
- * none of the event names makes it a pure property bag that the client reads
429
- * back with {@link getEventFragmentById} when it emits its own events.
430
- *
431
- * Any existing fragment with the same ID is replaced, so a new journey never
432
- * inherits properties from a stale one.
433
- *
434
- * Nothing is created unless the user is opted in, or undecided with the
435
- * pre-consent queue enabled, so an opted-out user accumulates no fragment
436
- * data.
437
- *
438
- * @param options - The fragment definition. An ID is generated when one is
439
- * not supplied.
440
- * @returns A read-only copy of the created fragment, or `undefined` when the
441
- * event fragments feature is disabled or the consent state does not allow
442
- * capture. Mutating the returned object does not change controller state.
443
- * Use {@link updateEventFragment} or {@link upsertEventFragment} to write.
444
- */
445
- createEventFragment(options = {}) {
446
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'createEventFragment')) {
447
- return undefined;
448
- }
449
- const now = Date.now();
450
- const fragment = {
451
- id: options.id ?? uuid(),
452
- properties: { ...(options.properties ?? {}) },
453
- sensitiveProperties: { ...(options.sensitiveProperties ?? {}) },
454
- createdAt: now,
455
- lastUpdated: now,
456
- ...(options.initialEvent === undefined
457
- ? {}
458
- : { initialEvent: options.initialEvent }),
459
- ...(options.successEvent === undefined
460
- ? {}
461
- : { successEvent: options.successEvent }),
462
- ...(options.failureEvent === undefined
463
- ? {}
464
- : { failureEvent: options.failureEvent }),
465
- ...(options.context === undefined
466
- ? {}
467
- : { context: { ...options.context } }),
468
- ...(options.persist === undefined ? {} : { persist: options.persist }),
469
- };
470
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, fragment);
471
- if (fragment.initialEvent) {
472
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_emitEventFragment).call(this, fragment, fragment.initialEvent, fragment.context);
473
- }
474
- return cloneDeep(fragment);
475
- }
476
- /**
477
- * Write to an event fragment, creating a property bag if none exists.
478
- *
479
- * This is the ergonomic entry point for contributors that do not know
480
- * whether the journey has been started yet, and it avoids the read then
481
- * write race a caller would otherwise have to implement itself.
482
- *
483
- * @param id - The fragment ID.
484
- * @param payload - The properties and context to merge in.
485
- */
486
- upsertEventFragment(id, payload = {}) {
487
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'upsertEventFragment')) {
488
- return;
489
- }
490
- const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
491
- if (!fragment) {
492
- this.createEventFragment({ id, ...payload });
493
- return;
494
- }
495
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, mergeEventFragment(fragment, payload));
496
- }
497
- /**
498
- * Write to an existing event fragment.
499
- *
500
- * @param id - The fragment ID.
501
- * @param payload - The properties and context to merge in.
502
- * @throws Error if no fragment has that ID when the call is not ignored.
503
- * Use {@link upsertEventFragment} when the fragment may not exist yet.
504
- * When the event fragments feature is disabled or the consent state does not
505
- * allow capture, the call is a logged no-op and does not throw.
506
- */
507
- updateEventFragment(id, payload = {}) {
508
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'updateEventFragment')) {
509
- return;
510
- }
511
- const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
512
- if (!fragment) {
513
- throw new Error(`Event fragment with id ${id} does not exist.`);
514
- }
515
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, mergeEventFragment(fragment, payload));
516
- }
517
- /**
518
- * Read an event fragment.
519
- *
520
- * @param id - The fragment ID.
521
- * @returns A read-only copy of the fragment, or `undefined` when no fragment
522
- * has that ID, the event fragments feature is disabled, or the consent state
523
- * does not allow capture. Mutating the returned object does not change
524
- * controller state. Use {@link updateEventFragment} or
525
- * {@link upsertEventFragment} to write.
526
- */
527
- getEventFragmentById(id) {
528
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'getEventFragmentById')) {
529
- return undefined;
530
- }
531
- const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
532
- return fragment === undefined ? undefined : cloneDeep(fragment);
533
- }
534
- /**
535
- * Discard an event fragment without emitting anything.
536
- *
537
- * @param id - The fragment ID.
538
- */
539
- deleteEventFragment(id) {
540
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'deleteEventFragment')) {
541
- return;
542
- }
543
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeEventFragment).call(this, id);
544
- }
545
- /**
546
- * Close an event fragment, emitting its closing event and discarding it.
547
- *
548
- * The event emitted is `failureEvent` when the journey was abandoned and
549
- * `successEvent` otherwise. A fragment that does not declare the relevant
550
- * event name is discarded silently, which is what makes a pure property bag
551
- * possible.
552
- *
553
- * @param id - The fragment ID.
554
- * @param options - Finalization options.
555
- * @param options.abandoned - Whether the journey was abandoned.
556
- * @param options.context - Context merged over the fragment's own context.
557
- * @throws Error if no fragment has that ID when the call is not ignored.
558
- * When the event fragments feature is disabled or the consent state does not
559
- * allow capture, the call is a logged no-op and does not throw.
560
- */
561
- finalizeEventFragment(id, { abandoned = false, context } = {}) {
562
- if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'finalizeEventFragment')) {
563
- return;
564
- }
565
- const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
566
- if (!fragment) {
567
- throw new Error(`Event fragment with id ${id} does not exist.`);
568
- }
569
- const eventName = abandoned ? fragment.failureEvent : fragment.successEvent;
570
- if (eventName) {
571
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_emitEventFragment).call(this, fragment, eventName, mergeEventFragmentContext(fragment.context, context));
572
- }
573
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeEventFragment).call(this, id);
574
- }
575
- /**
576
- * Opt in to analytics.
577
- *
578
- * Records that a consent decision has been made and replays any events that
579
- * were queued while the user was undecided.
580
- *
581
- * When geolocation enrichment is enabled, geolocation is resolved here (once
582
- * the user has consented) and awaited before the queued events are replayed,
583
- * so those events are enriched with the resolved location as they are sent.
584
- *
585
- * @returns A promise that resolves once opt-in processing has completed.
586
- */
587
- async optIn() {
588
- this.update((state) => {
589
- state.optedIn = true;
590
- state.consentDecisionMade = true;
591
- });
592
- // Now that the user has consented, resolve geolocation (once) and wait for
593
- // it so the queued pre-consent events can be enriched as they replay.
594
- await __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_maybeResolveLocation).call(this);
595
- // Reconcile against the current state rather than replaying blindly: the
596
- // consent decision may have changed while geolocation was resolving (e.g.
597
- // resetConsentDecision ran during the await), and preserved pre-consent
598
- // events must not be delivered once the user is no longer opted in.
599
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcilePreConsentEvents).call(this);
600
- }
601
- /**
602
- * Opt out of analytics.
603
- *
604
- * Records that a consent decision has been made and discards any persisted
605
- * events and in-progress event fragments so nothing captured before the
606
- * decision is ever delivered.
607
- */
608
- optOut() {
609
- this.update((state) => {
610
- state.optedIn = false;
611
- state.consentDecisionMade = true;
612
- });
613
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
614
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
615
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
616
- }
617
- /**
618
- * Reset the consent decision back to undecided.
619
- *
620
- * Intended for client flows that restart onboarding. Clears the opt-in
621
- * preference and discards the delivery queue, but preserves any pre-consent
622
- * events so they can still be replayed if the user opts in again. The user is
623
- * treated as undecided again.
624
- *
625
- * In-progress event fragments are kept only while the undecided user can
626
- * still accumulate them, and discarded otherwise, so no fragment outlives the
627
- * consent state that allowed it.
628
- */
629
- resetConsentDecision() {
630
- this.update((state) => {
631
- state.optedIn = false;
632
- state.consentDecisionMade = false;
633
- });
634
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
635
- if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
636
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
637
- }
638
- }
639
- }
640
- _AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_isEventQueuePersistenceEnabled = new WeakMap(), _AnalyticsController_isPreConsentQueueEnabled = new WeakMap(), _AnalyticsController_isGeolocationEnabled = new WeakMap(), _AnalyticsController_isEventFragmentsEnabled = new WeakMap(), _AnalyticsController_initPromise = new WeakMap(), _AnalyticsController_locationResolvePromise = new WeakMap(), _AnalyticsController_locationContext = new WeakMap(), _AnalyticsController_instances = new WeakSet(), _AnalyticsController_performInit =
641
- /**
642
- * Performs the one-time initialization work: resolve geolocation, run the
643
- * platform adapter's onSetupCompleted lifecycle hook, then replay any queued
644
- * and pre-consent events.
645
- */
646
- async function _AnalyticsController_performInit() {
647
- // Snapshot fragment IDs and createdAt before any awaited init work so
648
- // reconciliation can tell previous-session leftovers from fragments
649
- // created or replaced while init runs.
650
- const initEventFragmentSnapshot = new Map();
651
- for (const [id, fragment] of Object.entries(this.state.eventFragments ?? {})) {
652
- if (isAnalyticsEventFragment(fragment) &&
653
- fragment.id === id &&
654
- typeof fragment.createdAt === 'number') {
655
- initEventFragmentSnapshot.set(id, fragment.createdAt);
656
- }
657
- }
658
- // Resolve geolocation only when the user is already opted in; for undecided
659
- // or opted-out users it is deferred to {@link optIn}. Awaited so that an
660
- // already-opted-in session has location available before events replay.
661
- await __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_maybeResolveLocation).call(this);
662
- // Call onSetupCompleted lifecycle hook after initialization
663
- // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4
664
- try {
665
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").onSetupCompleted(this.state.analyticsId);
666
- }
667
- catch (error) {
668
- // Log error but don't throw - adapter setup failure shouldn't break controller
669
- log('Error calling platformAdapter.onSetupCompleted', error);
670
- }
671
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayQueuedEvents).call(this);
672
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcilePreConsentEvents).call(this);
673
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcileEventFragments).call(this, initEventFragmentSnapshot);
674
- }, _AnalyticsController_maybeResolveLocation = function _AnalyticsController_maybeResolveLocation() {
675
- if (__classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f") &&
676
- __classPrivateFieldGet(this, _AnalyticsController_locationResolvePromise, "f") === undefined &&
677
- analyticsControllerSelectors.selectEnabled(this.state)) {
678
- __classPrivateFieldSet(this, _AnalyticsController_locationResolvePromise, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_resolveLocationContext).call(this), "f");
679
- }
680
- return __classPrivateFieldGet(this, _AnalyticsController_locationResolvePromise, "f");
681
- }, _AnalyticsController_resolveLocationContext = async function _AnalyticsController_resolveLocationContext() {
682
- try {
683
- const geolocation = await this.messenger.call('GeolocationController:getGeolocationData');
684
- __classPrivateFieldSet(this, _AnalyticsController_locationContext, buildLocationContext(geolocation), "f");
685
- }
686
- catch (error) {
687
- // A common cause is the GeolocationController not being registered before
688
- // resolution runs (at init for an opted-in user, otherwise at opt-in).
689
- // Name it here so the failure is diagnosable, since enrichment is
690
- // otherwise skipped silently for the session.
691
- log('Failed to resolve geolocation for analytics enrichment; events will be sent without location. Ensure the GeolocationController is registered and initialized before the user opts in when geolocation is enabled.', error);
692
- }
693
- }, _AnalyticsController_withLocationContext = function _AnalyticsController_withLocationContext(context) {
694
- if (!__classPrivateFieldGet(this, _AnalyticsController_locationContext, "f")) {
695
- return context;
696
- }
697
- const callerLocation = context?.location;
698
- return {
699
- ...context,
700
- location: {
701
- ...(isJsonRecord(callerLocation) ? callerLocation : {}),
702
- ...__classPrivateFieldGet(this, _AnalyticsController_locationContext, "f"),
703
- },
704
- };
705
- }, _AnalyticsController_sendOrQueueTrackEvent = function _AnalyticsController_sendOrQueueTrackEvent(eventName, properties, context) {
706
- // Direct delivery: enabled and not persisting.
707
- if (analyticsControllerSelectors.selectEnabled(this.state) &&
708
- !__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
709
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(eventName, properties, context);
710
- return;
711
- }
712
- const queuedEvent = {
713
- type: 'track',
714
- eventName,
715
- messageId: uuid(),
716
- timestamp: new Date().toISOString(),
717
- ...(properties === undefined ? {} : { properties }),
718
- ...(context === undefined ? {} : { context }),
719
- };
720
- // Not yet enabled (reached only while undecided with the pre-consent queue
721
- // enabled): hold the event until the user opts in.
722
- if (!analyticsControllerSelectors.selectEnabled(this.state)) {
723
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueuePreConsentEvent).call(this, queuedEvent);
724
- return;
725
- }
726
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
727
- }, _AnalyticsController_sendOrQueueIdentifyEvent = function _AnalyticsController_sendOrQueueIdentifyEvent(userId, traits, context) {
728
- if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
729
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(userId, traits, context);
730
- return;
731
- }
732
- const queuedEvent = {
733
- type: 'identify',
734
- userId,
735
- messageId: uuid(),
736
- timestamp: new Date().toISOString(),
737
- ...(traits === undefined ? {} : { traits }),
738
- ...(context === undefined ? {} : { context }),
739
- };
740
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
741
- }, _AnalyticsController_sendOrQueueViewEvent = function _AnalyticsController_sendOrQueueViewEvent(name, properties, context) {
742
- if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
743
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties, context);
744
- return;
745
- }
746
- const queuedEvent = {
747
- type: 'view',
748
- name,
749
- messageId: uuid(),
750
- timestamp: new Date().toISOString(),
751
- ...(properties === undefined ? {} : { properties }),
752
- ...(context === undefined ? {} : { context }),
753
- };
754
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
755
- }, _AnalyticsController_enqueueEvent = function _AnalyticsController_enqueueEvent(queuedEvent) {
756
- const eventQueue = {
757
- ...(this.state.eventQueue ?? {}),
758
- [queuedEvent.messageId]: queuedEvent,
759
- };
760
- this.update((state) => {
761
- state.eventQueue = eventQueue;
762
- });
763
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
764
- }, _AnalyticsController_sendQueuedEvent = function _AnalyticsController_sendQueuedEvent(queuedEvent) {
765
- const timestamp = new Date(queuedEvent.timestamp);
766
- if (Number.isNaN(timestamp.getTime())) {
767
- log('Dropping queued analytics event with invalid timestamp', {
768
- messageId: queuedEvent.messageId,
769
- });
770
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
771
- return;
772
- }
773
- const options = {
774
- messageId: queuedEvent.messageId,
775
- timestamp,
776
- callback: (error) => {
777
- if (error) {
778
- log('Queued analytics event delivery failed', {
779
- messageId: queuedEvent.messageId,
780
- error,
781
- });
782
- }
783
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
784
- },
785
- };
786
- try {
787
- if (queuedEvent.type === 'track') {
788
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(queuedEvent.eventName, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
789
- }
790
- else if (queuedEvent.type === 'identify') {
791
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(queuedEvent.userId, cloneDeep(queuedEvent.traits), cloneDeep(queuedEvent.context), options);
792
- }
793
- else {
794
- __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(queuedEvent.name, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
795
- }
796
- }
797
- catch (error) {
798
- log('Error sending queued analytics event', {
799
- messageId: queuedEvent.messageId,
800
- error,
801
- });
802
- }
803
- }, _AnalyticsController_replayQueuedEvents = function _AnalyticsController_replayQueuedEvents() {
804
- if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f") || !this.state.eventQueue) {
805
- return;
806
- }
807
- if (!analyticsControllerSelectors.selectEnabled(this.state)) {
808
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
809
- return;
810
- }
811
- for (const [messageId, queuedEvent] of Object.entries(this.state.eventQueue)) {
812
- if (!isAnalyticsQueuedEvent(queuedEvent) ||
813
- queuedEvent.messageId !== messageId) {
814
- log('Dropping invalid queued analytics event', { messageId });
815
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, messageId);
816
- continue;
817
- }
818
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
819
- }
820
- }, _AnalyticsController_removeQueuedEvent = function _AnalyticsController_removeQueuedEvent(messageId) {
821
- const currentEventQueue = this.state.eventQueue;
822
- if (!currentEventQueue ||
823
- !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)) {
824
- return;
825
- }
826
- const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;
827
- this.update((state) => {
828
- state.eventQueue = eventQueue;
829
- });
830
- }, _AnalyticsController_clearQueuedEvents = function _AnalyticsController_clearQueuedEvents() {
831
- if (!this.state.eventQueue ||
832
- Object.keys(this.state.eventQueue).length === 0) {
833
- return;
834
- }
835
- this.update((state) => {
836
- state.eventQueue = {};
837
- });
838
- }, _AnalyticsController_enqueuePreConsentEvent = function _AnalyticsController_enqueuePreConsentEvent(queuedEvent) {
839
- const preConsentEventQueue = {
840
- ...(this.state.preConsentEventQueue ?? {}),
841
- [queuedEvent.messageId]: queuedEvent,
842
- };
843
- this.update((state) => {
844
- state.preConsentEventQueue = preConsentEventQueue;
845
- });
846
- }, _AnalyticsController_replayPreConsentEvents = function _AnalyticsController_replayPreConsentEvents(queue) {
847
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
848
- for (const [messageId, queuedEvent] of Object.entries(queue)) {
849
- if (!isAnalyticsQueuedEvent(queuedEvent) ||
850
- queuedEvent.messageId !== messageId) {
851
- log('Dropping invalid queued pre-consent analytics event', {
852
- messageId,
853
- });
854
- continue;
855
- }
856
- const eventToReplay = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enrichPreConsentEvent).call(this, queuedEvent);
857
- if (__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
858
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, eventToReplay);
859
- }
860
- else {
861
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, eventToReplay);
862
- }
863
- }
864
- }, _AnalyticsController_enrichPreConsentEvent = function _AnalyticsController_enrichPreConsentEvent(queuedEvent) {
865
- if (queuedEvent.type === 'track' &&
866
- queuedEvent.properties?.anonymous === true) {
867
- return queuedEvent;
868
- }
869
- const context = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, queuedEvent.context);
870
- return {
871
- ...queuedEvent,
872
- ...(context === undefined ? {} : { context }),
873
- };
874
- }, _AnalyticsController_clearPreConsentEvents = function _AnalyticsController_clearPreConsentEvents() {
875
- if (!this.state.preConsentEventQueue) {
876
- return;
877
- }
878
- this.update((state) => {
879
- state.preConsentEventQueue = {};
880
- });
881
- }, _AnalyticsController_reconcilePreConsentEvents = function _AnalyticsController_reconcilePreConsentEvents() {
882
- const queue = this.state.preConsentEventQueue;
883
- if (!queue) {
884
- return;
885
- }
886
- if (!__classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f")) {
887
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
888
- return;
889
- }
890
- if (this.state.optedIn) {
891
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayPreConsentEvents).call(this, queue);
892
- }
893
- else if (this.state.consentDecisionMade) {
894
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
895
- }
896
- }, _AnalyticsController_reconcileEventFragments = function _AnalyticsController_reconcileEventFragments(initEventFragmentSnapshot) {
897
- const fragments = this.state.eventFragments;
898
- if (!fragments) {
899
- return;
900
- }
901
- if (!__classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f") || !__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
902
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
903
- return;
904
- }
905
- __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_purgeStaleEventFragments).call(this, fragments, initEventFragmentSnapshot);
906
- }, _AnalyticsController_purgeStaleEventFragments = function _AnalyticsController_purgeStaleEventFragments(currentEventFragments, initEventFragmentSnapshot) {
907
- const eventFragments = {};
908
- const now = Date.now();
909
- for (const [id, fragment] of Object.entries(currentEventFragments)) {
910
- if (!isAnalyticsEventFragment(fragment) || fragment.id !== id) {
911
- log('Dropping invalid persisted event fragment', { id });
912
- continue;
913
- }
914
- if (now - fragment.lastUpdated > EVENT_FRAGMENT_MAX_AGE) {
915
- log('Dropping expired persisted event fragment', { id });
916
- continue;
917
- }
918
- const snapshotCreatedAt = initEventFragmentSnapshot.get(id);
919
- if (fragment.persist === true ||
920
- snapshotCreatedAt === undefined ||
921
- fragment.createdAt !== snapshotCreatedAt) {
922
- eventFragments[id] = fragment;
923
- }
924
- }
925
- if (Object.keys(eventFragments).length ===
926
- Object.keys(currentEventFragments).length) {
927
- return;
928
- }
929
- this.update((state) => {
930
- state.eventFragments = eventFragments;
931
- });
932
- }, _AnalyticsController_getEventFragment = function _AnalyticsController_getEventFragment(id) {
933
- return this.state.eventFragments?.[id];
934
- }, _AnalyticsController_setEventFragment = function _AnalyticsController_setEventFragment(fragment) {
935
- const eventFragments = {
936
- ...this.state.eventFragments,
937
- [fragment.id]: fragment,
938
- };
939
- this.update((state) => {
940
- state.eventFragments = eventFragments;
941
- });
942
- }, _AnalyticsController_removeEventFragment = function _AnalyticsController_removeEventFragment(id) {
943
- const currentEventFragments = this.state.eventFragments;
944
- if (!currentEventFragments ||
945
- !Object.prototype.hasOwnProperty.call(currentEventFragments, id)) {
946
- return;
947
- }
948
- const { [id]: _deletedFragment, ...eventFragments } = currentEventFragments;
949
- this.update((state) => {
950
- state.eventFragments = eventFragments;
951
- });
952
- }, _AnalyticsController_clearEventFragments = function _AnalyticsController_clearEventFragments() {
953
- if (!this.state.eventFragments ||
954
- Object.keys(this.state.eventFragments).length === 0) {
955
- return;
956
- }
957
- this.update((state) => {
958
- state.eventFragments = {};
959
- });
960
- }, _AnalyticsController_shouldIgnoreEventFragmentCall = function _AnalyticsController_shouldIgnoreEventFragmentCall(method) {
961
- if (!__classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f")) {
962
- log('Ignoring event fragment call because the event fragments feature is disabled', { method });
963
- return true;
964
- }
965
- if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
966
- log('Ignoring event fragment call because the consent state does not allow capturing analytics', { method });
967
- return true;
968
- }
969
- return false;
970
- }, _AnalyticsController_emitEventFragment = function _AnalyticsController_emitEventFragment(fragment, name, context) {
971
- const properties = { ...fragment.properties };
972
- const sensitiveProperties = { ...fragment.sensitiveProperties };
973
- this.trackEvent({
974
- name,
975
- properties,
976
- sensitiveProperties,
977
- saveDataRecording: false,
978
- hasProperties: Object.keys(properties).length > 0 ||
979
- Object.keys(sensitiveProperties).length > 0,
980
- }, context);
981
- }, _AnalyticsController_isAnalyticsCaptureAllowed = function _AnalyticsController_isAnalyticsCaptureAllowed() {
982
- if (analyticsControllerSelectors.selectEnabled(this.state)) {
983
- return true;
984
- }
985
- return __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f") && !this.state.consentDecisionMade;
986
- };
987
- //# sourceMappingURL=AnalyticsController.mjs.map