@metamask-previews/analytics-controller 2.0.0-preview-3866c0ff1 → 2.0.0-preview-e3275932a
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.
- package/CHANGELOG.md +0 -4
- package/dist/AnalyticsController-method-action-types.cjs +7 -0
- package/dist/AnalyticsController-method-action-types.cjs.map +1 -0
- package/dist/{AnalyticsController-method-action-types.d.ts → AnalyticsController-method-action-types.d.cts} +2 -2
- package/dist/AnalyticsController-method-action-types.d.cts.map +1 -0
- package/dist/AnalyticsController-method-action-types.d.mts +81 -0
- package/dist/AnalyticsController-method-action-types.d.mts.map +1 -0
- package/dist/{AnalyticsController-method-action-types.js → AnalyticsController-method-action-types.mjs} +1 -1
- package/dist/AnalyticsController-method-action-types.mjs.map +1 -0
- package/dist/AnalyticsController.cjs +641 -0
- package/dist/AnalyticsController.cjs.map +1 -0
- package/dist/{AnalyticsController.d.ts → AnalyticsController.d.cts} +8 -8
- package/dist/AnalyticsController.d.cts.map +1 -0
- package/dist/AnalyticsController.d.mts +312 -0
- package/dist/AnalyticsController.d.mts.map +1 -0
- package/dist/AnalyticsController.mjs +637 -0
- package/dist/AnalyticsController.mjs.map +1 -0
- package/dist/AnalyticsLogger.cjs +8 -0
- package/dist/AnalyticsLogger.cjs.map +1 -0
- package/dist/AnalyticsLogger.d.cts +5 -0
- package/dist/AnalyticsLogger.d.cts.map +1 -0
- package/dist/AnalyticsLogger.d.mts +5 -0
- package/dist/AnalyticsLogger.d.mts.map +1 -0
- package/dist/{AnalyticsLogger.js → AnalyticsLogger.mjs} +2 -2
- package/dist/AnalyticsLogger.mjs.map +1 -0
- package/dist/AnalyticsPlatformAdapter.types.cjs +3 -0
- package/dist/AnalyticsPlatformAdapter.types.cjs.map +1 -0
- package/dist/{AnalyticsPlatformAdapter.types.d.ts → AnalyticsPlatformAdapter.types.d.cts} +2 -2
- package/dist/AnalyticsPlatformAdapter.types.d.cts.map +1 -0
- package/dist/AnalyticsPlatformAdapter.types.d.mts +144 -0
- package/dist/AnalyticsPlatformAdapter.types.d.mts.map +1 -0
- package/dist/AnalyticsPlatformAdapter.types.mjs +2 -0
- package/dist/AnalyticsPlatformAdapter.types.mjs.map +1 -0
- package/dist/AnalyticsPlatformAdapterSetupError.cjs +17 -0
- package/dist/AnalyticsPlatformAdapterSetupError.cjs.map +1 -0
- package/dist/{AnalyticsPlatformAdapterSetupError.d.ts → AnalyticsPlatformAdapterSetupError.d.cts} +1 -1
- package/dist/AnalyticsPlatformAdapterSetupError.d.cts.map +1 -0
- package/dist/AnalyticsPlatformAdapterSetupError.d.mts +8 -0
- package/dist/AnalyticsPlatformAdapterSetupError.d.mts.map +1 -0
- package/dist/{AnalyticsPlatformAdapterSetupError.js → AnalyticsPlatformAdapterSetupError.mjs} +1 -2
- package/dist/AnalyticsPlatformAdapterSetupError.mjs.map +1 -0
- package/dist/analyticsControllerStateValidator.cjs +36 -0
- package/dist/analyticsControllerStateValidator.cjs.map +1 -0
- package/dist/{analyticsControllerStateValidator.d.ts → analyticsControllerStateValidator.d.cts} +2 -2
- package/dist/analyticsControllerStateValidator.d.cts.map +1 -0
- package/dist/analyticsControllerStateValidator.d.mts +17 -0
- package/dist/analyticsControllerStateValidator.d.mts.map +1 -0
- package/dist/{analyticsControllerStateValidator.js → analyticsControllerStateValidator.mjs} +1 -1
- package/dist/analyticsControllerStateValidator.mjs.map +1 -0
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -0
- package/dist/{index.d.ts → index.d.cts} +10 -10
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +10 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +7 -0
- package/dist/index.mjs.map +1 -0
- package/dist/{selectors.d.ts → selectors.cjs} +13 -12
- package/dist/selectors.cjs.map +1 -0
- package/dist/selectors.d.cts +12 -0
- package/dist/selectors.d.cts.map +1 -0
- package/dist/selectors.d.mts +12 -0
- package/dist/selectors.d.mts.map +1 -0
- package/dist/{selectors.js → selectors.mjs} +1 -1
- package/dist/selectors.mjs.map +1 -0
- package/package.json +17 -13
- package/dist/AnalyticsController-method-action-types.d.ts.map +0 -1
- package/dist/AnalyticsController-method-action-types.js.map +0 -1
- package/dist/AnalyticsController.d.ts.map +0 -1
- package/dist/AnalyticsController.js +0 -746
- package/dist/AnalyticsController.js.map +0 -1
- package/dist/AnalyticsLogger.d.ts +0 -4
- package/dist/AnalyticsLogger.d.ts.map +0 -1
- package/dist/AnalyticsLogger.js.map +0 -1
- package/dist/AnalyticsPlatformAdapter.types.d.ts.map +0 -1
- package/dist/AnalyticsPlatformAdapter.types.js +0 -2
- package/dist/AnalyticsPlatformAdapter.types.js.map +0 -1
- package/dist/AnalyticsPlatformAdapterSetupError.d.ts.map +0 -1
- package/dist/AnalyticsPlatformAdapterSetupError.js.map +0 -1
- package/dist/analyticsControllerStateValidator.d.ts.map +0 -1
- package/dist/analyticsControllerStateValidator.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -7
- package/dist/index.js.map +0 -1
- package/dist/selectors.d.ts.map +0 -1
- package/dist/selectors.js.map +0 -1
|
@@ -1,746 +0,0 @@
|
|
|
1
|
-
import { BaseController } from '@metamask/base-controller';
|
|
2
|
-
import { cloneDeep } from 'lodash-es';
|
|
3
|
-
import { v4 as uuid } from 'uuid';
|
|
4
|
-
import { validateAnalyticsControllerState } from './analyticsControllerStateValidator.js';
|
|
5
|
-
import { projectLogger as log } from './AnalyticsLogger.js';
|
|
6
|
-
import { analyticsControllerSelectors } from './selectors.js';
|
|
7
|
-
// === GENERAL ===
|
|
8
|
-
/**
|
|
9
|
-
* The name of the {@link AnalyticsController}, used to namespace the
|
|
10
|
-
* controller's actions and events and to namespace the controller's state data
|
|
11
|
-
* when composed with other controllers.
|
|
12
|
-
*/
|
|
13
|
-
export const controllerName = 'AnalyticsController';
|
|
14
|
-
/**
|
|
15
|
-
* Returns default values for AnalyticsController state.
|
|
16
|
-
*
|
|
17
|
-
* Note: analyticsId is NOT included - it's an identity that must be
|
|
18
|
-
* provided by the platform (generated once on first run, then persisted).
|
|
19
|
-
*
|
|
20
|
-
* @returns Default state without analyticsId
|
|
21
|
-
*/
|
|
22
|
-
export function getDefaultAnalyticsControllerState() {
|
|
23
|
-
return {
|
|
24
|
-
optedIn: false,
|
|
25
|
-
consentDecisionMade: false,
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* The metadata for each property in {@link AnalyticsControllerState}.
|
|
30
|
-
*
|
|
31
|
-
* Both `optedIn` and `analyticsId` are persisted (`persist: true`).
|
|
32
|
-
* The platform must supply a valid UUIDv4 `analyticsId` on first run.
|
|
33
|
-
*/
|
|
34
|
-
const analyticsControllerMetadata = {
|
|
35
|
-
optedIn: {
|
|
36
|
-
includeInStateLogs: true,
|
|
37
|
-
persist: true,
|
|
38
|
-
includeInDebugSnapshot: true,
|
|
39
|
-
usedInUi: true,
|
|
40
|
-
},
|
|
41
|
-
analyticsId: {
|
|
42
|
-
includeInStateLogs: true,
|
|
43
|
-
persist: true,
|
|
44
|
-
includeInDebugSnapshot: true,
|
|
45
|
-
usedInUi: false,
|
|
46
|
-
},
|
|
47
|
-
eventQueue: {
|
|
48
|
-
includeInStateLogs: false,
|
|
49
|
-
persist: true,
|
|
50
|
-
includeInDebugSnapshot: false,
|
|
51
|
-
usedInUi: false,
|
|
52
|
-
},
|
|
53
|
-
consentDecisionMade: {
|
|
54
|
-
includeInStateLogs: true,
|
|
55
|
-
persist: true,
|
|
56
|
-
includeInDebugSnapshot: true,
|
|
57
|
-
usedInUi: true,
|
|
58
|
-
},
|
|
59
|
-
preConsentEventQueue: {
|
|
60
|
-
includeInStateLogs: false,
|
|
61
|
-
persist: true,
|
|
62
|
-
includeInDebugSnapshot: false,
|
|
63
|
-
usedInUi: false,
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
// === MESSENGER ===
|
|
67
|
-
const MESSENGER_EXPOSED_METHODS = [
|
|
68
|
-
'trackEvent',
|
|
69
|
-
'identify',
|
|
70
|
-
'trackView',
|
|
71
|
-
'optIn',
|
|
72
|
-
'optOut',
|
|
73
|
-
'resetConsentDecision',
|
|
74
|
-
];
|
|
75
|
-
/**
|
|
76
|
-
* Returns whether a value is a non-array object.
|
|
77
|
-
*
|
|
78
|
-
* @param value - The value to check.
|
|
79
|
-
* @returns True if the value is a record.
|
|
80
|
-
*/
|
|
81
|
-
function isRecord(value) {
|
|
82
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Returns whether a JSON value is a non-array object.
|
|
86
|
-
*
|
|
87
|
-
* @param value - The value to check.
|
|
88
|
-
* @returns True if the value is a JSON record.
|
|
89
|
-
*/
|
|
90
|
-
function isJsonRecord(value) {
|
|
91
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Builds the analytics location context from geolocation data, keeping only
|
|
95
|
-
* the fields the geolocation API was able to determine.
|
|
96
|
-
*
|
|
97
|
-
* @param geolocation - The geolocation data to convert.
|
|
98
|
-
* @returns The location context, or `undefined` when no field is known.
|
|
99
|
-
*/
|
|
100
|
-
function buildLocationContext(geolocation) {
|
|
101
|
-
const locationContext = {
|
|
102
|
-
...(geolocation.country === null
|
|
103
|
-
? {}
|
|
104
|
-
: { country_code: geolocation.country }),
|
|
105
|
-
...(geolocation.region === null ? {} : { region: geolocation.region }),
|
|
106
|
-
...(geolocation.timezone === null
|
|
107
|
-
? {}
|
|
108
|
-
: { timezone: geolocation.timezone }),
|
|
109
|
-
};
|
|
110
|
-
return Object.keys(locationContext).length === 0
|
|
111
|
-
? undefined
|
|
112
|
-
: locationContext;
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* Returns whether a value is a valid persisted analytics event.
|
|
116
|
-
*
|
|
117
|
-
* @param value - The value to check.
|
|
118
|
-
* @returns True if the value is a queued analytics event.
|
|
119
|
-
*/
|
|
120
|
-
function isAnalyticsQueuedEvent(value) {
|
|
121
|
-
if (!isRecord(value)) {
|
|
122
|
-
return false;
|
|
123
|
-
}
|
|
124
|
-
if (typeof value.messageId !== 'string' ||
|
|
125
|
-
typeof value.timestamp !== 'string') {
|
|
126
|
-
return false;
|
|
127
|
-
}
|
|
128
|
-
if (value.type === 'track') {
|
|
129
|
-
return (typeof value.eventName === 'string' &&
|
|
130
|
-
(value.properties === undefined || isRecord(value.properties)) &&
|
|
131
|
-
(value.context === undefined || isRecord(value.context)));
|
|
132
|
-
}
|
|
133
|
-
if (value.type === 'identify') {
|
|
134
|
-
return (typeof value.userId === 'string' &&
|
|
135
|
-
(value.traits === undefined || isRecord(value.traits)) &&
|
|
136
|
-
(value.context === undefined || isRecord(value.context)));
|
|
137
|
-
}
|
|
138
|
-
if (value.type === 'view') {
|
|
139
|
-
return (typeof value.name === 'string' &&
|
|
140
|
-
(value.properties === undefined || isRecord(value.properties)) &&
|
|
141
|
-
(value.context === undefined || isRecord(value.context)));
|
|
142
|
-
}
|
|
143
|
-
return false;
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).
|
|
147
|
-
* It provides a unified interface for tracking events, identifying users, and managing
|
|
148
|
-
* analytics preferences while delegating platform-specific implementation to an
|
|
149
|
-
* {@link AnalyticsPlatformAdapter}.
|
|
150
|
-
*
|
|
151
|
-
* This controller follows the MetaMask controller pattern and integrates with the
|
|
152
|
-
* messenger system to allow other controllers and components to track analytics events.
|
|
153
|
-
* It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.
|
|
154
|
-
*
|
|
155
|
-
* The controller persists `optedIn` and `analyticsId` when composed with a persisted
|
|
156
|
-
* store. The platform must supply a valid `analyticsId` on first launch.
|
|
157
|
-
*/
|
|
158
|
-
export class AnalyticsController extends BaseController {
|
|
159
|
-
#platformAdapter;
|
|
160
|
-
#isAnonymousEventsFeatureEnabled;
|
|
161
|
-
#isEventQueuePersistenceEnabled;
|
|
162
|
-
#isPreConsentQueueEnabled;
|
|
163
|
-
#isGeolocationEnabled;
|
|
164
|
-
/**
|
|
165
|
-
* The in-flight (or settled) initialization promise. Set on the first
|
|
166
|
-
* {@link init} call and returned by subsequent calls so overlapping callers
|
|
167
|
-
* await the same work rather than observing a premature completion.
|
|
168
|
-
*/
|
|
169
|
-
#initPromise;
|
|
170
|
-
/**
|
|
171
|
-
* The in-flight (or settled) geolocation resolution, if any. Its presence
|
|
172
|
-
* marks that resolution has been started, so it runs at most once.
|
|
173
|
-
*/
|
|
174
|
-
#locationResolvePromise;
|
|
175
|
-
#locationContext;
|
|
176
|
-
/**
|
|
177
|
-
* Constructs an AnalyticsController instance.
|
|
178
|
-
*
|
|
179
|
-
* @param options - Controller options
|
|
180
|
-
* @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.
|
|
181
|
-
* Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.
|
|
182
|
-
* @param options.messenger - Messenger used to communicate with BaseController
|
|
183
|
-
* @param options.platformAdapter - Platform adapter implementation for tracking
|
|
184
|
-
* @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
|
|
185
|
-
* @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
|
|
186
|
-
* @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled
|
|
187
|
-
* @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled
|
|
188
|
-
* @throws Error if state.analyticsId is missing or not a valid UUIDv4
|
|
189
|
-
* @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
|
|
190
|
-
*/
|
|
191
|
-
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, isPreConsentQueueEnabled = false, isGeolocationEnabled = false, }) {
|
|
192
|
-
const initialState = {
|
|
193
|
-
...getDefaultAnalyticsControllerState(),
|
|
194
|
-
...state,
|
|
195
|
-
};
|
|
196
|
-
validateAnalyticsControllerState(initialState, platformAdapter.skipUUIDv4Check === true);
|
|
197
|
-
super({
|
|
198
|
-
name: controllerName,
|
|
199
|
-
metadata: analyticsControllerMetadata,
|
|
200
|
-
state: initialState,
|
|
201
|
-
messenger,
|
|
202
|
-
});
|
|
203
|
-
this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;
|
|
204
|
-
this.#isEventQueuePersistenceEnabled = isEventQueuePersistenceEnabled;
|
|
205
|
-
this.#isPreConsentQueueEnabled = isPreConsentQueueEnabled;
|
|
206
|
-
this.#isGeolocationEnabled = isGeolocationEnabled;
|
|
207
|
-
this.#platformAdapter = platformAdapter;
|
|
208
|
-
this.#initPromise = undefined;
|
|
209
|
-
this.#locationResolvePromise = undefined;
|
|
210
|
-
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
211
|
-
log('AnalyticsController initialized and ready', {
|
|
212
|
-
enabled: analyticsControllerSelectors.selectEnabled(this.state),
|
|
213
|
-
optedIn: this.state.optedIn,
|
|
214
|
-
consentDecisionMade: this.state.consentDecisionMade,
|
|
215
|
-
analyticsId: this.state.analyticsId,
|
|
216
|
-
eventQueuePersistenceEnabled: this.#isEventQueuePersistenceEnabled,
|
|
217
|
-
preConsentQueueEnabled: this.#isPreConsentQueueEnabled,
|
|
218
|
-
geolocationEnabled: this.#isGeolocationEnabled,
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
/**
|
|
222
|
-
* Initialize the controller by calling the platform adapter's
|
|
223
|
-
* onSetupCompleted lifecycle hook and replaying any queued events. This
|
|
224
|
-
* method must be called after construction to complete the setup process.
|
|
225
|
-
*
|
|
226
|
-
* When geolocation enrichment is enabled (`isGeolocationEnabled`), geolocation
|
|
227
|
-
* is resolved only for a user who is already opted in; for undecided or
|
|
228
|
-
* opted-out users it is deferred until they opt in (see {@link optIn}), so a
|
|
229
|
-
* user's location is never requested before they consent to analytics. In
|
|
230
|
-
* either case the `GeolocationController` and its
|
|
231
|
-
* `GeolocationController:getGeolocationData` action must be registered before
|
|
232
|
-
* resolution occurs, or enrichment is skipped for the session (a message is
|
|
233
|
-
* logged, see {@link #resolveLocationContext}).
|
|
234
|
-
*
|
|
235
|
-
* Safe to call more than once: the first call performs initialization and
|
|
236
|
-
* subsequent calls return the same in-flight (or settled) promise.
|
|
237
|
-
*
|
|
238
|
-
* @returns A promise that resolves once initialization has completed.
|
|
239
|
-
*/
|
|
240
|
-
init() {
|
|
241
|
-
// Cache the in-flight promise so repeated or overlapping calls share a
|
|
242
|
-
// single initialization and all await the same completion (rather than an
|
|
243
|
-
// early call observing a finished init while work is still pending).
|
|
244
|
-
this.#initPromise ??= this.#performInit();
|
|
245
|
-
return this.#initPromise;
|
|
246
|
-
}
|
|
247
|
-
/**
|
|
248
|
-
* Performs the one-time initialization work: resolve geolocation, run the
|
|
249
|
-
* platform adapter's onSetupCompleted lifecycle hook, then replay any queued
|
|
250
|
-
* and pre-consent events.
|
|
251
|
-
*/
|
|
252
|
-
async #performInit() {
|
|
253
|
-
// Resolve geolocation only when the user is already opted in; for undecided
|
|
254
|
-
// or opted-out users it is deferred to {@link optIn}. Awaited so that an
|
|
255
|
-
// already-opted-in session has location available before events replay.
|
|
256
|
-
await this.#maybeResolveLocation();
|
|
257
|
-
// Call onSetupCompleted lifecycle hook after initialization
|
|
258
|
-
// State is already validated, so analyticsId is guaranteed to be a valid UUIDv4
|
|
259
|
-
try {
|
|
260
|
-
this.#platformAdapter.onSetupCompleted(this.state.analyticsId);
|
|
261
|
-
}
|
|
262
|
-
catch (error) {
|
|
263
|
-
// Log error but don't throw - adapter setup failure shouldn't break controller
|
|
264
|
-
log('Error calling platformAdapter.onSetupCompleted', error);
|
|
265
|
-
}
|
|
266
|
-
this.#replayQueuedEvents();
|
|
267
|
-
this.#reconcilePreConsentEvents();
|
|
268
|
-
}
|
|
269
|
-
/**
|
|
270
|
-
* Start resolving the geolocation context if warranted, and return the
|
|
271
|
-
* in-flight (or settled) resolution so callers can await it. No-op unless
|
|
272
|
-
* enrichment is enabled, the user is opted in, and a resolution has not
|
|
273
|
-
* already been started. Deferring resolution until opt-in ensures a user's
|
|
274
|
-
* location is never requested before they consent to analytics (for example,
|
|
275
|
-
* during onboarding).
|
|
276
|
-
*
|
|
277
|
-
* Resolution runs at most once per controller session: the settled promise
|
|
278
|
-
* is retained, so the outcome — including a failure (see
|
|
279
|
-
* {@link #resolveLocationContext}) — is not retried, and events are delivered
|
|
280
|
-
* without location for the rest of the session.
|
|
281
|
-
*
|
|
282
|
-
* @returns The geolocation resolution promise, or `undefined` when no
|
|
283
|
-
* resolution is warranted.
|
|
284
|
-
*/
|
|
285
|
-
#maybeResolveLocation() {
|
|
286
|
-
if (this.#isGeolocationEnabled &&
|
|
287
|
-
this.#locationResolvePromise === undefined &&
|
|
288
|
-
analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
289
|
-
this.#locationResolvePromise = this.#resolveLocationContext();
|
|
290
|
-
}
|
|
291
|
-
return this.#locationResolvePromise;
|
|
292
|
-
}
|
|
293
|
-
async #resolveLocationContext() {
|
|
294
|
-
try {
|
|
295
|
-
const geolocation = await this.messenger.call('GeolocationController:getGeolocationData');
|
|
296
|
-
this.#locationContext = buildLocationContext(geolocation);
|
|
297
|
-
}
|
|
298
|
-
catch (error) {
|
|
299
|
-
// A common cause is the GeolocationController not being registered before
|
|
300
|
-
// resolution runs (at init for an opted-in user, otherwise at opt-in).
|
|
301
|
-
// Name it here so the failure is diagnosable, since enrichment is
|
|
302
|
-
// otherwise skipped silently for the session.
|
|
303
|
-
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);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* Merge the resolved location context into a caller-provided context.
|
|
308
|
-
*
|
|
309
|
-
* Caller-provided `location` fields are preserved, but the fields the
|
|
310
|
-
* controller resolves take precedence over them.
|
|
311
|
-
*
|
|
312
|
-
* @param context - Optional caller-provided context.
|
|
313
|
-
* @returns The context enriched with location, or the original context when
|
|
314
|
-
* no location is known.
|
|
315
|
-
*/
|
|
316
|
-
#withLocationContext(context) {
|
|
317
|
-
if (!this.#locationContext) {
|
|
318
|
-
return context;
|
|
319
|
-
}
|
|
320
|
-
const callerLocation = context?.location;
|
|
321
|
-
return {
|
|
322
|
-
...context,
|
|
323
|
-
location: {
|
|
324
|
-
...(isJsonRecord(callerLocation) ? callerLocation : {}),
|
|
325
|
-
...this.#locationContext,
|
|
326
|
-
},
|
|
327
|
-
};
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Send final track payload through the platform adapter or queue it if persistence is enabled.
|
|
331
|
-
*
|
|
332
|
-
* @param eventName - The name of the event.
|
|
333
|
-
* @param properties - Optional event properties.
|
|
334
|
-
* @param context - Optional platform-specific context.
|
|
335
|
-
*/
|
|
336
|
-
#sendOrQueueTrackEvent(eventName, properties, context) {
|
|
337
|
-
// Direct delivery: enabled and not persisting.
|
|
338
|
-
if (analyticsControllerSelectors.selectEnabled(this.state) &&
|
|
339
|
-
!this.#isEventQueuePersistenceEnabled) {
|
|
340
|
-
this.#platformAdapter.track(eventName, properties, context);
|
|
341
|
-
return;
|
|
342
|
-
}
|
|
343
|
-
const queuedEvent = {
|
|
344
|
-
type: 'track',
|
|
345
|
-
eventName,
|
|
346
|
-
messageId: uuid(),
|
|
347
|
-
timestamp: new Date().toISOString(),
|
|
348
|
-
...(properties === undefined ? {} : { properties }),
|
|
349
|
-
...(context === undefined ? {} : { context }),
|
|
350
|
-
};
|
|
351
|
-
// Not yet enabled (reached only while undecided with the pre-consent queue
|
|
352
|
-
// enabled): hold the event until the user opts in.
|
|
353
|
-
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
354
|
-
this.#enqueuePreConsentEvent(queuedEvent);
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
this.#enqueueEvent(queuedEvent);
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* Send final identify payload through the platform adapter or queue it if persistence is enabled.
|
|
361
|
-
*
|
|
362
|
-
* @param userId - The user ID.
|
|
363
|
-
* @param traits - Optional user traits.
|
|
364
|
-
* @param context - Optional platform-specific context.
|
|
365
|
-
*/
|
|
366
|
-
#sendOrQueueIdentifyEvent(userId, traits, context) {
|
|
367
|
-
if (!this.#isEventQueuePersistenceEnabled) {
|
|
368
|
-
this.#platformAdapter.identify(userId, traits, context);
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
const queuedEvent = {
|
|
372
|
-
type: 'identify',
|
|
373
|
-
userId,
|
|
374
|
-
messageId: uuid(),
|
|
375
|
-
timestamp: new Date().toISOString(),
|
|
376
|
-
...(traits === undefined ? {} : { traits }),
|
|
377
|
-
...(context === undefined ? {} : { context }),
|
|
378
|
-
};
|
|
379
|
-
this.#enqueueEvent(queuedEvent);
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Send final view payload through the platform adapter or queue it if persistence is enabled.
|
|
383
|
-
*
|
|
384
|
-
* @param name - The view name.
|
|
385
|
-
* @param properties - Optional view properties.
|
|
386
|
-
* @param context - Optional platform-specific context.
|
|
387
|
-
*/
|
|
388
|
-
#sendOrQueueViewEvent(name, properties, context) {
|
|
389
|
-
if (!this.#isEventQueuePersistenceEnabled) {
|
|
390
|
-
this.#platformAdapter.view(name, properties, context);
|
|
391
|
-
return;
|
|
392
|
-
}
|
|
393
|
-
const queuedEvent = {
|
|
394
|
-
type: 'view',
|
|
395
|
-
name,
|
|
396
|
-
messageId: uuid(),
|
|
397
|
-
timestamp: new Date().toISOString(),
|
|
398
|
-
...(properties === undefined ? {} : { properties }),
|
|
399
|
-
...(context === undefined ? {} : { context }),
|
|
400
|
-
};
|
|
401
|
-
this.#enqueueEvent(queuedEvent);
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Add an analytics event to the queue and send it.
|
|
405
|
-
*
|
|
406
|
-
* @param queuedEvent - The event to enqueue and deliver.
|
|
407
|
-
*/
|
|
408
|
-
#enqueueEvent(queuedEvent) {
|
|
409
|
-
const eventQueue = {
|
|
410
|
-
...(this.state.eventQueue ?? {}),
|
|
411
|
-
[queuedEvent.messageId]: queuedEvent,
|
|
412
|
-
};
|
|
413
|
-
this.update((state) => {
|
|
414
|
-
state.eventQueue = eventQueue;
|
|
415
|
-
});
|
|
416
|
-
this.#sendQueuedEvent(queuedEvent);
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Send a queued event through the platform adapter.
|
|
420
|
-
*
|
|
421
|
-
* @param queuedEvent - The queued event to deliver.
|
|
422
|
-
*/
|
|
423
|
-
#sendQueuedEvent(queuedEvent) {
|
|
424
|
-
const timestamp = new Date(queuedEvent.timestamp);
|
|
425
|
-
if (Number.isNaN(timestamp.getTime())) {
|
|
426
|
-
log('Dropping queued analytics event with invalid timestamp', {
|
|
427
|
-
messageId: queuedEvent.messageId,
|
|
428
|
-
});
|
|
429
|
-
this.#removeQueuedEvent(queuedEvent.messageId);
|
|
430
|
-
return;
|
|
431
|
-
}
|
|
432
|
-
const options = {
|
|
433
|
-
messageId: queuedEvent.messageId,
|
|
434
|
-
timestamp,
|
|
435
|
-
callback: (error) => {
|
|
436
|
-
if (error) {
|
|
437
|
-
log('Queued analytics event delivery failed', {
|
|
438
|
-
messageId: queuedEvent.messageId,
|
|
439
|
-
error,
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
|
-
this.#removeQueuedEvent(queuedEvent.messageId);
|
|
443
|
-
},
|
|
444
|
-
};
|
|
445
|
-
try {
|
|
446
|
-
if (queuedEvent.type === 'track') {
|
|
447
|
-
this.#platformAdapter.track(queuedEvent.eventName, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
|
|
448
|
-
}
|
|
449
|
-
else if (queuedEvent.type === 'identify') {
|
|
450
|
-
this.#platformAdapter.identify(queuedEvent.userId, cloneDeep(queuedEvent.traits), cloneDeep(queuedEvent.context), options);
|
|
451
|
-
}
|
|
452
|
-
else {
|
|
453
|
-
this.#platformAdapter.view(queuedEvent.name, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
catch (error) {
|
|
457
|
-
log('Error sending queued analytics event', {
|
|
458
|
-
messageId: queuedEvent.messageId,
|
|
459
|
-
error,
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
/**
|
|
464
|
-
* Replay persisted analytics events.
|
|
465
|
-
*/
|
|
466
|
-
#replayQueuedEvents() {
|
|
467
|
-
if (!this.#isEventQueuePersistenceEnabled || !this.state.eventQueue) {
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
471
|
-
this.#clearQueuedEvents();
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
for (const [messageId, queuedEvent] of Object.entries(this.state.eventQueue)) {
|
|
475
|
-
if (!isAnalyticsQueuedEvent(queuedEvent) ||
|
|
476
|
-
queuedEvent.messageId !== messageId) {
|
|
477
|
-
log('Dropping invalid queued analytics event', { messageId });
|
|
478
|
-
this.#removeQueuedEvent(messageId);
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
this.#sendQueuedEvent(queuedEvent);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* Remove a queued analytics event.
|
|
486
|
-
*
|
|
487
|
-
* @param messageId - The queued event message ID.
|
|
488
|
-
*/
|
|
489
|
-
#removeQueuedEvent(messageId) {
|
|
490
|
-
const currentEventQueue = this.state.eventQueue;
|
|
491
|
-
if (!currentEventQueue ||
|
|
492
|
-
!Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)) {
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;
|
|
496
|
-
this.update((state) => {
|
|
497
|
-
state.eventQueue = eventQueue;
|
|
498
|
-
});
|
|
499
|
-
}
|
|
500
|
-
/**
|
|
501
|
-
* Clear all queued analytics events.
|
|
502
|
-
*/
|
|
503
|
-
#clearQueuedEvents() {
|
|
504
|
-
if (!this.state.eventQueue ||
|
|
505
|
-
Object.keys(this.state.eventQueue).length === 0) {
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
this.update((state) => {
|
|
509
|
-
state.eventQueue = {};
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
/**
|
|
513
|
-
* Add an event to the pre-consent queue without delivering it.
|
|
514
|
-
*
|
|
515
|
-
* @param queuedEvent - The event to hold until the user opts in.
|
|
516
|
-
*/
|
|
517
|
-
#enqueuePreConsentEvent(queuedEvent) {
|
|
518
|
-
const preConsentEventQueue = {
|
|
519
|
-
...(this.state.preConsentEventQueue ?? {}),
|
|
520
|
-
[queuedEvent.messageId]: queuedEvent,
|
|
521
|
-
};
|
|
522
|
-
this.update((state) => {
|
|
523
|
-
state.preConsentEventQueue = preConsentEventQueue;
|
|
524
|
-
});
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Replay queued pre-consent events through the delivery path.
|
|
528
|
-
*
|
|
529
|
-
* Only called by {@link #reconcilePreConsentEvents}, which guarantees the
|
|
530
|
-
* pre-consent queue is enabled and that the user is opted in. The queue is
|
|
531
|
-
* cleared before replaying so events cannot be re-queued or replayed twice.
|
|
532
|
-
*
|
|
533
|
-
* @param queue - The pre-consent event queue to replay.
|
|
534
|
-
*/
|
|
535
|
-
#replayPreConsentEvents(queue) {
|
|
536
|
-
this.#clearPreConsentEvents();
|
|
537
|
-
for (const [messageId, queuedEvent] of Object.entries(queue)) {
|
|
538
|
-
if (!isAnalyticsQueuedEvent(queuedEvent) ||
|
|
539
|
-
queuedEvent.messageId !== messageId) {
|
|
540
|
-
log('Dropping invalid queued pre-consent analytics event', {
|
|
541
|
-
messageId,
|
|
542
|
-
});
|
|
543
|
-
continue;
|
|
544
|
-
}
|
|
545
|
-
const eventToReplay = this.#enrichPreConsentEvent(queuedEvent);
|
|
546
|
-
if (this.#isEventQueuePersistenceEnabled) {
|
|
547
|
-
this.#enqueueEvent(eventToReplay);
|
|
548
|
-
}
|
|
549
|
-
else {
|
|
550
|
-
this.#sendQueuedEvent(eventToReplay);
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
/**
|
|
555
|
-
* Enrich a pre-consent event with the geolocation resolved on opt-in.
|
|
556
|
-
*
|
|
557
|
-
* Pre-consent events are captured while geolocation is not yet resolved, so
|
|
558
|
-
* they are re-enriched here as they replay. Anonymous track payloads are left
|
|
559
|
-
* untouched, since they must never carry location.
|
|
560
|
-
*
|
|
561
|
-
* @param queuedEvent - The queued pre-consent event.
|
|
562
|
-
* @returns The event with its context enriched, or the event unchanged when
|
|
563
|
-
* enrichment does not apply.
|
|
564
|
-
*/
|
|
565
|
-
#enrichPreConsentEvent(queuedEvent) {
|
|
566
|
-
if (queuedEvent.type === 'track' &&
|
|
567
|
-
queuedEvent.properties?.anonymous === true) {
|
|
568
|
-
return queuedEvent;
|
|
569
|
-
}
|
|
570
|
-
const context = this.#withLocationContext(queuedEvent.context);
|
|
571
|
-
return {
|
|
572
|
-
...queuedEvent,
|
|
573
|
-
...(context === undefined ? {} : { context }),
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
/**
|
|
577
|
-
* Clear all queued pre-consent events.
|
|
578
|
-
*/
|
|
579
|
-
#clearPreConsentEvents() {
|
|
580
|
-
if (!this.state.preConsentEventQueue) {
|
|
581
|
-
return;
|
|
582
|
-
}
|
|
583
|
-
this.update((state) => {
|
|
584
|
-
state.preConsentEventQueue = {};
|
|
585
|
-
});
|
|
586
|
-
}
|
|
587
|
-
/**
|
|
588
|
-
* Reconcile the pre-consent queue on initialization.
|
|
589
|
-
*
|
|
590
|
-
* The queue should normally be empty unless the user is still undecided. This
|
|
591
|
-
* handles the rare cases where a consent decision was persisted but the queue
|
|
592
|
-
* was not flushed/cleared (e.g. an interrupted shutdown): replay it if the
|
|
593
|
-
* user is opted in, or clear it if they opted out.
|
|
594
|
-
*
|
|
595
|
-
* If the pre-consent queue is disabled, any stale persisted entries (e.g. from
|
|
596
|
-
* a previous session where it was enabled) are dropped so they can never be
|
|
597
|
-
* replayed.
|
|
598
|
-
*/
|
|
599
|
-
#reconcilePreConsentEvents() {
|
|
600
|
-
const queue = this.state.preConsentEventQueue;
|
|
601
|
-
if (!queue) {
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
if (!this.#isPreConsentQueueEnabled) {
|
|
605
|
-
this.#clearPreConsentEvents();
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
if (this.state.optedIn) {
|
|
609
|
-
this.#replayPreConsentEvents(queue);
|
|
610
|
-
}
|
|
611
|
-
else if (this.state.consentDecisionMade) {
|
|
612
|
-
this.#clearPreConsentEvents();
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
/**
|
|
616
|
-
* Track an analytics event.
|
|
617
|
-
*
|
|
618
|
-
* Events are only tracked if analytics is enabled.
|
|
619
|
-
*
|
|
620
|
-
* @param event - Analytics event with properties and sensitive properties
|
|
621
|
-
* @param context - Optional platform-specific context forwarded to the platform adapter.
|
|
622
|
-
*/
|
|
623
|
-
trackEvent(event, context) {
|
|
624
|
-
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
625
|
-
// While the user is undecided, fall through so the event is processed and
|
|
626
|
-
// captured in the pre-consent queue (see #sendOrQueueTrackEvent) to be
|
|
627
|
-
// replayed if they later opt in. Otherwise (opted out, or pre-consent
|
|
628
|
-
// queue disabled) drop it.
|
|
629
|
-
const shouldQueuePreConsent = this.#isPreConsentQueueEnabled && !this.state.consentDecisionMade;
|
|
630
|
-
if (!shouldQueuePreConsent) {
|
|
631
|
-
return;
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
// if event does not have properties, send event without properties
|
|
635
|
-
// and return to prevent any additional processing
|
|
636
|
-
if (!event.hasProperties) {
|
|
637
|
-
this.#sendOrQueueTrackEvent(event.name, undefined, this.#withLocationContext(context));
|
|
638
|
-
return;
|
|
639
|
-
}
|
|
640
|
-
// Track regular properties first if anonymous events feature is enabled
|
|
641
|
-
if (this.#isAnonymousEventsFeatureEnabled) {
|
|
642
|
-
// Note: Even if regular properties object is empty, we still send it to ensure
|
|
643
|
-
// an event with user ID is tracked.
|
|
644
|
-
this.#sendOrQueueTrackEvent(event.name, {
|
|
645
|
-
...event.properties,
|
|
646
|
-
}, this.#withLocationContext(context));
|
|
647
|
-
}
|
|
648
|
-
const hasSensitiveProperties = Object.keys(event.sensitiveProperties).length > 0;
|
|
649
|
-
if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {
|
|
650
|
-
this.#sendOrQueueTrackEvent(event.name, {
|
|
651
|
-
...event.properties,
|
|
652
|
-
...event.sensitiveProperties,
|
|
653
|
-
...(hasSensitiveProperties && { anonymous: true }),
|
|
654
|
-
},
|
|
655
|
-
// When the anonymous events feature is enabled, this payload is the
|
|
656
|
-
// anonymous one and must carry no geolocation. When the feature is
|
|
657
|
-
// disabled, this is the single identified payload, so it is enriched.
|
|
658
|
-
this.#isAnonymousEventsFeatureEnabled
|
|
659
|
-
? context
|
|
660
|
-
: this.#withLocationContext(context));
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
/**
|
|
664
|
-
* Identify a user for analytics.
|
|
665
|
-
*
|
|
666
|
-
* @param traits - User traits/properties
|
|
667
|
-
* @param context - Optional platform-specific context forwarded to the platform adapter.
|
|
668
|
-
*/
|
|
669
|
-
identify(traits, context) {
|
|
670
|
-
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
671
|
-
return;
|
|
672
|
-
}
|
|
673
|
-
// Delegate to platform adapter using the current analytics ID
|
|
674
|
-
this.#sendOrQueueIdentifyEvent(this.state.analyticsId, traits, this.#withLocationContext(context));
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Track a page or screen view.
|
|
678
|
-
*
|
|
679
|
-
* @param name - The identifier/name of the page or screen being viewed (e.g., "home", "settings", "wallet")
|
|
680
|
-
* @param properties - Optional properties associated with the view
|
|
681
|
-
* @param context - Optional platform-specific context forwarded to the platform adapter.
|
|
682
|
-
*/
|
|
683
|
-
trackView(name, properties, context) {
|
|
684
|
-
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
687
|
-
// Delegate to platform adapter
|
|
688
|
-
this.#sendOrQueueViewEvent(name, properties, this.#withLocationContext(context));
|
|
689
|
-
}
|
|
690
|
-
/**
|
|
691
|
-
* Opt in to analytics.
|
|
692
|
-
*
|
|
693
|
-
* Records that a consent decision has been made and replays any events that
|
|
694
|
-
* were queued while the user was undecided.
|
|
695
|
-
*
|
|
696
|
-
* When geolocation enrichment is enabled, geolocation is resolved here (once
|
|
697
|
-
* the user has consented) and awaited before the queued events are replayed,
|
|
698
|
-
* so those events are enriched with the resolved location as they are sent.
|
|
699
|
-
*
|
|
700
|
-
* @returns A promise that resolves once opt-in processing has completed.
|
|
701
|
-
*/
|
|
702
|
-
async optIn() {
|
|
703
|
-
this.update((state) => {
|
|
704
|
-
state.optedIn = true;
|
|
705
|
-
state.consentDecisionMade = true;
|
|
706
|
-
});
|
|
707
|
-
// Now that the user has consented, resolve geolocation (once) and wait for
|
|
708
|
-
// it so the queued pre-consent events can be enriched as they replay.
|
|
709
|
-
await this.#maybeResolveLocation();
|
|
710
|
-
// Reconcile against the current state rather than replaying blindly: the
|
|
711
|
-
// consent decision may have changed while geolocation was resolving (e.g.
|
|
712
|
-
// resetConsentDecision ran during the await), and preserved pre-consent
|
|
713
|
-
// events must not be delivered once the user is no longer opted in.
|
|
714
|
-
this.#reconcilePreConsentEvents();
|
|
715
|
-
}
|
|
716
|
-
/**
|
|
717
|
-
* Opt out of analytics.
|
|
718
|
-
*
|
|
719
|
-
* Records that a consent decision has been made and discards any persisted
|
|
720
|
-
* events so nothing captured before the decision is ever delivered.
|
|
721
|
-
*/
|
|
722
|
-
optOut() {
|
|
723
|
-
this.update((state) => {
|
|
724
|
-
state.optedIn = false;
|
|
725
|
-
state.consentDecisionMade = true;
|
|
726
|
-
});
|
|
727
|
-
this.#clearQueuedEvents();
|
|
728
|
-
this.#clearPreConsentEvents();
|
|
729
|
-
}
|
|
730
|
-
/**
|
|
731
|
-
* Reset the consent decision back to undecided.
|
|
732
|
-
*
|
|
733
|
-
* Intended for client flows that restart onboarding. Clears the opt-in
|
|
734
|
-
* preference and discards the delivery queue, but preserves any pre-consent
|
|
735
|
-
* events so they can still be replayed if the user opts in again. The user is
|
|
736
|
-
* treated as undecided again.
|
|
737
|
-
*/
|
|
738
|
-
resetConsentDecision() {
|
|
739
|
-
this.update((state) => {
|
|
740
|
-
state.optedIn = false;
|
|
741
|
-
state.consentDecisionMade = false;
|
|
742
|
-
});
|
|
743
|
-
this.#clearQueuedEvents();
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
//# sourceMappingURL=AnalyticsController.js.map
|