@metamask-previews/analytics-controller 3.2.0-preview-82a2b9842 → 3.2.0-preview-85a915769
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
CHANGED
|
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **BREAKING:** Wire up `#fetchEventsConfig` in `AnalyticsController.init` to read `eventsConfig` from `ConfigRegistryController:getState` and update in-memory event-purpose classification when the version differs; subscribes to `ConfigRegistryController:stateChanged` for within-session refresh; adds `@metamask/config-registry-controller` `^4.0.0` as a dependency and requires `ConfigRegistryController:getState` in `AnalyticsControllerMessenger`'s `AllowedActions` and `ConfigRegistryController:stateChanged` in its `AllowedEvents` ([#10448](https://github.com/MetaMask/core/pull/10448))
|
|
13
|
+
|
|
10
14
|
### Changed
|
|
11
15
|
|
|
12
16
|
- Bump `lodash-es` from `^4.17.21` to `^4.18.1` ([#10447](https://github.com/MetaMask/core/pull/10447))
|
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@ The AnalyticsController provides a unified interface for tracking analytics even
|
|
|
34
34
|
3. **Subscribe to state changes**: Persist changes to isolated storage
|
|
35
35
|
4. **Persist to isolated storage**: Keep analytics settings separate from main state (protects against state corruption)
|
|
36
36
|
|
|
37
|
-
`eventsConfig.events` maps event names to one or both `AnalyticsPurpose` values (`product` and `marketing`). Unlisted names default to product-only.
|
|
37
|
+
`eventsConfig.events` maps event names to one or both `AnalyticsPurpose` values (`product` and `marketing`). Unlisted names default to product-only. The config is loaded from `ConfigRegistryController` state during `init` and refreshed automatically when `ConfigRegistryController` state changes.
|
|
38
38
|
|
|
39
39
|
Each `track` and `view` payload is emitted once when at least one eligible purpose is opted in. A dual-purpose event is still emitted once when both consents are enabled. Its allowed purposes are stamped using Segment's consent context:
|
|
40
40
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ControllerGetStateAction, ControllerStateChangeEvent } from '@metamask/base-controller';
|
|
2
2
|
import { BaseController } from '@metamask/base-controller';
|
|
3
|
+
import type { ConfigRegistryControllerGetStateAction, ConfigRegistryControllerStateChangedEvent } from '@metamask/config-registry-controller';
|
|
3
4
|
import type { GeolocationControllerGetGeolocationDataAction } from '@metamask/geolocation-controller';
|
|
4
5
|
import type { Messenger } from '@metamask/messenger';
|
|
5
6
|
import type { Json } from '@metamask/utils';
|
|
@@ -67,10 +68,8 @@ export type AnalyticsControllerState = {
|
|
|
67
68
|
marketingConsentDecisionMade?: boolean;
|
|
68
69
|
/**
|
|
69
70
|
* Cached event-purpose configuration. Optional for backward compatibility.
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* that up, classification uses the persisted config. Unlisted names are
|
|
73
|
-
* product-only.
|
|
71
|
+
* Loaded from ConfigRegistryController state during init. Unlisted events
|
|
72
|
+
* default to product-only.
|
|
74
73
|
*/
|
|
75
74
|
eventsConfig?: AnalyticsEventsConfig;
|
|
76
75
|
/**
|
|
@@ -206,7 +205,7 @@ export type AnalyticsControllerActions = AnalyticsControllerGetStateAction | Ana
|
|
|
206
205
|
/**
|
|
207
206
|
* Actions from other messengers that {@link AnalyticsControllerMessenger} calls.
|
|
208
207
|
*/
|
|
209
|
-
type AllowedActions = GeolocationControllerGetGeolocationDataAction;
|
|
208
|
+
type AllowedActions = GeolocationControllerGetGeolocationDataAction | ConfigRegistryControllerGetStateAction;
|
|
210
209
|
/**
|
|
211
210
|
* Event emitted when the state of the {@link AnalyticsController} changes.
|
|
212
211
|
*/
|
|
@@ -218,7 +217,7 @@ export type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;
|
|
|
218
217
|
/**
|
|
219
218
|
* Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.
|
|
220
219
|
*/
|
|
221
|
-
type AllowedEvents =
|
|
220
|
+
type AllowedEvents = ConfigRegistryControllerStateChangedEvent;
|
|
222
221
|
/**
|
|
223
222
|
* The messenger restricted to actions and events accessed by
|
|
224
223
|
* {@link AnalyticsController}.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsController.d.ts","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,6CAA6C,EAE9C,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAI5C,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,8CAA8C,CAAC;AAGrG,OAAO,KAAK,EACV,wBAAwB,EAExB,gBAAgB,EAChB,wBAAwB,EAExB,mBAAmB,EACnB,sBAAsB,EACvB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAEV,qCAAqC,EACrC,6BAA6B,EAC7B,6BAA6B,EAC7B,uBAAuB,EACvB,8BAA8B,EAC/B,MAAM,0BAA0B,CAAC;AAKlC;;;;GAIG;AACH,eAAO,MAAM,cAAc,wBAAwB,CAAC;AAEpD;;;;;;;;GAQG;AACH,eAAO,MAAM,sBAAsB,QAAsB,CAAC;AAE1D;;GAEG;AACH,eAAO,MAAM,gBAAgB;aAC3B,OAAO,EAAE,SAAS;aAClB,SAAS,EAAE,WAAW;CACd,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAC1B,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,OAAO,gBAAgB,CAAC,CAAC;AAE3D;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE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;OAMG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAQtC;IAED;;;;;OAKG;IACH,iBAAiB,IAAI,IAAI,CAQxB;IAED;;;;OAIG;IACH,6BAA6B,IAAI,IAAI,CAQpC;IAED;;;;;;;;;;OAUG;IACH,4BAA4B,CAAC,yBAAyB,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAI3E;CACF"}
|
|
@@ -439,6 +439,17 @@ export class AnalyticsController extends BaseController {
|
|
|
439
439
|
}
|
|
440
440
|
}
|
|
441
441
|
await this.#fetchEventsConfig();
|
|
442
|
+
try {
|
|
443
|
+
this.messenger.subscribe('ConfigRegistryController:stateChanged', (newState) => {
|
|
444
|
+
if (newState.configs.eventsConfig?.version !== this.#eventsConfigVersion) {
|
|
445
|
+
this.#fetchEventsConfig().catch(
|
|
446
|
+
/* istanbul ignore next */ () => undefined);
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
// ConfigRegistryController may not be registered in all environments.
|
|
452
|
+
}
|
|
442
453
|
// Resolve geolocation only when the user is already opted in to product or
|
|
443
454
|
// marketing analytics. For undecided or opted-out users it is deferred to
|
|
444
455
|
// {@link optIn} / {@link optInToMarketing}. Awaited so that an already-opted-in
|
|
@@ -548,13 +559,37 @@ export class AnalyticsController extends BaseController {
|
|
|
548
559
|
};
|
|
549
560
|
}
|
|
550
561
|
/**
|
|
551
|
-
* Load event-purpose configuration.
|
|
552
|
-
*
|
|
553
|
-
* Phase 1 stub. Persisted configuration remains authoritative until a remote
|
|
554
|
-
* source is wired up.
|
|
562
|
+
* Load event-purpose configuration from ConfigRegistryController state.
|
|
563
|
+
* Updates in-memory purposes map and persisted state when the version differs.
|
|
555
564
|
*/
|
|
556
565
|
async #fetchEventsConfig() {
|
|
557
|
-
|
|
566
|
+
let eventsConfigState;
|
|
567
|
+
try {
|
|
568
|
+
eventsConfigState = this.messenger.call('ConfigRegistryController:getState');
|
|
569
|
+
}
|
|
570
|
+
catch {
|
|
571
|
+
// ConfigRegistryController may not be registered in all environments.
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
const remoteEventsConfig = eventsConfigState.configs.eventsConfig;
|
|
575
|
+
if (!remoteEventsConfig) {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
const candidate = {
|
|
579
|
+
schemaVersion: remoteEventsConfig.schemaVersion,
|
|
580
|
+
version: remoteEventsConfig.version,
|
|
581
|
+
timestamp: remoteEventsConfig.timestamp,
|
|
582
|
+
events: remoteEventsConfig.events,
|
|
583
|
+
};
|
|
584
|
+
if (!isAnalyticsEventsConfig(candidate) ||
|
|
585
|
+
candidate.version === this.#eventsConfigVersion) {
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
this.#eventPurposes = new Map(Object.entries(candidate.events));
|
|
589
|
+
this.#eventsConfigVersion = candidate.version;
|
|
590
|
+
this.update((state) => {
|
|
591
|
+
state.eventsConfig = candidate;
|
|
592
|
+
});
|
|
558
593
|
}
|
|
559
594
|
#purposesFromName(name) {
|
|
560
595
|
return [...(this.#eventPurposes.get(name) ?? [AnalyticsPurpose.Product])];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsController.js","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAO3D,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAGlC,OAAO,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EAAE,aAAa,IAAI,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAkB5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAC;AAE9D,kBAAkB;AAElB;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,qBA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C3B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;YACjC,KAAK,CAAC,4BAA4B,GAAG,KAAK,CAAC;YAC3C,KAAK,CAAC,yBAAyB,GAAG,IAAI,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAED;;;;;;;;;;OAUG;IACH,4BAA4B,CAAC,yBAAwC;QACnE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,yBAAyB,GAAG,yBAAyB,CAAC;QAC9D,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n GeolocationControllerGetGeolocationDataAction,\n GeolocationData,\n} from '@metamask/geolocation-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport { cloneDeep } from 'lodash-es';\nimport { v4 as uuid } from 'uuid';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types.js';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator.js';\nimport { projectLogger as log } from './AnalyticsLogger.js';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsDeliveryOptions,\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsLocationContext,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types.js';\nimport type {\n AnalyticsEventFragment,\n AnalyticsEventFragmentFinalizeOptions,\n AnalyticsEventFragmentOptions,\n AnalyticsEventFragmentPayload,\n AnalyticsEventFragments,\n ReadonlyAnalyticsEventFragment,\n} from './EventFragment.types.js';\nimport { analyticsControllerSelectors } from './selectors.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n/**\n * Maximum age of a persisted event fragment, measured from\n * {@link AnalyticsEventFragment.lastUpdated}.\n *\n * Fragments older than this are discarded during {@link AnalyticsController.init}\n * without emitting a success or failure event. Confirmation journeys that span a\n * restart are expected to resume within this window; abandoned ones must not keep\n * `properties` or `sensitiveProperties` in storage indefinitely.\n */\nexport const EVENT_FRAGMENT_MAX_AGE = 24 * 60 * 60 * 1000;\n\n/**\n * Purposes for which an analytics payload can be used.\n */\nexport const AnalyticsPurpose = {\n Product: 'product',\n Marketing: 'marketing',\n} as const;\n\n/**\n * A purpose for which an analytics payload can be used.\n */\nexport type AnalyticsPurpose =\n (typeof AnalyticsPurpose)[keyof typeof AnalyticsPurpose];\n\n/**\n * Persisted event-purpose classification fetched from config registry.\n */\nexport type AnalyticsEventsConfig = {\n schemaVersion: string;\n version: string;\n timestamp: number;\n events: Record<string, AnalyticsPurpose[]>;\n};\n\n/**\n * Persisted queues on {@link AnalyticsControllerState}.\n */\nconst AnalyticsQueue = {\n EventQueue: 'eventQueue',\n PreConsentEventQueue: 'preConsentEventQueue',\n} as const;\n\ntype AnalyticsQueue = (typeof AnalyticsQueue)[keyof typeof AnalyticsQueue];\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * Whether the user has opted in to marketing analytics.\n *\n * Independent of {@link optedIn}. Named events in the remote marketing list\n * are governed only by this flag. Optional for backward compatibility with\n * persisted state that predates this field. Missing values are treated as\n * `false`.\n */\n optedInToMarketing?: boolean;\n\n /**\n * Whether the user has made a marketing consent decision (opted in or opted\n * out). Mirrors {@link consentDecisionMade} for the marketing purpose.\n * Optional for backward compatibility. Missing values are treated as `false`.\n */\n marketingConsentDecisionMade?: boolean;\n\n /**\n * Cached event-purpose configuration. Optional for backward compatibility.\n *\n * Phase 1 does not load this from a remote source. Until a later phase wires\n * that up, classification uses the persisted config. Unlisted names are\n * product-only.\n */\n eventsConfig?: AnalyticsEventsConfig;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n\n /**\n * Persisted queue of analytics events waiting for delivery acknowledgement.\n * This is only used when event queue persistence is enabled.\n */\n eventQueue?: Record<string, Json>;\n\n /**\n * Whether the user has made a consent decision (opted in or opted out).\n *\n * This distinguishes the \"undecided\" state (e.g. during onboarding, before\n * the user has answered the analytics prompt) from an explicit opt-out.\n * Defaults to `false` and is set to `true` by {@link AnalyticsController.optIn}\n * or {@link AnalyticsController.optOut}, and back to `false` by\n * {@link AnalyticsController.resetConsentDecision}. Optional for backward\n * compatibility with persisted state that predates this field.\n */\n consentDecisionMade?: boolean;\n\n /**\n * Persisted queue of track events ({@link AnalyticsQueuedTrackEvent}) captured\n * while the user is undecided (no consent decision made yet). Replayed on\n * opt-in and cleared on opt-out.\n * Preserved across {@link AnalyticsController.resetConsentDecision} so onboarding\n * restarts do not drop install-time events.\n * This is only used when the pre-consent queue is enabled.\n */\n preConsentEventQueue?: Record<string, Json>;\n\n /**\n * Persisted event fragments ({@link AnalyticsEventFragment}) keyed by\n * fragment ID. Fragments accumulate properties across a user journey and are\n * removed when the journey is finalized or deleted. Fragments that set\n * `persist: true` can survive {@link AnalyticsController.init}, but only\n * while younger than {@link EVENT_FRAGMENT_MAX_AGE}.\n * This is only used when the event fragments feature is enabled.\n */\n eventFragments?: AnalyticsEventFragments;\n\n /**\n * Marketing campaign cookie ID set when the user arrives via a marketing\n * campaign. Cleared automatically when the user calls\n * {@link AnalyticsController.optOutOfMarketing} or\n * {@link AnalyticsController.resetMarketingConsentDecision}. Optional for backward\n * compatibility with persisted state that predates this field.\n */\n marketingCampaignCookieId?: string | null;\n};\n\n/**\n * Event types supported by the persisted analytics event queue.\n */\nexport type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';\n\n/**\n * Base persisted event queue entry.\n */\nexport type AnalyticsQueuedEventBase = {\n /**\n * Event type used to replay the payload with the platform adapter.\n */\n type: AnalyticsQueuedEventType;\n\n /**\n * Stable identifier for the analytics payload.\n */\n messageId: string;\n\n /**\n * Original payload timestamp serialized for persistence.\n */\n timestamp: string;\n\n /**\n * Event purposes captured with the payload, before user consent is applied.\n */\n eventPurposes?: AnalyticsPurpose[];\n\n /**\n * Events config version used to classify the payload.\n */\n eventsConfigVersion?: string;\n};\n\n/**\n * Persisted track event queue entry.\n */\nexport type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {\n type: 'track';\n eventName: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted identify event queue entry.\n */\nexport type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {\n type: 'identify';\n userId: string;\n traits?: AnalyticsUserTraits;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted view event queue entry.\n */\nexport type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {\n type: 'view';\n name: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted analytics event queue entry.\n */\nexport type AnalyticsQueuedEvent =\n | AnalyticsQueuedTrackEvent\n | AnalyticsQueuedIdentifyEvent\n | AnalyticsQueuedViewEvent;\n\n/**\n * Persisted analytics event queue keyed by message ID.\n */\nexport type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n consentDecisionMade: false,\n optedInToMarketing: false,\n marketingConsentDecisionMade: false,\n marketingCampaignCookieId: null,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Both `optedIn` and `analyticsId` are persisted (`persist: true`).\n * The platform must supply a valid UUIDv4 `analyticsId` on first run.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n optedInToMarketing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n marketingConsentDecisionMade: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n eventsConfig: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n eventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n consentDecisionMade: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n preConsentEventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n eventFragments: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n marketingCampaignCookieId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n 'resetConsentDecision',\n 'optInToMarketing',\n 'optOutOfMarketing',\n 'resetMarketingConsentDecision',\n 'setMarketingCampaignCookieId',\n 'createEventFragment',\n 'upsertEventFragment',\n 'updateEventFragment',\n 'getEventFragmentById',\n 'deleteEventFragment',\n 'finalizeEventFragment',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions = GeolocationControllerGetGeolocationDataAction;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating the ID on first run.\n * It is then persisted with controller state when using a persisted store.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n\n /**\n * Whether analytics event queue persistence is enabled.\n *\n * When enabled, AnalyticsController persists each platform adapter payload\n * until the adapter reports successful delivery.\n *\n * @default false\n */\n isEventQueuePersistenceEnabled?: boolean;\n\n /**\n * Whether the pre-consent event queue is enabled.\n *\n * When enabled, track events received while the user is undecided\n * (no consent decision made yet) are persisted and replayed on opt-in,\n * or dropped on opt-out. When disabled, such events are dropped immediately,\n * preserving the legacy behavior.\n *\n * @default false\n */\n isPreConsentQueueEnabled?: boolean;\n\n /**\n * Whether geolocation enrichment is enabled.\n *\n * When enabled, {@link AnalyticsController.init} resolves the user's\n * country, region, and timezone via `GeolocationController:getGeolocationData`\n * and attaches them to `context.location` on non-anonymous payloads.\n * Compositions must register that action when this is enabled. When disabled,\n * the controller never calls the geolocation action and events are delivered\n * without location.\n *\n * @default false\n */\n isGeolocationEnabled?: boolean;\n\n /**\n * Whether the event fragments feature is enabled.\n *\n * When enabled, clients can accumulate analytics properties across a user\n * journey with {@link AnalyticsController.createEventFragment} and friends,\n * as long as the consent state allows analytics to be captured. When\n * disabled, every fragment method is a logged no-op and no fragment is ever\n * written to state.\n *\n * @default false\n */\n isEventFragmentsEnabled?: boolean;\n};\n\n/**\n * Returns whether a value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a record.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isAnalyticsPurpose(value: unknown): value is AnalyticsPurpose {\n return (\n value === AnalyticsPurpose.Product || value === AnalyticsPurpose.Marketing\n );\n}\n\nfunction isEventPurposesRecord(\n value: unknown,\n): value is Record<string, AnalyticsPurpose[]> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (purposes) =>\n Array.isArray(purposes) &&\n purposes.length > 0 &&\n purposes.every(isAnalyticsPurpose),\n )\n );\n}\n\nfunction isAnalyticsEventsConfig(\n value: unknown,\n): value is AnalyticsEventsConfig {\n return (\n isRecord(value) &&\n typeof value.schemaVersion === 'string' &&\n typeof value.version === 'string' &&\n typeof value.timestamp === 'number' &&\n isEventPurposesRecord(value.events)\n );\n}\n\n/**\n * Returns whether a JSON value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a JSON record.\n */\nfunction isJsonRecord(value: Json | undefined): value is Record<string, Json> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Builds the analytics location context from geolocation data, keeping only\n * the fields the geolocation API was able to determine.\n *\n * @param geolocation - The geolocation data to convert.\n * @returns The location context, or `undefined` when no field is known.\n */\nfunction buildLocationContext(\n geolocation: GeolocationData,\n): AnalyticsLocationContext | undefined {\n const locationContext: AnalyticsLocationContext = {\n ...(geolocation.country === null\n ? {}\n : { country_code: geolocation.country }),\n ...(geolocation.region === null ? {} : { region: geolocation.region }),\n ...(geolocation.timezone === null\n ? {}\n : { timezone: geolocation.timezone }),\n };\n\n return Object.keys(locationContext).length === 0\n ? undefined\n : locationContext;\n}\n\n/**\n * Returns whether a value is a valid persisted analytics event.\n *\n * @param value - The value to check.\n * @returns True if the value is a queued analytics event.\n */\nfunction isAnalyticsQueuedEvent(value: unknown): value is AnalyticsQueuedEvent {\n if (!isRecord(value)) {\n return false;\n }\n\n if (\n typeof value.messageId !== 'string' ||\n typeof value.timestamp !== 'string' ||\n (value.eventPurposes !== undefined &&\n (!Array.isArray(value.eventPurposes) ||\n !value.eventPurposes.every(isAnalyticsPurpose))) ||\n (value.eventsConfigVersion !== undefined &&\n typeof value.eventsConfigVersion !== 'string')\n ) {\n return false;\n }\n\n if (value.type === 'track') {\n return (\n typeof value.eventName === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'identify') {\n return (\n typeof value.userId === 'string' &&\n (value.traits === undefined || isRecord(value.traits)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'view') {\n return (\n typeof value.name === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n return false;\n}\n\n/**\n * Returns whether a value is a valid persisted event fragment.\n *\n * @param value - The value to check.\n * @returns True if the value is an event fragment.\n */\nfunction isAnalyticsEventFragment(\n value: unknown,\n): value is AnalyticsEventFragment {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n typeof value.id === 'string' &&\n typeof value.createdAt === 'number' &&\n typeof value.lastUpdated === 'number' &&\n isRecord(value.properties) &&\n isRecord(value.sensitiveProperties) &&\n (value.initialEvent === undefined ||\n typeof value.initialEvent === 'string') &&\n (value.successEvent === undefined ||\n typeof value.successEvent === 'string') &&\n (value.failureEvent === undefined ||\n typeof value.failureEvent === 'string') &&\n (value.eventPurposes === undefined ||\n isEventPurposesRecord(value.eventPurposes)) &&\n (value.eventsConfigVersion === undefined ||\n typeof value.eventsConfigVersion === 'string') &&\n (value.context === undefined || isRecord(value.context)) &&\n (value.persist === undefined || typeof value.persist === 'boolean')\n );\n}\n\n/**\n * Merges a payload into an event fragment.\n *\n * `properties`, `sensitiveProperties` and `context` are merged one level deep,\n * so a key written twice is replaced rather than combined. This keeps array\n * values predictable: writing a shorter array replaces the longer one instead\n * of leaving stale trailing entries behind.\n *\n * @param fragment - The fragment to merge into.\n * @param payload - The payload to merge.\n * @returns A new fragment with the payload applied.\n */\nfunction mergeEventFragment(\n fragment: AnalyticsEventFragment,\n payload: AnalyticsEventFragmentPayload,\n): AnalyticsEventFragment {\n const context = mergeEventFragmentContext(fragment.context, payload.context);\n\n return {\n ...fragment,\n properties: { ...fragment.properties, ...(payload.properties ?? {}) },\n sensitiveProperties: {\n ...fragment.sensitiveProperties,\n ...(payload.sensitiveProperties ?? {}),\n },\n ...(context === undefined ? {} : { context }),\n lastUpdated: Date.now(),\n };\n}\n\n/**\n * Merges two optional analytics contexts.\n *\n * @param base - The context to merge into.\n * @param override - The context whose fields win. When omitted, `base` is kept.\n * @returns The merged context, or `undefined` when both sides are unset.\n */\nfunction mergeEventFragmentContext(\n base: AnalyticsContext | undefined,\n override: AnalyticsContext | undefined,\n): AnalyticsContext | undefined {\n if (override === undefined) {\n return base;\n }\n\n return { ...(base ?? {}), ...override };\n}\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * The controller persists `optedIn` and `analyticsId` when composed with a persisted\n * store. The platform must supply a valid `analyticsId` on first launch.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n readonly #isEventQueuePersistenceEnabled: boolean;\n\n readonly #isPreConsentQueueEnabled: boolean;\n\n readonly #isGeolocationEnabled: boolean;\n\n readonly #isEventFragmentsEnabled: boolean;\n\n /**\n * In-memory event-purpose lookup from persisted state.\n */\n readonly #eventPurposes: Map<string, AnalyticsPurpose[]>;\n\n readonly #eventsConfigVersion: string | undefined;\n\n /**\n * The in-flight (or settled) initialization promise. Set on the first\n * {@link init} call and returned by subsequent calls so overlapping callers\n * await the same work rather than observing a premature completion.\n */\n #initPromise: Promise<void> | undefined;\n\n /**\n * The in-flight (or settled) geolocation resolution, if any. Its presence\n * marks that resolution has been started, so it runs at most once.\n */\n #locationResolvePromise: Promise<void> | undefined;\n\n #locationContext: AnalyticsLocationContext | undefined;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled\n * @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled\n * @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled\n * @param options.isEventFragmentsEnabled - Whether the event fragments feature is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n isEventQueuePersistenceEnabled = false,\n isPreConsentQueueEnabled = false,\n isGeolocationEnabled = false,\n isEventFragmentsEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n const eventsConfig = isAnalyticsEventsConfig(initialState.eventsConfig)\n ? initialState.eventsConfig\n : undefined;\n if (eventsConfig === undefined) {\n delete initialState.eventsConfig;\n } else {\n initialState.eventsConfig = eventsConfig;\n }\n\n validateAnalyticsControllerState(\n initialState,\n platformAdapter.skipUUIDv4Check === true,\n );\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#isEventQueuePersistenceEnabled = isEventQueuePersistenceEnabled;\n this.#isPreConsentQueueEnabled = isPreConsentQueueEnabled;\n this.#isGeolocationEnabled = isGeolocationEnabled;\n this.#isEventFragmentsEnabled = isEventFragmentsEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initPromise = undefined;\n this.#locationResolvePromise = undefined;\n this.#eventPurposes = new Map(Object.entries(eventsConfig?.events ?? {}));\n this.#eventsConfigVersion = eventsConfig?.version;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n optedInToMarketing: this.state.optedInToMarketing === true,\n marketingConsentDecisionMade:\n this.state.marketingConsentDecisionMade === true,\n consentDecisionMade: this.state.consentDecisionMade,\n analyticsId: this.state.analyticsId,\n eventQueuePersistenceEnabled: this.#isEventQueuePersistenceEnabled,\n preConsentQueueEnabled: this.#isPreConsentQueueEnabled,\n geolocationEnabled: this.#isGeolocationEnabled,\n eventFragmentsEnabled: this.#isEventFragmentsEnabled,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's\n * onSetupCompleted lifecycle hook and replaying any queued events. This\n * method must be called after construction to complete the setup process.\n *\n * When geolocation enrichment is enabled (`isGeolocationEnabled`), geolocation\n * is resolved only for a user who is already opted in to product or marketing\n * analytics. For users undecided or opted out of both purposes, it is\n * deferred until they opt in to either one (see {@link optIn} and\n * {@link optInToMarketing}), so a user's location is never requested before\n * they consent to analytics. In either case the `GeolocationController` and its\n * `GeolocationController:getGeolocationData` action must be registered before\n * resolution occurs, or enrichment is skipped for the session (a message is\n * logged, see {@link #resolveLocationContext}).\n *\n * Safe to call more than once: the first call performs initialization and\n * subsequent calls return the same in-flight (or settled) promise.\n *\n * @returns A promise that resolves once initialization has completed.\n */\n init(): Promise<void> {\n // Cache the in-flight promise so repeated or overlapping calls share a\n // single initialization and all await the same completion (rather than an\n // early call observing a finished init while work is still pending).\n this.#initPromise ??= this.#performInit();\n return this.#initPromise;\n }\n\n /**\n * Performs the one-time initialization work: resolve geolocation, run the\n * platform adapter's onSetupCompleted lifecycle hook, then replay any queued\n * and pre-consent events.\n */\n async #performInit(): Promise<void> {\n // Snapshot fragment IDs and createdAt before any awaited init work so\n // reconciliation can tell previous-session leftovers from fragments\n // created or replaced while init runs.\n const initEventFragmentSnapshot = new Map<string, number>();\n for (const [id, fragment] of Object.entries(\n this.state.eventFragments ?? {},\n )) {\n if (\n isAnalyticsEventFragment(fragment) &&\n fragment.id === id &&\n typeof fragment.createdAt === 'number'\n ) {\n initEventFragmentSnapshot.set(id, fragment.createdAt);\n }\n }\n\n await this.#fetchEventsConfig();\n\n // Resolve geolocation only when the user is already opted in to product or\n // marketing analytics. For undecided or opted-out users it is deferred to\n // {@link optIn} / {@link optInToMarketing}. Awaited so that an already-opted-in\n // session has location available before events replay.\n await this.#maybeResolveLocation();\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n\n this.#replayQueuedEvents();\n this.#replayPreConsentEvents();\n this.#reconcileEventFragments(initEventFragmentSnapshot);\n }\n\n /**\n * Start resolving the geolocation context if warranted, and return the\n * in-flight (or settled) resolution so callers can await it. No-op unless\n * enrichment is enabled, the user is opted in to product or marketing\n * analytics, and a resolution has not already been started. Deferring\n * resolution until consent ensures a user's location is never requested before\n * they consent to analytics (for example, during onboarding).\n *\n * Resolution runs at most once per controller session: the settled promise\n * is retained, so the outcome, including a failure (see\n * {@link #resolveLocationContext}) is not retried, and events are delivered\n * without location for the rest of the session.\n *\n * @returns The geolocation resolution promise, or `undefined` when no\n * resolution is warranted.\n */\n #maybeResolveLocation(): Promise<void> | undefined {\n if (\n this.#isGeolocationEnabled &&\n this.#locationResolvePromise === undefined &&\n (this.state.optedIn || this.state.optedInToMarketing === true)\n ) {\n this.#locationResolvePromise = this.#resolveLocationContext();\n }\n\n return this.#locationResolvePromise;\n }\n\n async #resolveLocationContext(): Promise<void> {\n try {\n const geolocation = await this.messenger.call(\n 'GeolocationController:getGeolocationData',\n );\n\n this.#locationContext = buildLocationContext(geolocation);\n } catch (error) {\n // A common cause is the GeolocationController not being registered before\n // resolution runs (at init for an opted-in user, otherwise at opt-in).\n // Name it here so the failure is diagnosable, since enrichment is\n // otherwise skipped silently for the session.\n log(\n '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.',\n error,\n );\n }\n }\n\n /**\n * Merge the resolved location context into a caller-provided context.\n *\n * Caller-provided `location` fields are preserved, but the fields the\n * controller resolves take precedence over them.\n *\n * @param context - Optional caller-provided context.\n * @returns The context enriched with location, or the original context when\n * no location is known.\n */\n #withLocationContext(\n context?: AnalyticsContext,\n ): AnalyticsContext | undefined {\n if (!this.#locationContext) {\n return context;\n }\n\n const callerLocation = context?.location;\n\n return {\n ...context,\n location: {\n ...(isJsonRecord(callerLocation) ? callerLocation : {}),\n ...this.#locationContext,\n },\n };\n }\n\n /**\n * Stamp the purposes currently allowed for a payload using Segment's consent\n * context shape.\n *\n * @param purposes - Purposes for which the payload is eligible.\n * @param context - Optional caller-provided context.\n * @param version - Config version captured with the payload.\n * @returns Context with allowed purpose preferences.\n */\n #withConsentContext(\n purposes: AnalyticsPurpose[],\n context?: AnalyticsContext,\n version?: string,\n ): AnalyticsContext {\n const preferences = this.#allowedPurposePreferences(purposes);\n const {\n consent: existingConsent,\n eventsConfigVersion: _ignoredVersion,\n ...unmanagedContext\n } = context ?? {};\n const consent: Record<string, Json> = isJsonRecord(existingConsent)\n ? existingConsent\n : {};\n const existingCategoryPreferences = isJsonRecord(\n consent.categoryPreferences,\n )\n ? consent.categoryPreferences\n : {};\n\n return {\n ...unmanagedContext,\n consent: {\n ...consent,\n categoryPreferences: {\n ...existingCategoryPreferences,\n ...preferences,\n },\n },\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n }\n\n /**\n * Load event-purpose configuration.\n *\n * Phase 1 stub. Persisted configuration remains authoritative until a remote\n * source is wired up.\n */\n async #fetchEventsConfig(): Promise<void> {\n // Intentionally empty until an events-config source is wired up.\n }\n\n #purposesFromName(name: string): AnalyticsPurpose[] {\n return [...(this.#eventPurposes.get(name) ?? [AnalyticsPurpose.Product])];\n }\n\n #purposesFromQueuedEvent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsPurpose[] {\n if (queuedEvent.type === 'identify') {\n return [AnalyticsPurpose.Product];\n }\n\n if (queuedEvent.eventPurposes !== undefined) {\n return [...queuedEvent.eventPurposes];\n }\n\n return this.#purposesFromName(\n queuedEvent.type === 'view' ? queuedEvent.name : queuedEvent.eventName,\n );\n }\n\n #eventNamesFromFragment(\n fragment: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent'\n >,\n ): string[] {\n return [\n fragment.initialEvent,\n fragment.successEvent,\n fragment.failureEvent,\n ].filter((name): name is string => typeof name === 'string');\n }\n\n #purposesFromFragmentEvent(\n fragment: Pick<AnalyticsEventFragment, 'eventPurposes'>,\n name: string,\n ): AnalyticsPurpose[] {\n return [\n ...(fragment.eventPurposes?.[name] ?? this.#purposesFromName(name)),\n ];\n }\n\n #purposesFromFragment(\n fragment: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent' | 'eventPurposes'\n >,\n ): AnalyticsPurpose[] {\n const names = this.#eventNamesFromFragment(fragment);\n if (names.length === 0) {\n // Nameless property bags have no event to classify. Treat them as\n // eligible for any purpose so they can accumulate when either consent\n // allows capture.\n return Object.values(AnalyticsPurpose);\n }\n\n return [\n ...new Set(\n names.flatMap((name) =>\n this.#purposesFromFragmentEvent(fragment, name),\n ),\n ),\n ];\n }\n\n #consent(purpose: AnalyticsPurpose): {\n optedIn: boolean;\n decisionMade: boolean;\n } {\n return purpose === AnalyticsPurpose.Marketing\n ? {\n optedIn: this.state.optedInToMarketing === true,\n decisionMade: this.state.marketingConsentDecisionMade === true,\n }\n : {\n optedIn: this.state.optedIn,\n decisionMade: this.state.consentDecisionMade === true,\n };\n }\n\n #allowedPurposePreferences(purposes: AnalyticsPurpose[]): {\n product: boolean;\n marketing: boolean;\n } {\n return {\n product:\n purposes.includes(AnalyticsPurpose.Product) &&\n this.#consent(AnalyticsPurpose.Product).optedIn,\n marketing:\n purposes.includes(AnalyticsPurpose.Marketing) &&\n this.#consent(AnalyticsPurpose.Marketing).optedIn,\n };\n }\n\n #hasAllowedPurpose(purposes: AnalyticsPurpose[]): boolean {\n const { product, marketing } = this.#allowedPurposePreferences(purposes);\n return product || marketing;\n }\n\n #hasUndecidedPurpose(purposes: AnalyticsPurpose[]): boolean {\n return purposes.some((purpose) => !this.#consent(purpose).decisionMade);\n }\n\n #isCaptureAllowed(purposes: AnalyticsPurpose[]): boolean {\n return (\n this.#hasAllowedPurpose(purposes) ||\n (this.#isPreConsentQueueEnabled && this.#hasUndecidedPurpose(purposes))\n );\n }\n\n #replaceQueue(field: AnalyticsQueue, nextQueue: Record<string, Json>): void {\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state[field] = nextQueue as never;\n });\n }\n\n /**\n * Send final track payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param eventName - The name of the event.\n * @param properties - Optional event properties.\n * @param context - Optional platform-specific context.\n * @param purposes - Capture-time purposes for the event.\n * @param version - Capture-time events config version.\n */\n #sendOrQueueTrackEvent(\n eventName: string,\n properties: AnalyticsEventProperties | undefined,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n const isAllowed = this.#hasAllowedPurpose(purposes);\n const contextWithConsent = this.#withConsentContext(\n purposes,\n context,\n version,\n );\n\n // Direct delivery: enabled and not persisting.\n if (isAllowed && !this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.track(eventName, properties, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedTrackEvent = {\n type: 'track',\n eventName,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n context: contextWithConsent,\n eventPurposes: purposes,\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n\n if (!isAllowed) {\n this.#enqueuePreConsentEvent(queuedEvent);\n return;\n }\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final identify payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param userId - The user ID.\n * @param traits - Optional user traits.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueIdentifyEvent(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n ): void {\n const purposes = [AnalyticsPurpose.Product];\n const contextWithConsent = this.#withConsentContext(purposes, context);\n\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.identify(userId, traits, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedIdentifyEvent = {\n type: 'identify',\n userId,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(traits === undefined ? {} : { traits }),\n context: contextWithConsent,\n eventPurposes: purposes,\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final view payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param name - The view name.\n * @param properties - Optional view properties.\n * @param context - Optional platform-specific context.\n * @param purposes - Capture-time purposes for the view.\n * @param version - Capture-time events config version.\n */\n #sendOrQueueViewEvent(\n name: string,\n properties: AnalyticsEventProperties | undefined,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n const isAllowed = this.#hasAllowedPurpose(purposes);\n const contextWithConsent = this.#withConsentContext(\n purposes,\n context,\n version,\n );\n\n if (isAllowed && !this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.view(name, properties, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedViewEvent = {\n type: 'view',\n name,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n context: contextWithConsent,\n eventPurposes: purposes,\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n\n if (!isAllowed) {\n this.#enqueuePreConsentEvent(queuedEvent);\n return;\n }\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Add an analytics event to the queue and send it.\n *\n * @param queuedEvent - The event to enqueue and deliver.\n */\n #enqueueEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const eventQueue: Record<string, Json> = {\n ...(this.state.eventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventQueue = eventQueue as never;\n });\n\n this.#sendQueuedEvent(queuedEvent);\n }\n\n /**\n * Send a queued event through the platform adapter.\n *\n * @param queuedEvent - The queued event to deliver.\n */\n #sendQueuedEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const timestamp = new Date(queuedEvent.timestamp);\n\n if (Number.isNaN(timestamp.getTime())) {\n log('Dropping queued analytics event with invalid timestamp', {\n messageId: queuedEvent.messageId,\n });\n this.#removeQueuedEvent(queuedEvent.messageId);\n return;\n }\n\n const options: AnalyticsDeliveryOptions = {\n messageId: queuedEvent.messageId,\n timestamp,\n callback: (error?: unknown) => {\n if (error) {\n log('Queued analytics event delivery failed', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n\n this.#removeQueuedEvent(queuedEvent.messageId);\n },\n };\n\n try {\n if (queuedEvent.type === 'track') {\n this.#platformAdapter.track(\n queuedEvent.eventName,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else if (queuedEvent.type === 'identify') {\n this.#platformAdapter.identify(\n queuedEvent.userId,\n cloneDeep(queuedEvent.traits),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else {\n this.#platformAdapter.view(\n queuedEvent.name,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n }\n } catch (error) {\n log('Error sending queued analytics event', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n }\n\n /**\n * Replay persisted analytics events.\n */\n #replayQueuedEvents(): void {\n if (!this.#isEventQueuePersistenceEnabled || !this.state.eventQueue) {\n return;\n }\n\n const remainingQueue: Record<string, Json> = {};\n const eventsToSend: AnalyticsQueuedEvent[] = [];\n\n for (const [messageId, queuedEvent] of Object.entries(\n this.state.eventQueue,\n )) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n log('Dropping invalid queued analytics event', { messageId });\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n\n if (this.#hasAllowedPurpose(purposes)) {\n const refreshedEvent = this.#refreshQueuedEventConsent(queuedEvent);\n remainingQueue[messageId] = refreshedEvent;\n eventsToSend.push(refreshedEvent);\n }\n }\n\n this.#replaceQueue(AnalyticsQueue.EventQueue, remainingQueue);\n\n for (const queuedEvent of eventsToSend) {\n this.#sendQueuedEvent(queuedEvent);\n }\n }\n\n /**\n * Remove a queued analytics event.\n *\n * @param messageId - The queued event message ID.\n */\n #removeQueuedEvent(messageId: string): void {\n const currentEventQueue = this.state.eventQueue;\n\n if (\n !currentEventQueue ||\n !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)\n ) {\n return;\n }\n\n const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventQueue = eventQueue as never;\n });\n }\n\n #refreshQueuedEventConsent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsQueuedEvent {\n // Refresh only the consent stamp. Capture-time `eventPurposes` and\n // `eventsConfigVersion` stay as a pair and are never rewritten here.\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n const preferences = this.#allowedPurposePreferences(purposes);\n const existingPreferences = isJsonRecord(queuedEvent.context?.consent)\n ? queuedEvent.context.consent.categoryPreferences\n : undefined;\n\n if (\n isJsonRecord(existingPreferences) &&\n existingPreferences.product === preferences.product &&\n existingPreferences.marketing === preferences.marketing\n ) {\n return queuedEvent;\n }\n\n return {\n ...queuedEvent,\n context: this.#withConsentContext(\n purposes,\n queuedEvent.context,\n queuedEvent.eventsConfigVersion,\n ),\n };\n }\n\n /**\n * Prune a queue after a consent change.\n *\n * For {@link AnalyticsQueue.EventQueue}, entries are kept only while at least\n * one capture-time purpose is opted in, and their consent stamp is refreshed.\n * For {@link AnalyticsQueue.PreConsentEventQueue}, entries are kept while at\n * least one purpose is still allowed or undecided.\n *\n * @param field - The queue to prune.\n */\n #pruneQueueForConsent(field: AnalyticsQueue): void {\n const queue = this.state[field];\n if (!queue) {\n return;\n }\n\n const nextQueue: Record<string, Json> = {};\n for (const [messageId, queuedEvent] of Object.entries(queue)) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n const isAllowed = this.#hasAllowedPurpose(purposes);\n\n if (field === AnalyticsQueue.EventQueue) {\n if (isAllowed) {\n nextQueue[messageId] = this.#refreshQueuedEventConsent(queuedEvent);\n }\n }\n\n if (field === AnalyticsQueue.PreConsentEventQueue) {\n if (isAllowed || this.#hasUndecidedPurpose(purposes)) {\n nextQueue[messageId] = queuedEvent;\n }\n }\n }\n\n this.#replaceQueue(field, nextQueue);\n }\n\n /**\n * Add an event to the pre-consent queue without delivering it.\n *\n * @param queuedEvent - The event to hold until the user opts in.\n */\n #enqueuePreConsentEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const preConsentEventQueue: Record<string, Json> = {\n ...(this.state.preConsentEventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.preConsentEventQueue = preConsentEventQueue as never;\n });\n }\n\n /**\n * Enrich a pre-consent event with the geolocation resolved on opt-in.\n *\n * Pre-consent events are captured while geolocation is not yet resolved, so\n * they are re-enriched here as they replay. Anonymous track payloads are left\n * untouched, since they must never carry location.\n *\n * @param queuedEvent - The queued pre-consent event.\n * @returns The event with its context enriched, or the event unchanged when\n * enrichment does not apply.\n */\n #enrichPreConsentEvent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsQueuedEvent {\n if (\n queuedEvent.type === 'track' &&\n queuedEvent.properties?.anonymous === true\n ) {\n return queuedEvent;\n }\n\n const context = this.#withLocationContext(queuedEvent.context);\n\n return {\n ...queuedEvent,\n ...(context === undefined ? {} : { context }),\n };\n }\n\n /**\n * Replay eligible pre-consent events against current consent.\n *\n * Allowed entries are replayed, undecided entries are kept for later, and\n * entries with no remaining allowed or undecided purpose are dropped. The\n * keep set is written before replay so events cannot be re-queued or\n * replayed twice.\n *\n * If the pre-consent queue is disabled, any stale persisted entries (e.g. from\n * a previous session where it was enabled) are dropped so they can never be\n * replayed.\n */\n #replayPreConsentEvents(): void {\n const queue = this.state.preConsentEventQueue;\n\n if (!queue) {\n return;\n }\n\n if (!this.#isPreConsentQueueEnabled) {\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.preConsentEventQueue = {} as never;\n });\n return;\n }\n\n const keep: Record<string, Json> = {};\n const replay: AnalyticsQueuedEvent[] = [];\n\n for (const [messageId, queuedEvent] of Object.entries(queue)) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n\n if (this.#hasAllowedPurpose(purposes)) {\n replay.push(queuedEvent);\n } else if (this.#hasUndecidedPurpose(purposes)) {\n keep[messageId] = queuedEvent;\n }\n }\n\n this.#replaceQueue(AnalyticsQueue.PreConsentEventQueue, keep);\n\n for (const queuedEvent of replay) {\n const eventToReplay = this.#refreshQueuedEventConsent(\n this.#enrichPreConsentEvent(queuedEvent),\n );\n\n if (this.#isEventQueuePersistenceEnabled) {\n this.#enqueueEvent(eventToReplay);\n } else {\n this.#sendQueuedEvent(eventToReplay);\n }\n }\n }\n\n /**\n * Reconcile persisted event fragments on initialization.\n *\n * A fragment describes a journey that was in progress when the previous\n * session ended. Only fragments that opted into `persist` and are younger\n * than {@link EVENT_FRAGMENT_MAX_AGE} can be resumed, so the rest are\n * discarded. Nothing is emitted: a journey that never reached its own\n * finalization is not a failure, just an unfinished one.\n *\n * If the feature is disabled (e.g. a previous session had it enabled), or the\n * consent state no longer allows capture for any of a fragment's purposes,\n * those fragments are dropped so none of them can linger.\n *\n * Non-persistent fragments are dropped only when their ID and `createdAt`\n * match a fragment present at the start of {@link init}. Fragments created\n * or replaced while init is in flight are kept so a slow startup path cannot\n * discard an in-progress journey, as long as they have not expired.\n *\n * @param initEventFragmentSnapshot - Fragment IDs and `createdAt` values\n * present when {@link init} began.\n */\n #reconcileEventFragments(\n initEventFragmentSnapshot: Map<string, number>,\n ): void {\n const fragments = this.state.eventFragments;\n\n if (!fragments) {\n return;\n }\n\n if (!this.#isEventFragmentsEnabled) {\n this.#clearEventFragments();\n return;\n }\n\n const eventFragments: AnalyticsEventFragments = {};\n const now = Date.now();\n\n for (const [id, fragment] of Object.entries(fragments)) {\n if (!isAnalyticsEventFragment(fragment) || fragment.id !== id) {\n log('Dropping invalid persisted event fragment', { id });\n continue;\n }\n\n if (now - fragment.lastUpdated > EVENT_FRAGMENT_MAX_AGE) {\n log('Dropping expired persisted event fragment', { id });\n continue;\n }\n\n if (!this.#isCaptureAllowed(this.#purposesFromFragment(fragment))) {\n continue;\n }\n\n const snapshotCreatedAt = initEventFragmentSnapshot.get(id);\n\n if (\n fragment.persist === true ||\n snapshotCreatedAt === undefined ||\n fragment.createdAt !== snapshotCreatedAt\n ) {\n eventFragments[id] = fragment;\n }\n }\n\n if (Object.keys(eventFragments).length === 0) {\n this.#clearEventFragments();\n return;\n }\n\n if (Object.keys(eventFragments).length === Object.keys(fragments).length) {\n return;\n }\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Read an event fragment from state without the feature guard.\n *\n * @param id - The fragment ID.\n * @returns The fragment, or `undefined` when no fragment has that ID.\n */\n #getEventFragment(id: string): AnalyticsEventFragment | undefined {\n return this.state.eventFragments?.[id];\n }\n\n /**\n * Write an event fragment to state, replacing any fragment with the same ID.\n *\n * @param fragment - The fragment to store.\n * @returns The stored fragment with capture-time purpose metadata.\n */\n #setEventFragment(fragment: AnalyticsEventFragment): AnalyticsEventFragment {\n // Snapshot classification only. Consent is stamped at emit time by\n // {@link #trackEvent}, so fragment.context stays caller metadata.\n let fragmentWithPurposeSnapshot = fragment;\n if (fragment.eventPurposes === undefined) {\n const names = this.#eventNamesFromFragment(fragment);\n const eventPurposes = Object.fromEntries(\n names.map((name) => [name, this.#purposesFromName(name)]),\n );\n fragmentWithPurposeSnapshot = {\n ...fragment,\n ...(names.length === 0 ? {} : { eventPurposes }),\n ...(this.#eventsConfigVersion === undefined\n ? {}\n : { eventsConfigVersion: this.#eventsConfigVersion }),\n };\n }\n\n const eventFragments: AnalyticsEventFragments = {\n ...this.state.eventFragments,\n [fragmentWithPurposeSnapshot.id]: fragmentWithPurposeSnapshot,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n\n return fragmentWithPurposeSnapshot;\n }\n\n /**\n * Remove an event fragment from state.\n *\n * @param id - The fragment ID.\n */\n #removeEventFragment(id: string): void {\n const currentEventFragments = this.state.eventFragments;\n\n if (\n !currentEventFragments ||\n !Object.prototype.hasOwnProperty.call(currentEventFragments, id)\n ) {\n return;\n }\n\n const { [id]: _deletedFragment, ...eventFragments } = currentEventFragments;\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Drop event fragments that the current consent state no longer allows to\n * accumulate.\n */\n #pruneEventFragmentsForConsent(): void {\n const fragments = this.state.eventFragments;\n\n if (!fragments || Object.keys(fragments).length === 0) {\n return;\n }\n\n const eventFragments: AnalyticsEventFragments = {};\n for (const [id, fragment] of Object.entries(fragments)) {\n if (\n isAnalyticsEventFragment(fragment) &&\n this.#isCaptureAllowed(this.#purposesFromFragment(fragment))\n ) {\n eventFragments[id] = fragment;\n }\n }\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Drop queued events and fragments that the current consent state no longer\n * allows to keep.\n */\n #pruneAllForConsent(): void {\n this.#pruneQueueForConsent(AnalyticsQueue.EventQueue);\n this.#pruneQueueForConsent(AnalyticsQueue.PreConsentEventQueue);\n this.#pruneEventFragmentsForConsent();\n }\n\n /**\n * Clear all event fragments.\n */\n #clearEventFragments(): void {\n if (\n !this.state.eventFragments ||\n Object.keys(this.state.eventFragments).length === 0\n ) {\n return;\n }\n\n this.update((state) => {\n state.eventFragments = {};\n });\n }\n\n /**\n * Returns whether an event fragment call should be ignored, either because\n * the feature is disabled or because the consent state does not allow\n * capture. The ignored call is logged so a missing `isEventFragmentsEnabled`\n * or an unexpected consent state is diagnosable rather than silent.\n *\n * Consent is checked on every call, not just on the ones that emit, so a\n * fragment never accumulates data for an event that could not be delivered.\n *\n * @param method - The name of the method that was called.\n * @param fragment - The fragment being read or written, when one is known.\n * @returns True when the call should be ignored.\n */\n #shouldIgnoreEventFragmentCall(\n method: string,\n fragment?: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent' | 'eventPurposes'\n >,\n ): boolean {\n if (!this.#isEventFragmentsEnabled) {\n log(\n 'Ignoring event fragment call because the event fragments feature is disabled',\n { method },\n );\n\n return true;\n }\n\n const captureAllowed = fragment\n ? this.#isCaptureAllowed(this.#purposesFromFragment(fragment))\n : this.#isCaptureAllowed(Object.values(AnalyticsPurpose));\n\n if (!captureAllowed) {\n log(\n 'Ignoring event fragment call because the consent state does not allow capturing analytics',\n { method },\n );\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Emit one of an event fragment's events, carrying the properties the\n * fragment has accumulated.\n *\n * Delivery goes through {@link trackEvent}, so consent gating, the anonymous\n * payload split, the pre-consent queue and geolocation enrichment all apply.\n *\n * @param fragment - The fragment supplying the properties.\n * @param name - The name of the event to emit.\n * @param context - The context to send with the event.\n */\n #emitEventFragment(\n fragment: AnalyticsEventFragment,\n name: string,\n context: AnalyticsContext | undefined,\n ): void {\n const properties = { ...fragment.properties };\n const sensitiveProperties = { ...fragment.sensitiveProperties };\n\n this.#trackEvent(\n {\n name,\n properties,\n sensitiveProperties,\n saveDataRecording: false,\n hasProperties:\n Object.keys(properties).length > 0 ||\n Object.keys(sensitiveProperties).length > 0,\n },\n context,\n this.#purposesFromFragmentEvent(fragment, name),\n fragment.eventsConfigVersion,\n );\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void {\n this.#trackEvent(\n event,\n context,\n this.#purposesFromName(event.name),\n this.#eventsConfigVersion,\n );\n }\n\n #trackEvent(\n event: AnalyticsTrackingEvent,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n // An event captured while the user is still undecided is held in the\n // pre-consent queue (see #sendOrQueueTrackEvent) instead of being\n // delivered, and replayed if they later opt in.\n if (!this.#isCaptureAllowed(purposes)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n undefined,\n this.#withLocationContext(context),\n purposes,\n version,\n );\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n },\n this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n },\n // When the anonymous events feature is enabled, this payload is the\n // anonymous one and must carry no geolocation. When the feature is\n // disabled, this is the single identified payload, so it is enriched.\n this.#isAnonymousEventsFeatureEnabled\n ? context\n : this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n this.#sendOrQueueIdentifyEvent(\n this.state.analyticsId,\n traits,\n this.#withLocationContext(context),\n );\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackView(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n const purposes = this.#purposesFromName(name);\n const version = this.#eventsConfigVersion;\n if (!this.#isCaptureAllowed(purposes)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#sendOrQueueViewEvent(\n name,\n properties,\n this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n\n /**\n * Create an event fragment.\n *\n * A fragment accumulates properties across a user journey so that several\n * parts of a client can contribute to the same set of events without\n * re-deriving them. Declaring `successEvent` and `failureEvent` turns the\n * fragment into a funnel that {@link finalizeEventFragment} closes. Declaring\n * none of the event names makes it a pure property bag that the client reads\n * back with {@link getEventFragmentById} when it emits its own events.\n *\n * Any existing fragment with the same ID is replaced, so a new journey never\n * inherits properties from a stale one.\n *\n * Nothing is created unless the user is opted in, or undecided with the\n * pre-consent queue enabled, so an opted-out user accumulates no fragment\n * data.\n *\n * @param options - The fragment definition. An ID is generated when one is\n * not supplied.\n * @returns A read-only copy of the created fragment, or `undefined` when the\n * event fragments feature is disabled or the consent state does not allow\n * capture. Mutating the returned object does not change controller state.\n * Use {@link updateEventFragment} or {@link upsertEventFragment} to write.\n */\n createEventFragment(\n options: AnalyticsEventFragmentOptions = {},\n ): ReadonlyAnalyticsEventFragment | undefined {\n // Classify create from event names only. Caller consent context must not\n // affect the event-purpose snapshot.\n if (\n this.#shouldIgnoreEventFragmentCall('createEventFragment', {\n initialEvent: options.initialEvent,\n successEvent: options.successEvent,\n failureEvent: options.failureEvent,\n })\n ) {\n return undefined;\n }\n\n const now = Date.now();\n\n const fragment = this.#setEventFragment({\n id: options.id ?? uuid(),\n properties: { ...(options.properties ?? {}) },\n sensitiveProperties: { ...(options.sensitiveProperties ?? {}) },\n createdAt: now,\n lastUpdated: now,\n ...(options.initialEvent === undefined\n ? {}\n : { initialEvent: options.initialEvent }),\n ...(options.successEvent === undefined\n ? {}\n : { successEvent: options.successEvent }),\n ...(options.failureEvent === undefined\n ? {}\n : { failureEvent: options.failureEvent }),\n ...(options.context === undefined\n ? {}\n : { context: { ...options.context } }),\n ...(options.persist === undefined ? {} : { persist: options.persist }),\n });\n\n if (fragment.initialEvent) {\n this.#emitEventFragment(\n fragment,\n fragment.initialEvent,\n fragment.context,\n );\n }\n\n return cloneDeep(fragment);\n }\n\n /**\n * Write to an event fragment, creating a property bag if none exists.\n *\n * This is the ergonomic entry point for contributors that do not know\n * whether the journey has been started yet, and it avoids the read then\n * write race a caller would otherwise have to implement itself.\n *\n * @param id - The fragment ID.\n * @param payload - The properties and context to merge in.\n */\n upsertEventFragment(\n id: string,\n payload: AnalyticsEventFragmentPayload = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (\n this.#shouldIgnoreEventFragmentCall('upsertEventFragment', fragment ?? {})\n ) {\n return;\n }\n\n if (!fragment) {\n this.createEventFragment({ id, ...payload });\n return;\n }\n\n this.#setEventFragment(mergeEventFragment(fragment, payload));\n }\n\n /**\n * Write to an existing event fragment.\n *\n * @param id - The fragment ID.\n * @param payload - The properties and context to merge in.\n * @throws Error if no fragment has that ID when the call is not ignored.\n * Use {@link upsertEventFragment} when the fragment may not exist yet.\n * When the event fragments feature is disabled or the consent state does not\n * allow capture, the call is a logged no-op and does not throw.\n */\n updateEventFragment(\n id: string,\n payload: AnalyticsEventFragmentPayload = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('updateEventFragment', fragment)) {\n return;\n }\n\n if (!fragment) {\n throw new Error(`Event fragment with id ${id} does not exist.`);\n }\n\n this.#setEventFragment(mergeEventFragment(fragment, payload));\n }\n\n /**\n * Read an event fragment.\n *\n * @param id - The fragment ID.\n * @returns A read-only copy of the fragment, or `undefined` when no fragment\n * has that ID, the event fragments feature is disabled, or the consent state\n * does not allow capture. Mutating the returned object does not change\n * controller state. Use {@link updateEventFragment} or\n * {@link upsertEventFragment} to write.\n */\n getEventFragmentById(id: string): ReadonlyAnalyticsEventFragment | undefined {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('getEventFragmentById', fragment)) {\n return undefined;\n }\n\n return fragment === undefined ? undefined : cloneDeep(fragment);\n }\n\n /**\n * Discard an event fragment without emitting anything.\n *\n * @param id - The fragment ID.\n */\n deleteEventFragment(id: string): void {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('deleteEventFragment', fragment)) {\n return;\n }\n\n this.#removeEventFragment(id);\n }\n\n /**\n * Close an event fragment, emitting its closing event and discarding it.\n *\n * The event emitted is `failureEvent` when the journey was abandoned and\n * `successEvent` otherwise. A fragment that does not declare the relevant\n * event name is discarded silently, which is what makes a pure property bag\n * possible.\n *\n * @param id - The fragment ID.\n * @param options - Finalization options.\n * @param options.abandoned - Whether the journey was abandoned.\n * @param options.context - Context merged over the fragment's own context.\n * @throws Error if no fragment has that ID when the call is not ignored.\n * When the event fragments feature is disabled or the consent state does not\n * allow capture, the call is a logged no-op and does not throw.\n */\n finalizeEventFragment(\n id: string,\n { abandoned = false, context }: AnalyticsEventFragmentFinalizeOptions = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (\n this.#shouldIgnoreEventFragmentCall('finalizeEventFragment', fragment)\n ) {\n return;\n }\n\n if (!fragment) {\n throw new Error(`Event fragment with id ${id} does not exist.`);\n }\n\n const eventName = abandoned ? fragment.failureEvent : fragment.successEvent;\n\n if (eventName) {\n this.#emitEventFragment(\n fragment,\n eventName,\n mergeEventFragmentContext(fragment.context, context),\n );\n }\n\n this.#removeEventFragment(id);\n }\n\n /**\n * Opt in to analytics.\n *\n * Records that a consent decision has been made and replays any events that\n * were queued while the user was undecided.\n *\n * When geolocation enrichment is enabled, geolocation is resolved here (once\n * the user has consented) and awaited before the queued events are replayed,\n * so those events are enriched with the resolved location as they are sent.\n *\n * @returns A promise that resolves once opt-in processing has completed.\n */\n async optIn(): Promise<void> {\n this.update((state) => {\n state.optedIn = true;\n state.consentDecisionMade = true;\n });\n\n // Now that the user has consented, resolve geolocation (once) and wait for\n // it so the queued pre-consent events can be enriched as they replay.\n await this.#maybeResolveLocation();\n\n // Reconcile against the current state rather than replaying blindly: the\n // consent decision may have changed while geolocation was resolving (e.g.\n // resetConsentDecision ran during the await), and preserved pre-consent\n // events must not be delivered once the user is no longer opted in.\n this.#replayPreConsentEvents();\n }\n\n /**\n * Opt out of analytics.\n *\n * Records that a consent decision has been made and discards any persisted\n * events and in-progress event fragments so nothing captured before the\n * decision is ever delivered.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n state.consentDecisionMade = true;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Reset the consent decision back to undecided.\n *\n * Intended for client flows that restart onboarding. Clears the opt-in\n * preference and discards the delivery queue, but preserves any pre-consent\n * events so they can still be replayed if the user opts in again. The user is\n * treated as undecided again.\n *\n * In-progress event fragments are kept only while the undecided user can\n * still accumulate them, and discarded otherwise, so no fragment outlives the\n * consent state that allowed it.\n */\n resetConsentDecision(): void {\n this.update((state) => {\n state.optedIn = false;\n state.consentDecisionMade = false;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Opt in to marketing analytics.\n *\n * Independent of {@link optIn}. Replays queued marketing events.\n *\n * @returns A promise that resolves once opt-in processing has completed.\n */\n async optInToMarketing(): Promise<void> {\n this.update((state) => {\n state.optedInToMarketing = true;\n state.marketingConsentDecisionMade = true;\n });\n\n await this.#maybeResolveLocation();\n this.#replayPreConsentEvents();\n }\n\n /**\n * Opt out of marketing analytics.\n *\n * Independent of {@link optOut}. Discards queued marketing events and\n * marketing event fragments.\n */\n optOutOfMarketing(): void {\n this.update((state) => {\n state.optedInToMarketing = false;\n state.marketingConsentDecisionMade = true;\n state.marketingCampaignCookieId = null;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Reset the marketing consent decision back to undecided.\n *\n * Independent of {@link resetConsentDecision}.\n */\n resetMarketingConsentDecision(): void {\n this.update((state) => {\n state.optedInToMarketing = false;\n state.marketingConsentDecisionMade = false;\n state.marketingCampaignCookieId = null;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Set the marketing campaign cookie ID.\n *\n * Stores the ID of the marketing campaign cookie (e.g. a Google Analytics\n * client ID) that was active when the user arrived. Pass `null` to clear it.\n * The value is automatically cleared by {@link optOutOfMarketing} and\n * {@link resetMarketingConsentDecision}.\n *\n * @param marketingCampaignCookieId - The marketing campaign cookie ID, or\n * `null` to clear it.\n */\n setMarketingCampaignCookieId(marketingCampaignCookieId: string | null): void {\n this.update((state) => {\n state.marketingCampaignCookieId = marketingCampaignCookieId;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AnalyticsController.js","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAW3D,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAGlC,OAAO,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EAAE,aAAa,IAAI,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAkB5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAC;AAE9D,kBAAkB;AAElB;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAEpD;;;;;;;;GAQG;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OAIG;IACH,6BAA6B;QAC3B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;YACjC,KAAK,CAAC,4BAA4B,GAAG,KAAK,CAAC;YAC3C,KAAK,CAAC,yBAAyB,GAAG,IAAI,CAAC;QACzC,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAED;;;;;;;;;;OAUG;IACH,4BAA4B,CAAC,yBAAwC;QACnE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,yBAAyB,GAAG,yBAAyB,CAAC;QAC9D,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ConfigRegistryControllerGetStateAction,\n ConfigRegistryControllerStateChangedEvent,\n} from '@metamask/config-registry-controller';\nimport type {\n GeolocationControllerGetGeolocationDataAction,\n GeolocationData,\n} from '@metamask/geolocation-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport { cloneDeep } from 'lodash-es';\nimport { v4 as uuid } from 'uuid';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types.js';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator.js';\nimport { projectLogger as log } from './AnalyticsLogger.js';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsDeliveryOptions,\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsLocationContext,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types.js';\nimport type {\n AnalyticsEventFragment,\n AnalyticsEventFragmentFinalizeOptions,\n AnalyticsEventFragmentOptions,\n AnalyticsEventFragmentPayload,\n AnalyticsEventFragments,\n ReadonlyAnalyticsEventFragment,\n} from './EventFragment.types.js';\nimport { analyticsControllerSelectors } from './selectors.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n/**\n * Maximum age of a persisted event fragment, measured from\n * {@link AnalyticsEventFragment.lastUpdated}.\n *\n * Fragments older than this are discarded during {@link AnalyticsController.init}\n * without emitting a success or failure event. Confirmation journeys that span a\n * restart are expected to resume within this window; abandoned ones must not keep\n * `properties` or `sensitiveProperties` in storage indefinitely.\n */\nexport const EVENT_FRAGMENT_MAX_AGE = 24 * 60 * 60 * 1000;\n\n/**\n * Purposes for which an analytics payload can be used.\n */\nexport const AnalyticsPurpose = {\n Product: 'product',\n Marketing: 'marketing',\n} as const;\n\n/**\n * A purpose for which an analytics payload can be used.\n */\nexport type AnalyticsPurpose =\n (typeof AnalyticsPurpose)[keyof typeof AnalyticsPurpose];\n\n/**\n * Persisted event-purpose classification fetched from config registry.\n */\nexport type AnalyticsEventsConfig = {\n schemaVersion: string;\n version: string;\n timestamp: number;\n events: Record<string, AnalyticsPurpose[]>;\n};\n\n/**\n * Persisted queues on {@link AnalyticsControllerState}.\n */\nconst AnalyticsQueue = {\n EventQueue: 'eventQueue',\n PreConsentEventQueue: 'preConsentEventQueue',\n} as const;\n\ntype AnalyticsQueue = (typeof AnalyticsQueue)[keyof typeof AnalyticsQueue];\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * Whether the user has opted in to marketing analytics.\n *\n * Independent of {@link optedIn}. Named events in the remote marketing list\n * are governed only by this flag. Optional for backward compatibility with\n * persisted state that predates this field. Missing values are treated as\n * `false`.\n */\n optedInToMarketing?: boolean;\n\n /**\n * Whether the user has made a marketing consent decision (opted in or opted\n * out). Mirrors {@link consentDecisionMade} for the marketing purpose.\n * Optional for backward compatibility. Missing values are treated as `false`.\n */\n marketingConsentDecisionMade?: boolean;\n\n /**\n * Cached event-purpose configuration. Optional for backward compatibility.\n * Loaded from ConfigRegistryController state during init. Unlisted events\n * default to product-only.\n */\n eventsConfig?: AnalyticsEventsConfig;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n\n /**\n * Persisted queue of analytics events waiting for delivery acknowledgement.\n * This is only used when event queue persistence is enabled.\n */\n eventQueue?: Record<string, Json>;\n\n /**\n * Whether the user has made a consent decision (opted in or opted out).\n *\n * This distinguishes the \"undecided\" state (e.g. during onboarding, before\n * the user has answered the analytics prompt) from an explicit opt-out.\n * Defaults to `false` and is set to `true` by {@link AnalyticsController.optIn}\n * or {@link AnalyticsController.optOut}, and back to `false` by\n * {@link AnalyticsController.resetConsentDecision}. Optional for backward\n * compatibility with persisted state that predates this field.\n */\n consentDecisionMade?: boolean;\n\n /**\n * Persisted queue of track events ({@link AnalyticsQueuedTrackEvent}) captured\n * while the user is undecided (no consent decision made yet). Replayed on\n * opt-in and cleared on opt-out.\n * Preserved across {@link AnalyticsController.resetConsentDecision} so onboarding\n * restarts do not drop install-time events.\n * This is only used when the pre-consent queue is enabled.\n */\n preConsentEventQueue?: Record<string, Json>;\n\n /**\n * Persisted event fragments ({@link AnalyticsEventFragment}) keyed by\n * fragment ID. Fragments accumulate properties across a user journey and are\n * removed when the journey is finalized or deleted. Fragments that set\n * `persist: true` can survive {@link AnalyticsController.init}, but only\n * while younger than {@link EVENT_FRAGMENT_MAX_AGE}.\n * This is only used when the event fragments feature is enabled.\n */\n eventFragments?: AnalyticsEventFragments;\n\n /**\n * Marketing campaign cookie ID set when the user arrives via a marketing\n * campaign. Cleared automatically when the user calls\n * {@link AnalyticsController.optOutOfMarketing} or\n * {@link AnalyticsController.resetMarketingConsentDecision}. Optional for backward\n * compatibility with persisted state that predates this field.\n */\n marketingCampaignCookieId?: string | null;\n};\n\n/**\n * Event types supported by the persisted analytics event queue.\n */\nexport type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';\n\n/**\n * Base persisted event queue entry.\n */\nexport type AnalyticsQueuedEventBase = {\n /**\n * Event type used to replay the payload with the platform adapter.\n */\n type: AnalyticsQueuedEventType;\n\n /**\n * Stable identifier for the analytics payload.\n */\n messageId: string;\n\n /**\n * Original payload timestamp serialized for persistence.\n */\n timestamp: string;\n\n /**\n * Event purposes captured with the payload, before user consent is applied.\n */\n eventPurposes?: AnalyticsPurpose[];\n\n /**\n * Events config version used to classify the payload.\n */\n eventsConfigVersion?: string;\n};\n\n/**\n * Persisted track event queue entry.\n */\nexport type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {\n type: 'track';\n eventName: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted identify event queue entry.\n */\nexport type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {\n type: 'identify';\n userId: string;\n traits?: AnalyticsUserTraits;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted view event queue entry.\n */\nexport type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {\n type: 'view';\n name: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted analytics event queue entry.\n */\nexport type AnalyticsQueuedEvent =\n | AnalyticsQueuedTrackEvent\n | AnalyticsQueuedIdentifyEvent\n | AnalyticsQueuedViewEvent;\n\n/**\n * Persisted analytics event queue keyed by message ID.\n */\nexport type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n consentDecisionMade: false,\n optedInToMarketing: false,\n marketingConsentDecisionMade: false,\n marketingCampaignCookieId: null,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Both `optedIn` and `analyticsId` are persisted (`persist: true`).\n * The platform must supply a valid UUIDv4 `analyticsId` on first run.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n optedInToMarketing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n marketingConsentDecisionMade: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n eventsConfig: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n eventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n consentDecisionMade: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n preConsentEventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n eventFragments: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n marketingCampaignCookieId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n 'resetConsentDecision',\n 'optInToMarketing',\n 'optOutOfMarketing',\n 'resetMarketingConsentDecision',\n 'setMarketingCampaignCookieId',\n 'createEventFragment',\n 'upsertEventFragment',\n 'updateEventFragment',\n 'getEventFragmentById',\n 'deleteEventFragment',\n 'finalizeEventFragment',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions =\n | GeolocationControllerGetGeolocationDataAction\n | ConfigRegistryControllerGetStateAction;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = ConfigRegistryControllerStateChangedEvent;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating the ID on first run.\n * It is then persisted with controller state when using a persisted store.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n\n /**\n * Whether analytics event queue persistence is enabled.\n *\n * When enabled, AnalyticsController persists each platform adapter payload\n * until the adapter reports successful delivery.\n *\n * @default false\n */\n isEventQueuePersistenceEnabled?: boolean;\n\n /**\n * Whether the pre-consent event queue is enabled.\n *\n * When enabled, track events received while the user is undecided\n * (no consent decision made yet) are persisted and replayed on opt-in,\n * or dropped on opt-out. When disabled, such events are dropped immediately,\n * preserving the legacy behavior.\n *\n * @default false\n */\n isPreConsentQueueEnabled?: boolean;\n\n /**\n * Whether geolocation enrichment is enabled.\n *\n * When enabled, {@link AnalyticsController.init} resolves the user's\n * country, region, and timezone via `GeolocationController:getGeolocationData`\n * and attaches them to `context.location` on non-anonymous payloads.\n * Compositions must register that action when this is enabled. When disabled,\n * the controller never calls the geolocation action and events are delivered\n * without location.\n *\n * @default false\n */\n isGeolocationEnabled?: boolean;\n\n /**\n * Whether the event fragments feature is enabled.\n *\n * When enabled, clients can accumulate analytics properties across a user\n * journey with {@link AnalyticsController.createEventFragment} and friends,\n * as long as the consent state allows analytics to be captured. When\n * disabled, every fragment method is a logged no-op and no fragment is ever\n * written to state.\n *\n * @default false\n */\n isEventFragmentsEnabled?: boolean;\n};\n\n/**\n * Returns whether a value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a record.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isAnalyticsPurpose(value: unknown): value is AnalyticsPurpose {\n return (\n value === AnalyticsPurpose.Product || value === AnalyticsPurpose.Marketing\n );\n}\n\nfunction isEventPurposesRecord(\n value: unknown,\n): value is Record<string, AnalyticsPurpose[]> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (purposes) =>\n Array.isArray(purposes) &&\n purposes.length > 0 &&\n purposes.every(isAnalyticsPurpose),\n )\n );\n}\n\nfunction isAnalyticsEventsConfig(\n value: unknown,\n): value is AnalyticsEventsConfig {\n return (\n isRecord(value) &&\n typeof value.schemaVersion === 'string' &&\n typeof value.version === 'string' &&\n typeof value.timestamp === 'number' &&\n isEventPurposesRecord(value.events)\n );\n}\n\n/**\n * Returns whether a JSON value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a JSON record.\n */\nfunction isJsonRecord(value: Json | undefined): value is Record<string, Json> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Builds the analytics location context from geolocation data, keeping only\n * the fields the geolocation API was able to determine.\n *\n * @param geolocation - The geolocation data to convert.\n * @returns The location context, or `undefined` when no field is known.\n */\nfunction buildLocationContext(\n geolocation: GeolocationData,\n): AnalyticsLocationContext | undefined {\n const locationContext: AnalyticsLocationContext = {\n ...(geolocation.country === null\n ? {}\n : { country_code: geolocation.country }),\n ...(geolocation.region === null ? {} : { region: geolocation.region }),\n ...(geolocation.timezone === null\n ? {}\n : { timezone: geolocation.timezone }),\n };\n\n return Object.keys(locationContext).length === 0\n ? undefined\n : locationContext;\n}\n\n/**\n * Returns whether a value is a valid persisted analytics event.\n *\n * @param value - The value to check.\n * @returns True if the value is a queued analytics event.\n */\nfunction isAnalyticsQueuedEvent(value: unknown): value is AnalyticsQueuedEvent {\n if (!isRecord(value)) {\n return false;\n }\n\n if (\n typeof value.messageId !== 'string' ||\n typeof value.timestamp !== 'string' ||\n (value.eventPurposes !== undefined &&\n (!Array.isArray(value.eventPurposes) ||\n !value.eventPurposes.every(isAnalyticsPurpose))) ||\n (value.eventsConfigVersion !== undefined &&\n typeof value.eventsConfigVersion !== 'string')\n ) {\n return false;\n }\n\n if (value.type === 'track') {\n return (\n typeof value.eventName === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'identify') {\n return (\n typeof value.userId === 'string' &&\n (value.traits === undefined || isRecord(value.traits)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'view') {\n return (\n typeof value.name === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n return false;\n}\n\n/**\n * Returns whether a value is a valid persisted event fragment.\n *\n * @param value - The value to check.\n * @returns True if the value is an event fragment.\n */\nfunction isAnalyticsEventFragment(\n value: unknown,\n): value is AnalyticsEventFragment {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n typeof value.id === 'string' &&\n typeof value.createdAt === 'number' &&\n typeof value.lastUpdated === 'number' &&\n isRecord(value.properties) &&\n isRecord(value.sensitiveProperties) &&\n (value.initialEvent === undefined ||\n typeof value.initialEvent === 'string') &&\n (value.successEvent === undefined ||\n typeof value.successEvent === 'string') &&\n (value.failureEvent === undefined ||\n typeof value.failureEvent === 'string') &&\n (value.eventPurposes === undefined ||\n isEventPurposesRecord(value.eventPurposes)) &&\n (value.eventsConfigVersion === undefined ||\n typeof value.eventsConfigVersion === 'string') &&\n (value.context === undefined || isRecord(value.context)) &&\n (value.persist === undefined || typeof value.persist === 'boolean')\n );\n}\n\n/**\n * Merges a payload into an event fragment.\n *\n * `properties`, `sensitiveProperties` and `context` are merged one level deep,\n * so a key written twice is replaced rather than combined. This keeps array\n * values predictable: writing a shorter array replaces the longer one instead\n * of leaving stale trailing entries behind.\n *\n * @param fragment - The fragment to merge into.\n * @param payload - The payload to merge.\n * @returns A new fragment with the payload applied.\n */\nfunction mergeEventFragment(\n fragment: AnalyticsEventFragment,\n payload: AnalyticsEventFragmentPayload,\n): AnalyticsEventFragment {\n const context = mergeEventFragmentContext(fragment.context, payload.context);\n\n return {\n ...fragment,\n properties: { ...fragment.properties, ...(payload.properties ?? {}) },\n sensitiveProperties: {\n ...fragment.sensitiveProperties,\n ...(payload.sensitiveProperties ?? {}),\n },\n ...(context === undefined ? {} : { context }),\n lastUpdated: Date.now(),\n };\n}\n\n/**\n * Merges two optional analytics contexts.\n *\n * @param base - The context to merge into.\n * @param override - The context whose fields win. When omitted, `base` is kept.\n * @returns The merged context, or `undefined` when both sides are unset.\n */\nfunction mergeEventFragmentContext(\n base: AnalyticsContext | undefined,\n override: AnalyticsContext | undefined,\n): AnalyticsContext | undefined {\n if (override === undefined) {\n return base;\n }\n\n return { ...(base ?? {}), ...override };\n}\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * The controller persists `optedIn` and `analyticsId` when composed with a persisted\n * store. The platform must supply a valid `analyticsId` on first launch.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n readonly #isEventQueuePersistenceEnabled: boolean;\n\n readonly #isPreConsentQueueEnabled: boolean;\n\n readonly #isGeolocationEnabled: boolean;\n\n readonly #isEventFragmentsEnabled: boolean;\n\n /**\n * In-memory event-purpose lookup from persisted state.\n */\n #eventPurposes: Map<string, AnalyticsPurpose[]>;\n\n #eventsConfigVersion: string | undefined;\n\n /**\n * The in-flight (or settled) initialization promise. Set on the first\n * {@link init} call and returned by subsequent calls so overlapping callers\n * await the same work rather than observing a premature completion.\n */\n #initPromise: Promise<void> | undefined;\n\n /**\n * The in-flight (or settled) geolocation resolution, if any. Its presence\n * marks that resolution has been started, so it runs at most once.\n */\n #locationResolvePromise: Promise<void> | undefined;\n\n #locationContext: AnalyticsLocationContext | undefined;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled\n * @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled\n * @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled\n * @param options.isEventFragmentsEnabled - Whether the event fragments feature is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n isEventQueuePersistenceEnabled = false,\n isPreConsentQueueEnabled = false,\n isGeolocationEnabled = false,\n isEventFragmentsEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n const eventsConfig = isAnalyticsEventsConfig(initialState.eventsConfig)\n ? initialState.eventsConfig\n : undefined;\n if (eventsConfig === undefined) {\n delete initialState.eventsConfig;\n } else {\n initialState.eventsConfig = eventsConfig;\n }\n\n validateAnalyticsControllerState(\n initialState,\n platformAdapter.skipUUIDv4Check === true,\n );\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#isEventQueuePersistenceEnabled = isEventQueuePersistenceEnabled;\n this.#isPreConsentQueueEnabled = isPreConsentQueueEnabled;\n this.#isGeolocationEnabled = isGeolocationEnabled;\n this.#isEventFragmentsEnabled = isEventFragmentsEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initPromise = undefined;\n this.#locationResolvePromise = undefined;\n this.#eventPurposes = new Map(Object.entries(eventsConfig?.events ?? {}));\n this.#eventsConfigVersion = eventsConfig?.version;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n optedInToMarketing: this.state.optedInToMarketing === true,\n marketingConsentDecisionMade:\n this.state.marketingConsentDecisionMade === true,\n consentDecisionMade: this.state.consentDecisionMade,\n analyticsId: this.state.analyticsId,\n eventQueuePersistenceEnabled: this.#isEventQueuePersistenceEnabled,\n preConsentQueueEnabled: this.#isPreConsentQueueEnabled,\n geolocationEnabled: this.#isGeolocationEnabled,\n eventFragmentsEnabled: this.#isEventFragmentsEnabled,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's\n * onSetupCompleted lifecycle hook and replaying any queued events. This\n * method must be called after construction to complete the setup process.\n *\n * When geolocation enrichment is enabled (`isGeolocationEnabled`), geolocation\n * is resolved only for a user who is already opted in to product or marketing\n * analytics. For users undecided or opted out of both purposes, it is\n * deferred until they opt in to either one (see {@link optIn} and\n * {@link optInToMarketing}), so a user's location is never requested before\n * they consent to analytics. In either case the `GeolocationController` and its\n * `GeolocationController:getGeolocationData` action must be registered before\n * resolution occurs, or enrichment is skipped for the session (a message is\n * logged, see {@link #resolveLocationContext}).\n *\n * Safe to call more than once: the first call performs initialization and\n * subsequent calls return the same in-flight (or settled) promise.\n *\n * @returns A promise that resolves once initialization has completed.\n */\n init(): Promise<void> {\n // Cache the in-flight promise so repeated or overlapping calls share a\n // single initialization and all await the same completion (rather than an\n // early call observing a finished init while work is still pending).\n this.#initPromise ??= this.#performInit();\n return this.#initPromise;\n }\n\n /**\n * Performs the one-time initialization work: resolve geolocation, run the\n * platform adapter's onSetupCompleted lifecycle hook, then replay any queued\n * and pre-consent events.\n */\n async #performInit(): Promise<void> {\n // Snapshot fragment IDs and createdAt before any awaited init work so\n // reconciliation can tell previous-session leftovers from fragments\n // created or replaced while init runs.\n const initEventFragmentSnapshot = new Map<string, number>();\n for (const [id, fragment] of Object.entries(\n this.state.eventFragments ?? {},\n )) {\n if (\n isAnalyticsEventFragment(fragment) &&\n fragment.id === id &&\n typeof fragment.createdAt === 'number'\n ) {\n initEventFragmentSnapshot.set(id, fragment.createdAt);\n }\n }\n\n await this.#fetchEventsConfig();\n\n try {\n this.messenger.subscribe(\n 'ConfigRegistryController:stateChanged',\n (newState) => {\n if (\n newState.configs.eventsConfig?.version !== this.#eventsConfigVersion\n ) {\n this.#fetchEventsConfig().catch(\n /* istanbul ignore next */ () => undefined,\n );\n }\n },\n );\n } catch {\n // ConfigRegistryController may not be registered in all environments.\n }\n\n // Resolve geolocation only when the user is already opted in to product or\n // marketing analytics. For undecided or opted-out users it is deferred to\n // {@link optIn} / {@link optInToMarketing}. Awaited so that an already-opted-in\n // session has location available before events replay.\n await this.#maybeResolveLocation();\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n\n this.#replayQueuedEvents();\n this.#replayPreConsentEvents();\n this.#reconcileEventFragments(initEventFragmentSnapshot);\n }\n\n /**\n * Start resolving the geolocation context if warranted, and return the\n * in-flight (or settled) resolution so callers can await it. No-op unless\n * enrichment is enabled, the user is opted in to product or marketing\n * analytics, and a resolution has not already been started. Deferring\n * resolution until consent ensures a user's location is never requested before\n * they consent to analytics (for example, during onboarding).\n *\n * Resolution runs at most once per controller session: the settled promise\n * is retained, so the outcome, including a failure (see\n * {@link #resolveLocationContext}) is not retried, and events are delivered\n * without location for the rest of the session.\n *\n * @returns The geolocation resolution promise, or `undefined` when no\n * resolution is warranted.\n */\n #maybeResolveLocation(): Promise<void> | undefined {\n if (\n this.#isGeolocationEnabled &&\n this.#locationResolvePromise === undefined &&\n (this.state.optedIn || this.state.optedInToMarketing === true)\n ) {\n this.#locationResolvePromise = this.#resolveLocationContext();\n }\n\n return this.#locationResolvePromise;\n }\n\n async #resolveLocationContext(): Promise<void> {\n try {\n const geolocation = await this.messenger.call(\n 'GeolocationController:getGeolocationData',\n );\n\n this.#locationContext = buildLocationContext(geolocation);\n } catch (error) {\n // A common cause is the GeolocationController not being registered before\n // resolution runs (at init for an opted-in user, otherwise at opt-in).\n // Name it here so the failure is diagnosable, since enrichment is\n // otherwise skipped silently for the session.\n log(\n '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.',\n error,\n );\n }\n }\n\n /**\n * Merge the resolved location context into a caller-provided context.\n *\n * Caller-provided `location` fields are preserved, but the fields the\n * controller resolves take precedence over them.\n *\n * @param context - Optional caller-provided context.\n * @returns The context enriched with location, or the original context when\n * no location is known.\n */\n #withLocationContext(\n context?: AnalyticsContext,\n ): AnalyticsContext | undefined {\n if (!this.#locationContext) {\n return context;\n }\n\n const callerLocation = context?.location;\n\n return {\n ...context,\n location: {\n ...(isJsonRecord(callerLocation) ? callerLocation : {}),\n ...this.#locationContext,\n },\n };\n }\n\n /**\n * Stamp the purposes currently allowed for a payload using Segment's consent\n * context shape.\n *\n * @param purposes - Purposes for which the payload is eligible.\n * @param context - Optional caller-provided context.\n * @param version - Config version captured with the payload.\n * @returns Context with allowed purpose preferences.\n */\n #withConsentContext(\n purposes: AnalyticsPurpose[],\n context?: AnalyticsContext,\n version?: string,\n ): AnalyticsContext {\n const preferences = this.#allowedPurposePreferences(purposes);\n const {\n consent: existingConsent,\n eventsConfigVersion: _ignoredVersion,\n ...unmanagedContext\n } = context ?? {};\n const consent: Record<string, Json> = isJsonRecord(existingConsent)\n ? existingConsent\n : {};\n const existingCategoryPreferences = isJsonRecord(\n consent.categoryPreferences,\n )\n ? consent.categoryPreferences\n : {};\n\n return {\n ...unmanagedContext,\n consent: {\n ...consent,\n categoryPreferences: {\n ...existingCategoryPreferences,\n ...preferences,\n },\n },\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n }\n\n /**\n * Load event-purpose configuration from ConfigRegistryController state.\n * Updates in-memory purposes map and persisted state when the version differs.\n */\n async #fetchEventsConfig(): Promise<void> {\n let eventsConfigState;\n try {\n eventsConfigState = this.messenger.call(\n 'ConfigRegistryController:getState',\n );\n } catch {\n // ConfigRegistryController may not be registered in all environments.\n return;\n }\n\n const remoteEventsConfig = eventsConfigState.configs.eventsConfig;\n if (!remoteEventsConfig) {\n return;\n }\n\n const candidate: AnalyticsEventsConfig = {\n schemaVersion: remoteEventsConfig.schemaVersion,\n version: remoteEventsConfig.version,\n timestamp: remoteEventsConfig.timestamp,\n events: remoteEventsConfig.events as Record<string, AnalyticsPurpose[]>,\n };\n\n if (\n !isAnalyticsEventsConfig(candidate) ||\n candidate.version === this.#eventsConfigVersion\n ) {\n return;\n }\n\n this.#eventPurposes = new Map(Object.entries(candidate.events));\n this.#eventsConfigVersion = candidate.version;\n this.update((state) => {\n state.eventsConfig = candidate;\n });\n }\n\n #purposesFromName(name: string): AnalyticsPurpose[] {\n return [...(this.#eventPurposes.get(name) ?? [AnalyticsPurpose.Product])];\n }\n\n #purposesFromQueuedEvent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsPurpose[] {\n if (queuedEvent.type === 'identify') {\n return [AnalyticsPurpose.Product];\n }\n\n if (queuedEvent.eventPurposes !== undefined) {\n return [...queuedEvent.eventPurposes];\n }\n\n return this.#purposesFromName(\n queuedEvent.type === 'view' ? queuedEvent.name : queuedEvent.eventName,\n );\n }\n\n #eventNamesFromFragment(\n fragment: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent'\n >,\n ): string[] {\n return [\n fragment.initialEvent,\n fragment.successEvent,\n fragment.failureEvent,\n ].filter((name): name is string => typeof name === 'string');\n }\n\n #purposesFromFragmentEvent(\n fragment: Pick<AnalyticsEventFragment, 'eventPurposes'>,\n name: string,\n ): AnalyticsPurpose[] {\n return [\n ...(fragment.eventPurposes?.[name] ?? this.#purposesFromName(name)),\n ];\n }\n\n #purposesFromFragment(\n fragment: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent' | 'eventPurposes'\n >,\n ): AnalyticsPurpose[] {\n const names = this.#eventNamesFromFragment(fragment);\n if (names.length === 0) {\n // Nameless property bags have no event to classify. Treat them as\n // eligible for any purpose so they can accumulate when either consent\n // allows capture.\n return Object.values(AnalyticsPurpose);\n }\n\n return [\n ...new Set(\n names.flatMap((name) =>\n this.#purposesFromFragmentEvent(fragment, name),\n ),\n ),\n ];\n }\n\n #consent(purpose: AnalyticsPurpose): {\n optedIn: boolean;\n decisionMade: boolean;\n } {\n return purpose === AnalyticsPurpose.Marketing\n ? {\n optedIn: this.state.optedInToMarketing === true,\n decisionMade: this.state.marketingConsentDecisionMade === true,\n }\n : {\n optedIn: this.state.optedIn,\n decisionMade: this.state.consentDecisionMade === true,\n };\n }\n\n #allowedPurposePreferences(purposes: AnalyticsPurpose[]): {\n product: boolean;\n marketing: boolean;\n } {\n return {\n product:\n purposes.includes(AnalyticsPurpose.Product) &&\n this.#consent(AnalyticsPurpose.Product).optedIn,\n marketing:\n purposes.includes(AnalyticsPurpose.Marketing) &&\n this.#consent(AnalyticsPurpose.Marketing).optedIn,\n };\n }\n\n #hasAllowedPurpose(purposes: AnalyticsPurpose[]): boolean {\n const { product, marketing } = this.#allowedPurposePreferences(purposes);\n return product || marketing;\n }\n\n #hasUndecidedPurpose(purposes: AnalyticsPurpose[]): boolean {\n return purposes.some((purpose) => !this.#consent(purpose).decisionMade);\n }\n\n #isCaptureAllowed(purposes: AnalyticsPurpose[]): boolean {\n return (\n this.#hasAllowedPurpose(purposes) ||\n (this.#isPreConsentQueueEnabled && this.#hasUndecidedPurpose(purposes))\n );\n }\n\n #replaceQueue(field: AnalyticsQueue, nextQueue: Record<string, Json>): void {\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state[field] = nextQueue as never;\n });\n }\n\n /**\n * Send final track payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param eventName - The name of the event.\n * @param properties - Optional event properties.\n * @param context - Optional platform-specific context.\n * @param purposes - Capture-time purposes for the event.\n * @param version - Capture-time events config version.\n */\n #sendOrQueueTrackEvent(\n eventName: string,\n properties: AnalyticsEventProperties | undefined,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n const isAllowed = this.#hasAllowedPurpose(purposes);\n const contextWithConsent = this.#withConsentContext(\n purposes,\n context,\n version,\n );\n\n // Direct delivery: enabled and not persisting.\n if (isAllowed && !this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.track(eventName, properties, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedTrackEvent = {\n type: 'track',\n eventName,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n context: contextWithConsent,\n eventPurposes: purposes,\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n\n if (!isAllowed) {\n this.#enqueuePreConsentEvent(queuedEvent);\n return;\n }\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final identify payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param userId - The user ID.\n * @param traits - Optional user traits.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueIdentifyEvent(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n ): void {\n const purposes = [AnalyticsPurpose.Product];\n const contextWithConsent = this.#withConsentContext(purposes, context);\n\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.identify(userId, traits, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedIdentifyEvent = {\n type: 'identify',\n userId,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(traits === undefined ? {} : { traits }),\n context: contextWithConsent,\n eventPurposes: purposes,\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final view payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param name - The view name.\n * @param properties - Optional view properties.\n * @param context - Optional platform-specific context.\n * @param purposes - Capture-time purposes for the view.\n * @param version - Capture-time events config version.\n */\n #sendOrQueueViewEvent(\n name: string,\n properties: AnalyticsEventProperties | undefined,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n const isAllowed = this.#hasAllowedPurpose(purposes);\n const contextWithConsent = this.#withConsentContext(\n purposes,\n context,\n version,\n );\n\n if (isAllowed && !this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.view(name, properties, contextWithConsent);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedViewEvent = {\n type: 'view',\n name,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n context: contextWithConsent,\n eventPurposes: purposes,\n ...(version === undefined ? {} : { eventsConfigVersion: version }),\n };\n\n if (!isAllowed) {\n this.#enqueuePreConsentEvent(queuedEvent);\n return;\n }\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Add an analytics event to the queue and send it.\n *\n * @param queuedEvent - The event to enqueue and deliver.\n */\n #enqueueEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const eventQueue: Record<string, Json> = {\n ...(this.state.eventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventQueue = eventQueue as never;\n });\n\n this.#sendQueuedEvent(queuedEvent);\n }\n\n /**\n * Send a queued event through the platform adapter.\n *\n * @param queuedEvent - The queued event to deliver.\n */\n #sendQueuedEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const timestamp = new Date(queuedEvent.timestamp);\n\n if (Number.isNaN(timestamp.getTime())) {\n log('Dropping queued analytics event with invalid timestamp', {\n messageId: queuedEvent.messageId,\n });\n this.#removeQueuedEvent(queuedEvent.messageId);\n return;\n }\n\n const options: AnalyticsDeliveryOptions = {\n messageId: queuedEvent.messageId,\n timestamp,\n callback: (error?: unknown) => {\n if (error) {\n log('Queued analytics event delivery failed', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n\n this.#removeQueuedEvent(queuedEvent.messageId);\n },\n };\n\n try {\n if (queuedEvent.type === 'track') {\n this.#platformAdapter.track(\n queuedEvent.eventName,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else if (queuedEvent.type === 'identify') {\n this.#platformAdapter.identify(\n queuedEvent.userId,\n cloneDeep(queuedEvent.traits),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else {\n this.#platformAdapter.view(\n queuedEvent.name,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n }\n } catch (error) {\n log('Error sending queued analytics event', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n }\n\n /**\n * Replay persisted analytics events.\n */\n #replayQueuedEvents(): void {\n if (!this.#isEventQueuePersistenceEnabled || !this.state.eventQueue) {\n return;\n }\n\n const remainingQueue: Record<string, Json> = {};\n const eventsToSend: AnalyticsQueuedEvent[] = [];\n\n for (const [messageId, queuedEvent] of Object.entries(\n this.state.eventQueue,\n )) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n log('Dropping invalid queued analytics event', { messageId });\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n\n if (this.#hasAllowedPurpose(purposes)) {\n const refreshedEvent = this.#refreshQueuedEventConsent(queuedEvent);\n remainingQueue[messageId] = refreshedEvent;\n eventsToSend.push(refreshedEvent);\n }\n }\n\n this.#replaceQueue(AnalyticsQueue.EventQueue, remainingQueue);\n\n for (const queuedEvent of eventsToSend) {\n this.#sendQueuedEvent(queuedEvent);\n }\n }\n\n /**\n * Remove a queued analytics event.\n *\n * @param messageId - The queued event message ID.\n */\n #removeQueuedEvent(messageId: string): void {\n const currentEventQueue = this.state.eventQueue;\n\n if (\n !currentEventQueue ||\n !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)\n ) {\n return;\n }\n\n const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventQueue = eventQueue as never;\n });\n }\n\n #refreshQueuedEventConsent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsQueuedEvent {\n // Refresh only the consent stamp. Capture-time `eventPurposes` and\n // `eventsConfigVersion` stay as a pair and are never rewritten here.\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n const preferences = this.#allowedPurposePreferences(purposes);\n const existingPreferences = isJsonRecord(queuedEvent.context?.consent)\n ? queuedEvent.context.consent.categoryPreferences\n : undefined;\n\n if (\n isJsonRecord(existingPreferences) &&\n existingPreferences.product === preferences.product &&\n existingPreferences.marketing === preferences.marketing\n ) {\n return queuedEvent;\n }\n\n return {\n ...queuedEvent,\n context: this.#withConsentContext(\n purposes,\n queuedEvent.context,\n queuedEvent.eventsConfigVersion,\n ),\n };\n }\n\n /**\n * Prune a queue after a consent change.\n *\n * For {@link AnalyticsQueue.EventQueue}, entries are kept only while at least\n * one capture-time purpose is opted in, and their consent stamp is refreshed.\n * For {@link AnalyticsQueue.PreConsentEventQueue}, entries are kept while at\n * least one purpose is still allowed or undecided.\n *\n * @param field - The queue to prune.\n */\n #pruneQueueForConsent(field: AnalyticsQueue): void {\n const queue = this.state[field];\n if (!queue) {\n return;\n }\n\n const nextQueue: Record<string, Json> = {};\n for (const [messageId, queuedEvent] of Object.entries(queue)) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n const isAllowed = this.#hasAllowedPurpose(purposes);\n\n if (field === AnalyticsQueue.EventQueue) {\n if (isAllowed) {\n nextQueue[messageId] = this.#refreshQueuedEventConsent(queuedEvent);\n }\n }\n\n if (field === AnalyticsQueue.PreConsentEventQueue) {\n if (isAllowed || this.#hasUndecidedPurpose(purposes)) {\n nextQueue[messageId] = queuedEvent;\n }\n }\n }\n\n this.#replaceQueue(field, nextQueue);\n }\n\n /**\n * Add an event to the pre-consent queue without delivering it.\n *\n * @param queuedEvent - The event to hold until the user opts in.\n */\n #enqueuePreConsentEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const preConsentEventQueue: Record<string, Json> = {\n ...(this.state.preConsentEventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.preConsentEventQueue = preConsentEventQueue as never;\n });\n }\n\n /**\n * Enrich a pre-consent event with the geolocation resolved on opt-in.\n *\n * Pre-consent events are captured while geolocation is not yet resolved, so\n * they are re-enriched here as they replay. Anonymous track payloads are left\n * untouched, since they must never carry location.\n *\n * @param queuedEvent - The queued pre-consent event.\n * @returns The event with its context enriched, or the event unchanged when\n * enrichment does not apply.\n */\n #enrichPreConsentEvent(\n queuedEvent: AnalyticsQueuedEvent,\n ): AnalyticsQueuedEvent {\n if (\n queuedEvent.type === 'track' &&\n queuedEvent.properties?.anonymous === true\n ) {\n return queuedEvent;\n }\n\n const context = this.#withLocationContext(queuedEvent.context);\n\n return {\n ...queuedEvent,\n ...(context === undefined ? {} : { context }),\n };\n }\n\n /**\n * Replay eligible pre-consent events against current consent.\n *\n * Allowed entries are replayed, undecided entries are kept for later, and\n * entries with no remaining allowed or undecided purpose are dropped. The\n * keep set is written before replay so events cannot be re-queued or\n * replayed twice.\n *\n * If the pre-consent queue is disabled, any stale persisted entries (e.g. from\n * a previous session where it was enabled) are dropped so they can never be\n * replayed.\n */\n #replayPreConsentEvents(): void {\n const queue = this.state.preConsentEventQueue;\n\n if (!queue) {\n return;\n }\n\n if (!this.#isPreConsentQueueEnabled) {\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.preConsentEventQueue = {} as never;\n });\n return;\n }\n\n const keep: Record<string, Json> = {};\n const replay: AnalyticsQueuedEvent[] = [];\n\n for (const [messageId, queuedEvent] of Object.entries(queue)) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n continue;\n }\n\n const purposes = this.#purposesFromQueuedEvent(queuedEvent);\n\n if (this.#hasAllowedPurpose(purposes)) {\n replay.push(queuedEvent);\n } else if (this.#hasUndecidedPurpose(purposes)) {\n keep[messageId] = queuedEvent;\n }\n }\n\n this.#replaceQueue(AnalyticsQueue.PreConsentEventQueue, keep);\n\n for (const queuedEvent of replay) {\n const eventToReplay = this.#refreshQueuedEventConsent(\n this.#enrichPreConsentEvent(queuedEvent),\n );\n\n if (this.#isEventQueuePersistenceEnabled) {\n this.#enqueueEvent(eventToReplay);\n } else {\n this.#sendQueuedEvent(eventToReplay);\n }\n }\n }\n\n /**\n * Reconcile persisted event fragments on initialization.\n *\n * A fragment describes a journey that was in progress when the previous\n * session ended. Only fragments that opted into `persist` and are younger\n * than {@link EVENT_FRAGMENT_MAX_AGE} can be resumed, so the rest are\n * discarded. Nothing is emitted: a journey that never reached its own\n * finalization is not a failure, just an unfinished one.\n *\n * If the feature is disabled (e.g. a previous session had it enabled), or the\n * consent state no longer allows capture for any of a fragment's purposes,\n * those fragments are dropped so none of them can linger.\n *\n * Non-persistent fragments are dropped only when their ID and `createdAt`\n * match a fragment present at the start of {@link init}. Fragments created\n * or replaced while init is in flight are kept so a slow startup path cannot\n * discard an in-progress journey, as long as they have not expired.\n *\n * @param initEventFragmentSnapshot - Fragment IDs and `createdAt` values\n * present when {@link init} began.\n */\n #reconcileEventFragments(\n initEventFragmentSnapshot: Map<string, number>,\n ): void {\n const fragments = this.state.eventFragments;\n\n if (!fragments) {\n return;\n }\n\n if (!this.#isEventFragmentsEnabled) {\n this.#clearEventFragments();\n return;\n }\n\n const eventFragments: AnalyticsEventFragments = {};\n const now = Date.now();\n\n for (const [id, fragment] of Object.entries(fragments)) {\n if (!isAnalyticsEventFragment(fragment) || fragment.id !== id) {\n log('Dropping invalid persisted event fragment', { id });\n continue;\n }\n\n if (now - fragment.lastUpdated > EVENT_FRAGMENT_MAX_AGE) {\n log('Dropping expired persisted event fragment', { id });\n continue;\n }\n\n if (!this.#isCaptureAllowed(this.#purposesFromFragment(fragment))) {\n continue;\n }\n\n const snapshotCreatedAt = initEventFragmentSnapshot.get(id);\n\n if (\n fragment.persist === true ||\n snapshotCreatedAt === undefined ||\n fragment.createdAt !== snapshotCreatedAt\n ) {\n eventFragments[id] = fragment;\n }\n }\n\n if (Object.keys(eventFragments).length === 0) {\n this.#clearEventFragments();\n return;\n }\n\n if (Object.keys(eventFragments).length === Object.keys(fragments).length) {\n return;\n }\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Read an event fragment from state without the feature guard.\n *\n * @param id - The fragment ID.\n * @returns The fragment, or `undefined` when no fragment has that ID.\n */\n #getEventFragment(id: string): AnalyticsEventFragment | undefined {\n return this.state.eventFragments?.[id];\n }\n\n /**\n * Write an event fragment to state, replacing any fragment with the same ID.\n *\n * @param fragment - The fragment to store.\n * @returns The stored fragment with capture-time purpose metadata.\n */\n #setEventFragment(fragment: AnalyticsEventFragment): AnalyticsEventFragment {\n // Snapshot classification only. Consent is stamped at emit time by\n // {@link #trackEvent}, so fragment.context stays caller metadata.\n let fragmentWithPurposeSnapshot = fragment;\n if (fragment.eventPurposes === undefined) {\n const names = this.#eventNamesFromFragment(fragment);\n const eventPurposes = Object.fromEntries(\n names.map((name) => [name, this.#purposesFromName(name)]),\n );\n fragmentWithPurposeSnapshot = {\n ...fragment,\n ...(names.length === 0 ? {} : { eventPurposes }),\n ...(this.#eventsConfigVersion === undefined\n ? {}\n : { eventsConfigVersion: this.#eventsConfigVersion }),\n };\n }\n\n const eventFragments: AnalyticsEventFragments = {\n ...this.state.eventFragments,\n [fragmentWithPurposeSnapshot.id]: fragmentWithPurposeSnapshot,\n };\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n\n return fragmentWithPurposeSnapshot;\n }\n\n /**\n * Remove an event fragment from state.\n *\n * @param id - The fragment ID.\n */\n #removeEventFragment(id: string): void {\n const currentEventFragments = this.state.eventFragments;\n\n if (\n !currentEventFragments ||\n !Object.prototype.hasOwnProperty.call(currentEventFragments, id)\n ) {\n return;\n }\n\n const { [id]: _deletedFragment, ...eventFragments } = currentEventFragments;\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Drop event fragments that the current consent state no longer allows to\n * accumulate.\n */\n #pruneEventFragmentsForConsent(): void {\n const fragments = this.state.eventFragments;\n\n if (!fragments || Object.keys(fragments).length === 0) {\n return;\n }\n\n const eventFragments: AnalyticsEventFragments = {};\n for (const [id, fragment] of Object.entries(fragments)) {\n if (\n isAnalyticsEventFragment(fragment) &&\n this.#isCaptureAllowed(this.#purposesFromFragment(fragment))\n ) {\n eventFragments[id] = fragment;\n }\n }\n\n this.update((state) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n state.eventFragments = eventFragments as never;\n });\n }\n\n /**\n * Drop queued events and fragments that the current consent state no longer\n * allows to keep.\n */\n #pruneAllForConsent(): void {\n this.#pruneQueueForConsent(AnalyticsQueue.EventQueue);\n this.#pruneQueueForConsent(AnalyticsQueue.PreConsentEventQueue);\n this.#pruneEventFragmentsForConsent();\n }\n\n /**\n * Clear all event fragments.\n */\n #clearEventFragments(): void {\n if (\n !this.state.eventFragments ||\n Object.keys(this.state.eventFragments).length === 0\n ) {\n return;\n }\n\n this.update((state) => {\n state.eventFragments = {};\n });\n }\n\n /**\n * Returns whether an event fragment call should be ignored, either because\n * the feature is disabled or because the consent state does not allow\n * capture. The ignored call is logged so a missing `isEventFragmentsEnabled`\n * or an unexpected consent state is diagnosable rather than silent.\n *\n * Consent is checked on every call, not just on the ones that emit, so a\n * fragment never accumulates data for an event that could not be delivered.\n *\n * @param method - The name of the method that was called.\n * @param fragment - The fragment being read or written, when one is known.\n * @returns True when the call should be ignored.\n */\n #shouldIgnoreEventFragmentCall(\n method: string,\n fragment?: Pick<\n AnalyticsEventFragment,\n 'initialEvent' | 'successEvent' | 'failureEvent' | 'eventPurposes'\n >,\n ): boolean {\n if (!this.#isEventFragmentsEnabled) {\n log(\n 'Ignoring event fragment call because the event fragments feature is disabled',\n { method },\n );\n\n return true;\n }\n\n const captureAllowed = fragment\n ? this.#isCaptureAllowed(this.#purposesFromFragment(fragment))\n : this.#isCaptureAllowed(Object.values(AnalyticsPurpose));\n\n if (!captureAllowed) {\n log(\n 'Ignoring event fragment call because the consent state does not allow capturing analytics',\n { method },\n );\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Emit one of an event fragment's events, carrying the properties the\n * fragment has accumulated.\n *\n * Delivery goes through {@link trackEvent}, so consent gating, the anonymous\n * payload split, the pre-consent queue and geolocation enrichment all apply.\n *\n * @param fragment - The fragment supplying the properties.\n * @param name - The name of the event to emit.\n * @param context - The context to send with the event.\n */\n #emitEventFragment(\n fragment: AnalyticsEventFragment,\n name: string,\n context: AnalyticsContext | undefined,\n ): void {\n const properties = { ...fragment.properties };\n const sensitiveProperties = { ...fragment.sensitiveProperties };\n\n this.#trackEvent(\n {\n name,\n properties,\n sensitiveProperties,\n saveDataRecording: false,\n hasProperties:\n Object.keys(properties).length > 0 ||\n Object.keys(sensitiveProperties).length > 0,\n },\n context,\n this.#purposesFromFragmentEvent(fragment, name),\n fragment.eventsConfigVersion,\n );\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void {\n this.#trackEvent(\n event,\n context,\n this.#purposesFromName(event.name),\n this.#eventsConfigVersion,\n );\n }\n\n #trackEvent(\n event: AnalyticsTrackingEvent,\n context: AnalyticsContext | undefined,\n purposes: AnalyticsPurpose[],\n version: string | undefined,\n ): void {\n // An event captured while the user is still undecided is held in the\n // pre-consent queue (see #sendOrQueueTrackEvent) instead of being\n // delivered, and replayed if they later opt in.\n if (!this.#isCaptureAllowed(purposes)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n undefined,\n this.#withLocationContext(context),\n purposes,\n version,\n );\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n },\n this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n },\n // When the anonymous events feature is enabled, this payload is the\n // anonymous one and must carry no geolocation. When the feature is\n // disabled, this is the single identified payload, so it is enriched.\n this.#isAnonymousEventsFeatureEnabled\n ? context\n : this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n this.#sendOrQueueIdentifyEvent(\n this.state.analyticsId,\n traits,\n this.#withLocationContext(context),\n );\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackView(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n const purposes = this.#purposesFromName(name);\n const version = this.#eventsConfigVersion;\n if (!this.#isCaptureAllowed(purposes)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#sendOrQueueViewEvent(\n name,\n properties,\n this.#withLocationContext(context),\n purposes,\n version,\n );\n }\n\n /**\n * Create an event fragment.\n *\n * A fragment accumulates properties across a user journey so that several\n * parts of a client can contribute to the same set of events without\n * re-deriving them. Declaring `successEvent` and `failureEvent` turns the\n * fragment into a funnel that {@link finalizeEventFragment} closes. Declaring\n * none of the event names makes it a pure property bag that the client reads\n * back with {@link getEventFragmentById} when it emits its own events.\n *\n * Any existing fragment with the same ID is replaced, so a new journey never\n * inherits properties from a stale one.\n *\n * Nothing is created unless the user is opted in, or undecided with the\n * pre-consent queue enabled, so an opted-out user accumulates no fragment\n * data.\n *\n * @param options - The fragment definition. An ID is generated when one is\n * not supplied.\n * @returns A read-only copy of the created fragment, or `undefined` when the\n * event fragments feature is disabled or the consent state does not allow\n * capture. Mutating the returned object does not change controller state.\n * Use {@link updateEventFragment} or {@link upsertEventFragment} to write.\n */\n createEventFragment(\n options: AnalyticsEventFragmentOptions = {},\n ): ReadonlyAnalyticsEventFragment | undefined {\n // Classify create from event names only. Caller consent context must not\n // affect the event-purpose snapshot.\n if (\n this.#shouldIgnoreEventFragmentCall('createEventFragment', {\n initialEvent: options.initialEvent,\n successEvent: options.successEvent,\n failureEvent: options.failureEvent,\n })\n ) {\n return undefined;\n }\n\n const now = Date.now();\n\n const fragment = this.#setEventFragment({\n id: options.id ?? uuid(),\n properties: { ...(options.properties ?? {}) },\n sensitiveProperties: { ...(options.sensitiveProperties ?? {}) },\n createdAt: now,\n lastUpdated: now,\n ...(options.initialEvent === undefined\n ? {}\n : { initialEvent: options.initialEvent }),\n ...(options.successEvent === undefined\n ? {}\n : { successEvent: options.successEvent }),\n ...(options.failureEvent === undefined\n ? {}\n : { failureEvent: options.failureEvent }),\n ...(options.context === undefined\n ? {}\n : { context: { ...options.context } }),\n ...(options.persist === undefined ? {} : { persist: options.persist }),\n });\n\n if (fragment.initialEvent) {\n this.#emitEventFragment(\n fragment,\n fragment.initialEvent,\n fragment.context,\n );\n }\n\n return cloneDeep(fragment);\n }\n\n /**\n * Write to an event fragment, creating a property bag if none exists.\n *\n * This is the ergonomic entry point for contributors that do not know\n * whether the journey has been started yet, and it avoids the read then\n * write race a caller would otherwise have to implement itself.\n *\n * @param id - The fragment ID.\n * @param payload - The properties and context to merge in.\n */\n upsertEventFragment(\n id: string,\n payload: AnalyticsEventFragmentPayload = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (\n this.#shouldIgnoreEventFragmentCall('upsertEventFragment', fragment ?? {})\n ) {\n return;\n }\n\n if (!fragment) {\n this.createEventFragment({ id, ...payload });\n return;\n }\n\n this.#setEventFragment(mergeEventFragment(fragment, payload));\n }\n\n /**\n * Write to an existing event fragment.\n *\n * @param id - The fragment ID.\n * @param payload - The properties and context to merge in.\n * @throws Error if no fragment has that ID when the call is not ignored.\n * Use {@link upsertEventFragment} when the fragment may not exist yet.\n * When the event fragments feature is disabled or the consent state does not\n * allow capture, the call is a logged no-op and does not throw.\n */\n updateEventFragment(\n id: string,\n payload: AnalyticsEventFragmentPayload = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('updateEventFragment', fragment)) {\n return;\n }\n\n if (!fragment) {\n throw new Error(`Event fragment with id ${id} does not exist.`);\n }\n\n this.#setEventFragment(mergeEventFragment(fragment, payload));\n }\n\n /**\n * Read an event fragment.\n *\n * @param id - The fragment ID.\n * @returns A read-only copy of the fragment, or `undefined` when no fragment\n * has that ID, the event fragments feature is disabled, or the consent state\n * does not allow capture. Mutating the returned object does not change\n * controller state. Use {@link updateEventFragment} or\n * {@link upsertEventFragment} to write.\n */\n getEventFragmentById(id: string): ReadonlyAnalyticsEventFragment | undefined {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('getEventFragmentById', fragment)) {\n return undefined;\n }\n\n return fragment === undefined ? undefined : cloneDeep(fragment);\n }\n\n /**\n * Discard an event fragment without emitting anything.\n *\n * @param id - The fragment ID.\n */\n deleteEventFragment(id: string): void {\n const fragment = this.#getEventFragment(id);\n if (this.#shouldIgnoreEventFragmentCall('deleteEventFragment', fragment)) {\n return;\n }\n\n this.#removeEventFragment(id);\n }\n\n /**\n * Close an event fragment, emitting its closing event and discarding it.\n *\n * The event emitted is `failureEvent` when the journey was abandoned and\n * `successEvent` otherwise. A fragment that does not declare the relevant\n * event name is discarded silently, which is what makes a pure property bag\n * possible.\n *\n * @param id - The fragment ID.\n * @param options - Finalization options.\n * @param options.abandoned - Whether the journey was abandoned.\n * @param options.context - Context merged over the fragment's own context.\n * @throws Error if no fragment has that ID when the call is not ignored.\n * When the event fragments feature is disabled or the consent state does not\n * allow capture, the call is a logged no-op and does not throw.\n */\n finalizeEventFragment(\n id: string,\n { abandoned = false, context }: AnalyticsEventFragmentFinalizeOptions = {},\n ): void {\n const fragment = this.#getEventFragment(id);\n if (\n this.#shouldIgnoreEventFragmentCall('finalizeEventFragment', fragment)\n ) {\n return;\n }\n\n if (!fragment) {\n throw new Error(`Event fragment with id ${id} does not exist.`);\n }\n\n const eventName = abandoned ? fragment.failureEvent : fragment.successEvent;\n\n if (eventName) {\n this.#emitEventFragment(\n fragment,\n eventName,\n mergeEventFragmentContext(fragment.context, context),\n );\n }\n\n this.#removeEventFragment(id);\n }\n\n /**\n * Opt in to analytics.\n *\n * Records that a consent decision has been made and replays any events that\n * were queued while the user was undecided.\n *\n * When geolocation enrichment is enabled, geolocation is resolved here (once\n * the user has consented) and awaited before the queued events are replayed,\n * so those events are enriched with the resolved location as they are sent.\n *\n * @returns A promise that resolves once opt-in processing has completed.\n */\n async optIn(): Promise<void> {\n this.update((state) => {\n state.optedIn = true;\n state.consentDecisionMade = true;\n });\n\n // Now that the user has consented, resolve geolocation (once) and wait for\n // it so the queued pre-consent events can be enriched as they replay.\n await this.#maybeResolveLocation();\n\n // Reconcile against the current state rather than replaying blindly: the\n // consent decision may have changed while geolocation was resolving (e.g.\n // resetConsentDecision ran during the await), and preserved pre-consent\n // events must not be delivered once the user is no longer opted in.\n this.#replayPreConsentEvents();\n }\n\n /**\n * Opt out of analytics.\n *\n * Records that a consent decision has been made and discards any persisted\n * events and in-progress event fragments so nothing captured before the\n * decision is ever delivered.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n state.consentDecisionMade = true;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Reset the consent decision back to undecided.\n *\n * Intended for client flows that restart onboarding. Clears the opt-in\n * preference and discards the delivery queue, but preserves any pre-consent\n * events so they can still be replayed if the user opts in again. The user is\n * treated as undecided again.\n *\n * In-progress event fragments are kept only while the undecided user can\n * still accumulate them, and discarded otherwise, so no fragment outlives the\n * consent state that allowed it.\n */\n resetConsentDecision(): void {\n this.update((state) => {\n state.optedIn = false;\n state.consentDecisionMade = false;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Opt in to marketing analytics.\n *\n * Independent of {@link optIn}. Replays queued marketing events.\n *\n * @returns A promise that resolves once opt-in processing has completed.\n */\n async optInToMarketing(): Promise<void> {\n this.update((state) => {\n state.optedInToMarketing = true;\n state.marketingConsentDecisionMade = true;\n });\n\n await this.#maybeResolveLocation();\n this.#replayPreConsentEvents();\n }\n\n /**\n * Opt out of marketing analytics.\n *\n * Independent of {@link optOut}. Discards queued marketing events and\n * marketing event fragments.\n */\n optOutOfMarketing(): void {\n this.update((state) => {\n state.optedInToMarketing = false;\n state.marketingConsentDecisionMade = true;\n state.marketingCampaignCookieId = null;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Reset the marketing consent decision back to undecided.\n *\n * Independent of {@link resetConsentDecision}.\n */\n resetMarketingConsentDecision(): void {\n this.update((state) => {\n state.optedInToMarketing = false;\n state.marketingConsentDecisionMade = false;\n state.marketingCampaignCookieId = null;\n });\n\n this.#pruneAllForConsent();\n }\n\n /**\n * Set the marketing campaign cookie ID.\n *\n * Stores the ID of the marketing campaign cookie (e.g. a Google Analytics\n * client ID) that was active when the user arrived. Pass `null` to clear it.\n * The value is automatically cleared by {@link optOutOfMarketing} and\n * {@link resetMarketingConsentDecision}.\n *\n * @param marketingCampaignCookieId - The marketing campaign cookie ID, or\n * `null` to clear it.\n */\n setMarketingCampaignCookieId(marketingCampaignCookieId: string | null): void {\n this.update((state) => {\n state.marketingCampaignCookieId = marketingCampaignCookieId;\n });\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/analytics-controller",
|
|
3
|
-
"version": "3.2.0-preview-
|
|
3
|
+
"version": "3.2.0-preview-85a915769",
|
|
4
4
|
"description": "Common Analytics controller for event tracking",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -51,6 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@metamask/base-controller": "^10.0.0",
|
|
54
|
+
"@metamask/config-registry-controller": "^4.0.0",
|
|
54
55
|
"@metamask/geolocation-controller": "^2.0.0",
|
|
55
56
|
"@metamask/messenger": "^3.0.0",
|
|
56
57
|
"@metamask/utils": "^12.0.0",
|