@mparticle/web-rokt-kit 1.22.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1284 +1,2 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- /* eslint-disable no-undef */
6
- // Copyright 2025 mParticle, Inc.
7
- //
8
- // Licensed under the Apache License, Version 2.0 (the "License");
9
- // you may not use this file except in compliance with the License.
10
- // You may obtain a copy of the License at
11
- //
12
- // http://www.apache.org/licenses/LICENSE-2.0
13
- //
14
- // Unless required by applicable law or agreed to in writing, software
15
- // distributed under the License is distributed on an "AS IS" BASIS,
16
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
- // See the License for the specific language governing permissions and
18
- // limitations under the License.
19
-
20
- var name = 'Rokt';
21
- var moduleId = 181;
22
- var EVENT_NAME_SELECT_PLACEMENTS = 'selectPlacements';
23
-
24
- var constructor = function () {
25
- var self = this;
26
- var PerformanceMarks = {
27
- RoktScriptAppended: 'mp:RoktScriptAppended',
28
- };
29
-
30
- var EMAIL_SHA256_KEY = 'emailsha256';
31
-
32
- // Dynamic identity type for Rokt's emailsha256 identity value which MP doesn't natively support - will be set during initialization
33
- var mappedEmailSha256Key;
34
-
35
- self.name = name;
36
- self.moduleId = moduleId;
37
- self.isInitialized = false;
38
-
39
- self.launcher = null;
40
- self.filters = {};
41
- self.userAttributes = {};
42
- self.testHelpers = null;
43
- self.placementEventMappingLookup = {};
44
- self.placementEventAttributeMappingLookup = {};
45
- self.eventQueue = [];
46
- self.eventStreamQueue = [];
47
- self.integrationName = null;
48
-
49
- function getEventAttributeValue(event, eventAttributeKey) {
50
- var attributes = event && event.EventAttributes;
51
- if (!attributes) {
52
- return null;
53
- }
54
-
55
- if (typeof attributes[eventAttributeKey] === 'undefined') {
56
- return null;
57
- }
58
-
59
- return attributes[eventAttributeKey];
60
- }
61
-
62
- function doesEventAttributeConditionMatch(condition, actualValue) {
63
- if (!condition || !isString(condition.operator)) {
64
- return false;
65
- }
66
-
67
- var operator = condition.operator.toLowerCase();
68
- var expectedValue = condition.attributeValue;
69
-
70
- if (operator === 'exists') {
71
- return actualValue !== null;
72
- }
73
-
74
- if (actualValue == null) {
75
- return false;
76
- }
77
-
78
- if (operator === 'equals') {
79
- return String(actualValue) === String(expectedValue);
80
- }
81
-
82
- if (operator === 'contains') {
83
- return String(actualValue).indexOf(String(expectedValue)) !== -1;
84
- }
85
-
86
- return false;
87
- }
88
-
89
- function doesEventMatchRule(event, rule) {
90
- if (!rule || !isString(rule.eventAttributeKey)) {
91
- return false;
92
- }
93
-
94
- var conditions = rule.conditions;
95
- if (!Array.isArray(conditions)) {
96
- return false;
97
- }
98
-
99
- var actualValue = getEventAttributeValue(event, rule.eventAttributeKey);
100
-
101
- if (conditions.length === 0) {
102
- return actualValue !== null;
103
- }
104
- for (var i = 0; i < conditions.length; i++) {
105
- if (!doesEventAttributeConditionMatch(conditions[i], actualValue)) {
106
- return false;
107
- }
108
- }
109
-
110
- return true;
111
- }
112
-
113
- function generateMappedEventAttributeLookup(
114
- placementEventAttributeMapping
115
- ) {
116
- var mappedAttributeKeys = {};
117
- if (!Array.isArray(placementEventAttributeMapping)) {
118
- return mappedAttributeKeys;
119
- }
120
- for (var i = 0; i < placementEventAttributeMapping.length; i++) {
121
- var mapping = placementEventAttributeMapping[i];
122
- if (
123
- !mapping ||
124
- !isString(mapping.value) ||
125
- !isString(mapping.map)
126
- ) {
127
- continue;
128
- }
129
-
130
- var mappedAttributeKey = mapping.value;
131
- var eventAttributeKey = mapping.map;
132
-
133
- if (!mappedAttributeKeys[mappedAttributeKey]) {
134
- mappedAttributeKeys[mappedAttributeKey] = [];
135
- }
136
-
137
- mappedAttributeKeys[mappedAttributeKey].push({
138
- eventAttributeKey: eventAttributeKey,
139
- conditions: Array.isArray(mapping.conditions)
140
- ? mapping.conditions
141
- : [],
142
- });
143
- }
144
- return mappedAttributeKeys;
145
- }
146
-
147
- function applyPlacementEventAttributeMapping(event) {
148
- var mappedAttributeKeys = Object.keys(
149
- self.placementEventAttributeMappingLookup
150
- );
151
- for (var i = 0; i < mappedAttributeKeys.length; i++) {
152
- var mappedAttributeKey = mappedAttributeKeys[i];
153
- var rulesForMappedAttributeKey =
154
- self.placementEventAttributeMappingLookup[mappedAttributeKey];
155
- if (isEmpty(rulesForMappedAttributeKey)) {
156
- continue;
157
- }
158
-
159
- // Require ALL rules for the same key to match (AND).
160
- var allMatch = true;
161
- for (var j = 0; j < rulesForMappedAttributeKey.length; j++) {
162
- if (!doesEventMatchRule(event, rulesForMappedAttributeKey[j])) {
163
- allMatch = false;
164
- break;
165
- }
166
- }
167
- if (!allMatch) {
168
- continue;
169
- }
170
-
171
- window.mParticle.Rokt.setLocalSessionAttribute(
172
- mappedAttributeKey,
173
- true
174
- );
175
- }
176
- }
177
-
178
- /**
179
- * Generates the Rokt launcher script URL with optional domain override and extensions
180
- * @param {string} domain - The CNAME domain to use for overriding the launcher url
181
- * @param {Array<string>} extensions - List of extension query parameters to append
182
- * @returns {string} The complete launcher script URL
183
- */
184
- function generateLauncherScript(_domain, extensions) {
185
- // Override domain if a customer is using a CNAME
186
- // If a customer is using a CNAME, a domain will be passed. If not, we use the default domain.
187
- var domain = typeof _domain !== 'undefined' ? _domain : 'apps.rokt.com';
188
- var protocol = 'https://';
189
- var launcherPath = '/wsdk/integrations/launcher.js';
190
- var baseUrl = [protocol, domain, launcherPath].join('');
191
-
192
- if (!extensions || extensions.length === 0) {
193
- return baseUrl;
194
- }
195
- return baseUrl + '?extensions=' + extensions.join(',');
196
- }
197
-
198
- /**
199
- * Checks if Rokt launcher is available and ready to attach
200
- * @returns {boolean} True if launcher can be attached
201
- */
202
- function isLauncherReadyToAttach() {
203
- return window.Rokt && typeof window.Rokt.createLauncher === 'function';
204
- }
205
-
206
- /**
207
- * Passes attributes to the Rokt Web SDK for client-side hashing
208
- * @see https://docs.rokt.com/developers/integration-guides/web/library/integration-launcher#hash-attributes
209
- * @param {Object} attributes - The attributes to be hashed
210
- * @returns {Promise<Object|null>} A Promise resolving to the
211
- * hashed attributes from the launcher, or `null` if the kit is not initialized
212
- */
213
- function hashAttributes(attributes) {
214
- if (!isKitReady()) {
215
- console.error('Rokt Kit: Not initialized');
216
- return null;
217
- }
218
- return self.launcher.hashAttributes(attributes);
219
- }
220
-
221
- function initForwarder(
222
- settings,
223
- _service,
224
- testMode,
225
- _trackerId,
226
- filteredUserAttributes
227
- ) {
228
- var accountId = settings.accountId;
229
- var roktExtensions = extractRoktExtensions(settings.roktExtensions);
230
- self.userAttributes = filteredUserAttributes || {};
231
- self.onboardingExpProvider = settings.onboardingExpProvider;
232
-
233
- var placementEventMapping = parseSettingsString(
234
- settings.placementEventMapping
235
- );
236
- self.placementEventMappingLookup = generateMappedEventLookup(
237
- placementEventMapping
238
- );
239
-
240
- var placementEventAttributeMapping = parseSettingsString(
241
- settings.placementEventAttributeMapping
242
- );
243
- self.placementEventAttributeMappingLookup =
244
- generateMappedEventAttributeLookup(placementEventAttributeMapping);
245
-
246
- // Set dynamic OTHER_IDENTITY based on server settings
247
- // Convert to lowercase since server sends TitleCase (e.g., 'Other' -> 'other')
248
- if (settings.hashedEmailUserIdentityType) {
249
- mappedEmailSha256Key =
250
- settings.hashedEmailUserIdentityType.toLowerCase();
251
- }
252
-
253
- var domain = window.mParticle.Rokt.domain;
254
- var launcherOptions = mergeObjects(
255
- {},
256
- window.mParticle.Rokt.launcherOptions || {}
257
- );
258
- self.integrationName = generateIntegrationName(
259
- launcherOptions.integrationName
260
- );
261
- launcherOptions.integrationName = self.integrationName;
262
-
263
- self.domain = domain;
264
-
265
- // Register reporting services with the core SDK
266
- var reportingConfig = {
267
- loggingUrl: settings.loggingUrl,
268
- errorUrl: settings.errorUrl,
269
- isLoggingEnabled:
270
- settings.isLoggingEnabled === 'true' ||
271
- settings.isLoggingEnabled === true,
272
- };
273
- var errorReportingService = new ErrorReportingService(
274
- reportingConfig,
275
- self.integrationName,
276
- window.__rokt_li_guid__,
277
- settings.accountId
278
- );
279
- var loggingService = new LoggingService(
280
- reportingConfig,
281
- errorReportingService,
282
- self.integrationName,
283
- window.__rokt_li_guid__,
284
- settings.accountId
285
- );
286
-
287
- self.errorReportingService = errorReportingService;
288
- self.loggingService = loggingService;
289
-
290
- if (
291
- window.mParticle &&
292
- window.mParticle._registerErrorReportingService
293
- ) {
294
- window.mParticle._registerErrorReportingService(
295
- errorReportingService
296
- );
297
- }
298
- if (window.mParticle && window.mParticle._registerLoggingService) {
299
- window.mParticle._registerLoggingService(loggingService);
300
- }
301
-
302
- if (testMode) {
303
- self.testHelpers = {
304
- generateLauncherScript: generateLauncherScript,
305
- extractRoktExtensions: extractRoktExtensions,
306
- hashEventMessage: hashEventMessage,
307
- parseSettingsString: parseSettingsString,
308
- generateMappedEventLookup: generateMappedEventLookup,
309
- generateMappedEventAttributeLookup:
310
- generateMappedEventAttributeLookup,
311
- sendAdBlockMeasurementSignals: sendAdBlockMeasurementSignals,
312
- createAutoRemovedIframe: createAutoRemovedIframe,
313
- djb2: djb2,
314
- setAllowedOriginHashes: function (hashes) {
315
- _allowedOriginHashes = hashes;
316
- },
317
- ReportingTransport: ReportingTransport,
318
- ErrorReportingService: ErrorReportingService,
319
- LoggingService: LoggingService,
320
- RateLimiter: RateLimiter,
321
- ErrorCodes: ErrorCodes,
322
- WSDKErrorSeverity: WSDKErrorSeverity,
323
- };
324
- attachLauncher(accountId, launcherOptions);
325
- return;
326
- }
327
-
328
- if (isLauncherReadyToAttach()) {
329
- attachLauncher(accountId, launcherOptions);
330
- } else {
331
- var target = document.head || document.body;
332
- var script = document.createElement('script');
333
- script.type = 'text/javascript';
334
- script.src = generateLauncherScript(domain, roktExtensions);
335
- script.async = true;
336
- script.crossOrigin = 'anonymous';
337
- script.fetchPriority = 'high';
338
- script.id = 'rokt-launcher';
339
-
340
- script.onload = function () {
341
- if (isLauncherReadyToAttach()) {
342
- attachLauncher(accountId, launcherOptions);
343
- } else {
344
- console.error(
345
- 'Rokt object is not available after script load.'
346
- );
347
- }
348
- };
349
-
350
- script.onerror = function (error) {
351
- console.error('Error loading Rokt launcher script:', error);
352
- };
353
-
354
- target.appendChild(script);
355
- captureTiming(PerformanceMarks.RoktScriptAppended);
356
- }
357
- }
358
- /**
359
- * Returns the user identities from the filtered user, if any
360
- * @param {Object} filteredUser - The filtered user object containing identities
361
- * @returns {Object} The user identities from the filtered user
362
- */
363
- function returnUserIdentities(filteredUser) {
364
- if (!filteredUser || !filteredUser.getUserIdentities) {
365
- return {};
366
- }
367
-
368
- var userIdentities = filteredUser.getUserIdentities().userIdentities;
369
-
370
- return replaceOtherIdentityWithEmailsha256(userIdentities);
371
- }
372
-
373
- function returnLocalSessionAttributes() {
374
- if (
375
- !window.mParticle.Rokt ||
376
- typeof window.mParticle.Rokt.getLocalSessionAttributes !==
377
- 'function'
378
- ) {
379
- return {};
380
- }
381
- if (
382
- isEmpty(self.placementEventMappingLookup) &&
383
- isEmpty(self.placementEventAttributeMappingLookup)
384
- ) {
385
- return {};
386
- }
387
- return window.mParticle.Rokt.getLocalSessionAttributes();
388
- }
389
-
390
- function replaceOtherIdentityWithEmailsha256(userIdentities) {
391
- var newUserIdentities = mergeObjects({}, userIdentities || {});
392
- if (userIdentities[mappedEmailSha256Key]) {
393
- newUserIdentities[EMAIL_SHA256_KEY] =
394
- userIdentities[mappedEmailSha256Key];
395
- }
396
- delete newUserIdentities[mappedEmailSha256Key];
397
-
398
- return newUserIdentities;
399
- }
400
-
401
- /**
402
- * Selects placements for Rokt Web SDK with merged attributes, filters, and experimentation options
403
- * @see https://docs.rokt.com/developers/integration-guides/web/library/select-placements-options/
404
- * @param {Object} options - The options object for selecting placements containing:
405
- * - identifier {string}: The placement identifier
406
- * - attributes {Object}: Optional attributes to merge with existing attributes
407
- * @returns {Promise<void>} A Promise resolving to the Rokt launcher's selectPlacements method with processed attributes
408
- */
409
- function selectPlacements(options) {
410
- var attributes = (options && options.attributes) || {};
411
- var placementAttributes = mergeObjects(self.userAttributes, attributes);
412
-
413
- var filters = self.filters || {};
414
- var userAttributeFilters = filters.userAttributeFilters || [];
415
- var filteredUser = filters.filteredUser || {};
416
- var mpid =
417
- filteredUser &&
418
- filteredUser.getMPID &&
419
- typeof filteredUser.getMPID === 'function'
420
- ? filteredUser.getMPID()
421
- : null;
422
-
423
- var filteredAttributes;
424
-
425
- if (!filters) {
426
- console.warn(
427
- 'Rokt Kit: No filters available, using user attributes'
428
- );
429
-
430
- filteredAttributes = placementAttributes;
431
- } else if (filters.filterUserAttributes) {
432
- filteredAttributes = filters.filterUserAttributes(
433
- placementAttributes,
434
- userAttributeFilters
435
- );
436
- }
437
-
438
- self.userAttributes = filteredAttributes;
439
-
440
- var optimizelyAttributes =
441
- self.onboardingExpProvider === 'Optimizely'
442
- ? fetchOptimizely()
443
- : {};
444
-
445
- var filteredUserIdentities = returnUserIdentities(filteredUser);
446
-
447
- var localSessionAttributes = returnLocalSessionAttributes();
448
-
449
- var selectPlacementsAttributes = mergeObjects(
450
- filteredUserIdentities,
451
- filteredAttributes,
452
- optimizelyAttributes,
453
- localSessionAttributes,
454
- {
455
- mpid: mpid,
456
- }
457
- );
458
-
459
- var selectPlacementsOptions = mergeObjects(options, {
460
- attributes: selectPlacementsAttributes,
461
- });
462
-
463
- var selection = self.launcher.selectPlacements(selectPlacementsOptions);
464
-
465
- // After selection resolves, sync the Rokt session ID back to mParticle
466
- // as an integration attribute so server-side integrations can link events.
467
- // We log the custom event AFTER setting the attribute because
468
- // setIntegrationAttribute alone doesn't fire a network request —
469
- // if the user closes the page before another event fires, the server
470
- // would never receive the session ID.
471
- if (selection && typeof selection.then === 'function') {
472
- selection
473
- .then(function (sel) {
474
- if (sel && sel.context && sel.context.sessionId) {
475
- sel.context.sessionId
476
- .then(function (sessionId) {
477
- _setRoktSessionId(sessionId);
478
- logSelectPlacementsEvent(
479
- selectPlacementsAttributes
480
- );
481
- })
482
- .catch(function () {
483
- logSelectPlacementsEvent(
484
- selectPlacementsAttributes
485
- );
486
- });
487
- } else {
488
- logSelectPlacementsEvent(selectPlacementsAttributes);
489
- }
490
- })
491
- .catch(function () {
492
- logSelectPlacementsEvent(selectPlacementsAttributes);
493
- });
494
- } else {
495
- logSelectPlacementsEvent(selectPlacementsAttributes);
496
- }
497
-
498
- return selection;
499
- }
500
-
501
- /**
502
- * Logs a custom event when selectPlacements is called
503
- * This enables visibility and troubleshooting
504
- * @param {Object} attributes - The attributes sent to Rokt
505
- */
506
- function logSelectPlacementsEvent(attributes) {
507
- if (
508
- !window.mParticle ||
509
- typeof window.mParticle.logEvent !== 'function'
510
- ) {
511
- return;
512
- }
513
-
514
- if (!isObject(attributes)) {
515
- return;
516
- }
517
-
518
- var EVENT_TYPE_OTHER = window.mParticle.EventType.Other;
519
-
520
- window.mParticle.logEvent(
521
- EVENT_NAME_SELECT_PLACEMENTS,
522
- EVENT_TYPE_OTHER,
523
- attributes
524
- );
525
- }
526
-
527
- /**
528
- * Enables optional Integration Launcher extensions before selecting placements
529
- * @param {string} extensionName - Name of the extension to enable
530
- * @returns {Promise<*>} A Promise resolving to the extension API if available
531
- */
532
- function use(extensionName) {
533
- if (!isKitReady()) {
534
- console.error('Rokt Kit: Not initialized');
535
- return Promise.reject(new Error('Rokt Kit: Not initialized'));
536
- }
537
- if (!extensionName || !isString(extensionName)) {
538
- return Promise.reject(
539
- new Error('Rokt Kit: Invalid extension name')
540
- );
541
- }
542
- return self.launcher.use(extensionName);
543
- }
544
-
545
- /**
546
- * Sets extension data for Rokt Web SDK
547
- * @param {Object} partnerExtensionData - The extension data object containing:
548
- * - [extensionName] {string}: Name of the extension
549
- * - [extensionName].options {Object}: Key-value pairs of options for the extension
550
- * @returns {void} Nothing is returned
551
- */
552
- function setExtensionData(partnerExtensionData) {
553
- if (!isKitReady()) {
554
- console.error('Rokt Kit: Not initialized');
555
- return;
556
- }
557
-
558
- window.Rokt.setExtensionData(partnerExtensionData);
559
- }
560
-
561
- function processEventQueue() {
562
- self.eventQueue.forEach(function (event) {
563
- processEvent(event);
564
- });
565
- self.eventQueue = [];
566
- }
567
-
568
- function processEvent(event) {
569
- if (!isKitReady()) {
570
- self.eventQueue.push(event);
571
- return;
572
- }
573
-
574
- _sendEventStream(event);
575
-
576
- if (
577
- typeof window.mParticle.Rokt.setLocalSessionAttribute !== 'function'
578
- ) {
579
- return;
580
- }
581
-
582
- if (!isEmpty(self.placementEventAttributeMappingLookup)) {
583
- applyPlacementEventAttributeMapping(event);
584
- }
585
-
586
- if (isEmpty(self.placementEventMappingLookup)) {
587
- return;
588
- }
589
-
590
- var hashedEvent = hashEventMessage(
591
- event.EventDataType,
592
- event.EventCategory,
593
- event.EventName
594
- );
595
-
596
- if (self.placementEventMappingLookup[hashedEvent]) {
597
- var mappedValue = self.placementEventMappingLookup[hashedEvent];
598
- window.mParticle.Rokt.setLocalSessionAttribute(mappedValue, true);
599
- }
600
- }
601
-
602
- function _enrichEvent(event) {
603
- return mergeObjects({}, event, {
604
- UserAttributes: self.userAttributes,
605
- });
606
- }
607
-
608
- function _sendEventStream(event) {
609
- if (window.Rokt && typeof window.Rokt.__event_stream__ === 'function') {
610
- if (self.eventStreamQueue.length) {
611
- var queuedEvents = self.eventStreamQueue;
612
- self.eventStreamQueue = [];
613
- for (var i = 0; i < queuedEvents.length; i++) {
614
- window.Rokt.__event_stream__(_enrichEvent(queuedEvents[i]));
615
- }
616
- }
617
- window.Rokt.__event_stream__(_enrichEvent(event));
618
- } else {
619
- self.eventStreamQueue.push(event);
620
- }
621
- }
622
-
623
- function _setRoktSessionId(sessionId) {
624
- if (!sessionId || typeof sessionId !== 'string') {
625
- return;
626
- }
627
- try {
628
- var mpInstance = window.mParticle.getInstance();
629
- if (
630
- mpInstance &&
631
- typeof mpInstance.setIntegrationAttribute === 'function'
632
- ) {
633
- mpInstance.setIntegrationAttribute(moduleId, {
634
- roktSessionId: sessionId,
635
- });
636
- }
637
- } catch (e) {
638
- // Best effort — never let this break the partner page
639
- }
640
- }
641
-
642
- function onUserIdentified(filteredUser) {
643
- self.filters.filteredUser = filteredUser;
644
- self.userAttributes = filteredUser.getAllUserAttributes();
645
- _sendEventStream(_buildIdentityEvent('identify', filteredUser));
646
- }
647
-
648
- function _buildIdentityEvent(eventName, filteredUser) {
649
- var mpid =
650
- filteredUser.getMPID && typeof filteredUser.getMPID === 'function'
651
- ? filteredUser.getMPID()
652
- : null;
653
- var sessionId =
654
- window.mParticle &&
655
- window.mParticle.sessionManager &&
656
- typeof window.mParticle.sessionManager.getSession === 'function'
657
- ? window.mParticle.sessionManager.getSession()
658
- : null;
659
- var userIdentities =
660
- filteredUser.getUserIdentities &&
661
- typeof filteredUser.getUserIdentities === 'function'
662
- ? filteredUser.getUserIdentities().userIdentities
663
- : null;
664
-
665
- return {
666
- EventName: eventName,
667
- EventDataType: 14, // MessageType.Profile
668
- Timestamp: Date.now(),
669
- MPID: mpid,
670
- SessionId: sessionId,
671
- UserIdentities: userIdentities,
672
- };
673
- }
674
-
675
- function onLoginComplete(filteredUser) {
676
- self.userAttributes = filteredUser.getAllUserAttributes();
677
- _sendEventStream(_buildIdentityEvent('login', filteredUser));
678
- }
679
-
680
- function onLogoutComplete(filteredUser) {
681
- self.userAttributes = filteredUser.getAllUserAttributes();
682
- _sendEventStream(_buildIdentityEvent('logout', filteredUser));
683
- }
684
-
685
- function onModifyComplete(filteredUser) {
686
- self.userAttributes = filteredUser.getAllUserAttributes();
687
- _sendEventStream(_buildIdentityEvent('modify_user', filteredUser));
688
- }
689
-
690
- function setUserAttribute(key, value) {
691
- self.userAttributes[key] = value;
692
- _sendEventStream(
693
- _buildIdentityEvent(
694
- 'set_user_attributes',
695
- self.filters.filteredUser || {}
696
- )
697
- );
698
- }
699
-
700
- function removeUserAttribute(key) {
701
- delete self.userAttributes[key];
702
- }
703
-
704
- function attachLauncher(accountId, launcherOptions) {
705
- var mpSessionId =
706
- window.mParticle &&
707
- window.mParticle.sessionManager &&
708
- typeof window.mParticle.sessionManager.getSession === 'function'
709
- ? window.mParticle.sessionManager.getSession()
710
- : undefined;
711
-
712
- var options = mergeObjects(
713
- {
714
- accountId: accountId,
715
- },
716
- launcherOptions || {},
717
- mpSessionId ? { mpSessionId: mpSessionId } : {}
718
- );
719
-
720
- if (isPartnerInLocalLauncherTestGroup()) {
721
- var localLauncher = window.Rokt.createLocalLauncher(options);
722
- initRoktLauncher(localLauncher);
723
- } else {
724
- window.Rokt.createLauncher(options)
725
- .then(initRoktLauncher)
726
- .catch(function (err) {
727
- console.error('Error creating Rokt launcher:', err);
728
- });
729
- }
730
- }
731
-
732
- function initRoktLauncher(launcher) {
733
- // Assign the launcher to a global variable for later access
734
- window.Rokt.currentLauncher = launcher;
735
- // Locally cache the launcher and filters
736
- self.launcher = launcher;
737
-
738
- var roktFilters = window.mParticle.Rokt.filters;
739
-
740
- if (!roktFilters) {
741
- console.warn('Rokt Kit: No filters have been set.');
742
- } else {
743
- self.filters = roktFilters;
744
- if (!roktFilters.filteredUser) {
745
- console.warn('Rokt Kit: No filtered user has been set.');
746
- }
747
- }
748
-
749
- // Kit must be initialized before attaching to the Rokt manager
750
- self.isInitialized = true;
751
-
752
- sendAdBlockMeasurementSignals(self.domain, self.integrationName);
753
-
754
- // Attaches the kit to the Rokt manager
755
- window.mParticle.Rokt.attachKit(self);
756
- processEventQueue();
757
- }
758
-
759
- // mParticle Kit Callback Methods
760
- function fetchOptimizely() {
761
- var forwarders = window.mParticle
762
- ._getActiveForwarders()
763
- .filter(function (forwarder) {
764
- return forwarder.name === 'Optimizely';
765
- });
766
-
767
- try {
768
- if (forwarders.length > 0 && window.optimizely) {
769
- // Get the state object
770
- var optimizelyState = window.optimizely.get('state');
771
- if (
772
- !optimizelyState ||
773
- !optimizelyState.getActiveExperimentIds
774
- ) {
775
- return {};
776
- }
777
- // Get active experiment IDs
778
- var activeExperimentIds =
779
- optimizelyState.getActiveExperimentIds();
780
- // Get variations for each active experiment
781
- var activeExperiments = activeExperimentIds.reduce(function (
782
- acc,
783
- expId
784
- ) {
785
- acc[
786
- 'rokt.custom.optimizely.experiment.' +
787
- expId +
788
- '.variationId'
789
- ] = optimizelyState.getVariationMap()[expId].id;
790
- return acc;
791
- },
792
- {});
793
- return activeExperiments;
794
- }
795
- } catch (error) {
796
- console.error('Error fetching Optimizely attributes:', error);
797
- }
798
- return {};
799
- }
800
-
801
- // Called by the mParticle Rokt Manager
802
- this.selectPlacements = selectPlacements;
803
- this.hashAttributes = hashAttributes;
804
- this.use = use;
805
-
806
- // Kit Callback Methods
807
- this.init = initForwarder;
808
- this.process = processEvent;
809
- this.setExtensionData = setExtensionData;
810
- this.setUserAttribute = setUserAttribute;
811
- this.onUserIdentified = onUserIdentified;
812
- this.onLoginComplete = onLoginComplete;
813
- this.onLogoutComplete = onLogoutComplete;
814
- this.onModifyComplete = onModifyComplete;
815
- this.removeUserAttribute = removeUserAttribute;
816
-
817
- /**
818
- * Checks if the Rokt kit is ready to use.
819
- * Both conditions must be true:
820
- * 1. self.isInitialized - Set after successful initialization of the kit
821
- * 2. self.launcher - The Rokt launcher instance must be available
822
- * @returns {boolean} Whether the kit is ready for use
823
- */
824
- function isKitReady() {
825
- return !!(self.isInitialized && self.launcher);
826
- }
827
-
828
- function isPartnerInLocalLauncherTestGroup() {
829
- return (
830
- window.mParticle.config &&
831
- window.mParticle.config.isLocalLauncherEnabled &&
832
- _isAssignedToSampleGroup()
833
- );
834
- }
835
-
836
- function _isAssignedToSampleGroup() {
837
- var LOCAL_LAUNCHER_TEST_GROUP_THRESHOLD = 0.5;
838
- return Math.random() > LOCAL_LAUNCHER_TEST_GROUP_THRESHOLD;
839
- }
840
-
841
- function captureTiming(metricName) {
842
- if (
843
- window &&
844
- window.mParticle &&
845
- window.mParticle.captureTiming &&
846
- metricName
847
- ) {
848
- window.mParticle.captureTiming(metricName);
849
- }
850
- }
851
-
852
- function createAutoRemovedIframe(src) {
853
- var iframe = document.createElement('iframe');
854
- iframe.style.display = 'none';
855
- iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
856
- iframe.src = src;
857
- iframe.onload = function () {
858
- iframe.onload = null;
859
- if (iframe.parentNode) {
860
- iframe.parentNode.removeChild(iframe);
861
- }
862
- };
863
- var target = document.body || document.head;
864
- if (target) {
865
- target.appendChild(iframe);
866
- }
867
- }
868
-
869
- var ADBLOCK_CONTROL_DOMAIN = 'apps.roktecommerce.com';
870
- var INIT_LOG_SAMPLING_RATE = 0.1;
871
- var _allowedOriginHashes = [-553112570, 549508659];
872
-
873
- function djb2(str) {
874
- var hash = 5381;
875
- for (var i = 0; i < str.length; i++) {
876
- hash = (hash << 5) + hash + str.charCodeAt(i);
877
- hash = hash & hash;
878
- }
879
- return hash;
880
- }
881
-
882
- function sendAdBlockMeasurementSignals(domain, version) {
883
- var originHash = djb2(window.location.origin);
884
- if (_allowedOriginHashes.indexOf(originHash) === -1) {
885
- return;
886
- }
887
-
888
- if (Math.random() >= INIT_LOG_SAMPLING_RATE) {
889
- return;
890
- }
891
-
892
- var guid = window.__rokt_li_guid__;
893
- if (!guid) {
894
- return;
895
- }
896
-
897
- var pageUrl = window.location.href.split('?')[0].split('#')[0];
898
- var params =
899
- 'version=' +
900
- encodeURIComponent(version) +
901
- '&launcherInstanceGuid=' +
902
- encodeURIComponent(guid) +
903
- '&pageUrl=' +
904
- encodeURIComponent(pageUrl);
905
-
906
- var existingDomain = domain || 'apps.rokt.com';
907
- createAutoRemovedIframe(
908
- 'https://' + existingDomain + '/v1/wsdk-init/index.html?' + params
909
- );
910
-
911
- createAutoRemovedIframe(
912
- 'https://' +
913
- ADBLOCK_CONTROL_DOMAIN +
914
- '/v1/wsdk-init/index.html?' +
915
- params +
916
- '&isControl=true'
917
- );
918
- }
919
- };
920
-
921
- function generateIntegrationName(customIntegrationName) {
922
- var coreSdkVersion = window.mParticle.getVersion();
923
- var kitVersion = "1.22.0";
924
- var name = 'mParticle_' + 'wsdkv_' + coreSdkVersion + '_kitv_' + kitVersion;
925
-
926
- if (customIntegrationName) {
927
- name += '_' + customIntegrationName;
928
- }
929
- return name;
930
- }
931
-
932
- function getId() {
933
- return moduleId;
934
- }
935
-
936
- function register(config) {
937
- if (!config) {
938
- window.console.log(
939
- 'You must pass a config object to register the kit ' + name
940
- );
941
- return;
942
- }
943
- if (!isObject(config)) {
944
- window.console.log(
945
- "'config' must be an object. You passed in a " + typeof config
946
- );
947
- return;
948
- }
949
-
950
- if (isObject(config.kits)) {
951
- config.kits[name] = {
952
- constructor: constructor,
953
- };
954
- } else {
955
- config.kits = {};
956
- config.kits[name] = {
957
- constructor: constructor,
958
- };
959
- }
960
- window.console.log(
961
- 'Successfully registered ' + name + ' to your mParticle configuration'
962
- );
963
- }
964
-
965
- function isObject(val) {
966
- return (
967
- val != null && typeof val === 'object' && Array.isArray(val) === false
968
- );
969
- }
970
-
971
- function mergeObjects() {
972
- var resObj = {};
973
- for (var i = 0; i < arguments.length; i += 1) {
974
- var obj = arguments[i],
975
- keys = Object.keys(obj);
976
- for (var j = 0; j < keys.length; j += 1) {
977
- resObj[keys[j]] = obj[keys[j]];
978
- }
979
- }
980
- return resObj;
981
- }
982
-
983
- function parseSettingsString(settingsString) {
984
- if (!settingsString) {
985
- return [];
986
- }
987
- try {
988
- return JSON.parse(settingsString.replace(/&quot;/g, '"'));
989
- } catch (error) {
990
- console.error('Settings string contains invalid JSON');
991
- }
992
- return [];
993
- }
994
-
995
- function extractRoktExtensions(settingsString) {
996
- var settings = settingsString ? parseSettingsString(settingsString) : [];
997
- var roktExtensions = [];
998
-
999
- for (var i = 0; i < settings.length; i++) {
1000
- roktExtensions.push(settings[i].value);
1001
- }
1002
-
1003
- return roktExtensions;
1004
- }
1005
-
1006
- function generateMappedEventLookup(placementEventMapping) {
1007
- if (!placementEventMapping) {
1008
- return {};
1009
- }
1010
-
1011
- var mappedEvents = {};
1012
- for (var i = 0; i < placementEventMapping.length; i++) {
1013
- var mapping = placementEventMapping[i];
1014
- mappedEvents[mapping.jsmap] = mapping.value;
1015
- }
1016
- return mappedEvents;
1017
- }
1018
-
1019
- function hashEventMessage(messageType, eventType, eventName) {
1020
- return window.mParticle.generateHash(
1021
- [messageType, eventType, eventName].join('')
1022
- );
1023
- }
1024
-
1025
- function isEmpty(value) {
1026
- return value == null || !(Object.keys(value) || value).length;
1027
- }
1028
-
1029
- function isString(value) {
1030
- return typeof value === 'string';
1031
- }
1032
-
1033
- // --- Reporting Services ---
1034
-
1035
- var ErrorCodes = {
1036
- UNKNOWN_ERROR: 'UNKNOWN_ERROR',
1037
- UNHANDLED_EXCEPTION: 'UNHANDLED_EXCEPTION',
1038
- IDENTITY_REQUEST: 'IDENTITY_REQUEST',
1039
- };
1040
-
1041
- var WSDKErrorSeverity = {
1042
- ERROR: 'ERROR',
1043
- INFO: 'INFO',
1044
- WARNING: 'WARNING',
1045
- };
1046
-
1047
- var DEFAULT_LOGGING_URL = 'apps.rokt-api.com/v1/log';
1048
- var DEFAULT_ERROR_URL = 'apps.rokt-api.com/v1/errors';
1049
- var RATE_LIMIT_PER_SEVERITY = 10;
1050
-
1051
- function RateLimiter() {
1052
- this._logCount = {};
1053
- }
1054
-
1055
- RateLimiter.prototype.incrementAndCheck = function (severity) {
1056
- var count = this._logCount[severity] || 0;
1057
- var newCount = count + 1;
1058
- this._logCount[severity] = newCount;
1059
- return newCount > RATE_LIMIT_PER_SEVERITY;
1060
- };
1061
-
1062
- // --- ReportingTransport: shared transport layer for reporting services ---
1063
-
1064
- function ReportingTransport(
1065
- config,
1066
- integrationName,
1067
- launcherInstanceGuid,
1068
- accountId,
1069
- rateLimiter
1070
- ) {
1071
- var self = this;
1072
- self._isLoggingEnabled = (config && config.isLoggingEnabled) || false;
1073
- self._integrationName = integrationName || '';
1074
- self._launcherInstanceGuid = launcherInstanceGuid;
1075
- self._accountId = accountId || null;
1076
- self._rateLimiter = rateLimiter || new RateLimiter();
1077
- self._reporter = 'mp-wsdk';
1078
- self._isEnabled = _isReportingEnabled(self);
1079
- }
1080
-
1081
- ReportingTransport.prototype.send = function (
1082
- url,
1083
- severity,
1084
- msg,
1085
- code,
1086
- stackTrace,
1087
- onError
1088
- ) {
1089
- if (!this._isEnabled || this._rateLimiter.incrementAndCheck(severity)) {
1090
- return;
1091
- }
1092
-
1093
- try {
1094
- var logRequest = {
1095
- additionalInformation: {
1096
- message: msg,
1097
- version: this._integrationName || '',
1098
- },
1099
- severity: severity,
1100
- code: code || ErrorCodes.UNKNOWN_ERROR,
1101
- url: _getUrl(),
1102
- deviceInfo: _getUserAgent(),
1103
- stackTrace: stackTrace,
1104
- reporter: this._reporter,
1105
- integration: this._integrationName || '',
1106
- };
1107
- var headers = {
1108
- Accept: 'text/plain;charset=UTF-8',
1109
- 'Content-Type': 'application/json',
1110
- 'rokt-launcher-version': this._integrationName || '',
1111
- 'rokt-wsdk-version': 'joint',
1112
- };
1113
- if (this._launcherInstanceGuid) {
1114
- headers['rokt-launcher-instance-guid'] = this._launcherInstanceGuid;
1115
- }
1116
- if (this._accountId) {
1117
- headers['rokt-account-id'] = this._accountId;
1118
- }
1119
- var payload = {
1120
- method: 'POST',
1121
- headers: headers,
1122
- body: JSON.stringify(logRequest),
1123
- };
1124
- fetch(url, payload).catch(function (error) {
1125
- console.error('ReportingTransport: Failed to send log', error);
1126
- if (onError) {
1127
- onError(error);
1128
- }
1129
- });
1130
- } catch (error) {
1131
- console.error('ReportingTransport: Failed to send log', error);
1132
- if (onError) {
1133
- onError(error);
1134
- }
1135
- }
1136
- };
1137
-
1138
- function _isReportingEnabled(transport) {
1139
- return (
1140
- _isDebugModeEnabled() ||
1141
- (_isRoktDomainPresent() && transport._isLoggingEnabled)
1142
- );
1143
- }
1144
-
1145
- function _isRoktDomainPresent() {
1146
- return typeof window !== 'undefined' && Boolean(window['ROKT_DOMAIN']);
1147
- }
1148
-
1149
- function _isDebugModeEnabled() {
1150
- return (
1151
- typeof window !== 'undefined' &&
1152
- window.location &&
1153
- window.location.search &&
1154
- window.location.search
1155
- .toLowerCase()
1156
- .indexOf('mp_enable_logging=true') !== -1
1157
- );
1158
- }
1159
-
1160
- function _getUrl() {
1161
- return typeof window !== 'undefined' && window.location
1162
- ? window.location.href
1163
- : undefined;
1164
- }
1165
-
1166
- function _getUserAgent() {
1167
- return typeof window !== 'undefined' && window.navigator
1168
- ? window.navigator.userAgent
1169
- : undefined;
1170
- }
1171
-
1172
- // --- ErrorReportingService: handles ERROR and WARNING severity ---
1173
-
1174
- function ErrorReportingService(
1175
- config,
1176
- integrationName,
1177
- launcherInstanceGuid,
1178
- accountId,
1179
- rateLimiter
1180
- ) {
1181
- this._transport = new ReportingTransport(
1182
- config,
1183
- integrationName,
1184
- launcherInstanceGuid,
1185
- accountId,
1186
- rateLimiter
1187
- );
1188
- this._errorUrl =
1189
- 'https://' + ((config && config.errorUrl) || DEFAULT_ERROR_URL);
1190
- }
1191
-
1192
- ErrorReportingService.prototype.report = function (error) {
1193
- if (!error) {
1194
- return;
1195
- }
1196
- var severity = error.severity || WSDKErrorSeverity.ERROR;
1197
- this._transport.send(
1198
- this._errorUrl,
1199
- severity,
1200
- error.message,
1201
- error.code,
1202
- error.stackTrace
1203
- );
1204
- };
1205
-
1206
- // --- LoggingService: handles INFO severity ---
1207
-
1208
- function LoggingService(
1209
- config,
1210
- errorReportingService,
1211
- integrationName,
1212
- launcherInstanceGuid,
1213
- accountId,
1214
- rateLimiter
1215
- ) {
1216
- this._transport = new ReportingTransport(
1217
- config,
1218
- integrationName,
1219
- launcherInstanceGuid,
1220
- accountId,
1221
- rateLimiter
1222
- );
1223
- this._loggingUrl =
1224
- 'https://' + ((config && config.loggingUrl) || DEFAULT_LOGGING_URL);
1225
- this._errorReportingService = errorReportingService;
1226
- }
1227
-
1228
- LoggingService.prototype.log = function (entry) {
1229
- if (!entry) {
1230
- return;
1231
- }
1232
- var self = this;
1233
- self._transport.send(
1234
- self._loggingUrl,
1235
- WSDKErrorSeverity.INFO,
1236
- entry.message,
1237
- entry.code,
1238
- undefined,
1239
- function (error) {
1240
- if (self._errorReportingService) {
1241
- self._errorReportingService.report({
1242
- message:
1243
- 'LoggingService: Failed to send log: ' + error.message,
1244
- code: ErrorCodes.UNKNOWN_ERROR,
1245
- severity: WSDKErrorSeverity.ERROR,
1246
- });
1247
- }
1248
- }
1249
- );
1250
- };
1251
-
1252
- if (window && window.mParticle && window.mParticle.addForwarder) {
1253
- window.mParticle.addForwarder({
1254
- name: name,
1255
- constructor: constructor,
1256
- getId: getId,
1257
- });
1258
- }
1259
-
1260
- var RoktKit = {
1261
- register: register,
1262
- ReportingTransport: ReportingTransport,
1263
- ErrorReportingService: ErrorReportingService,
1264
- LoggingService: LoggingService,
1265
- RateLimiter: RateLimiter,
1266
- ErrorCodes: ErrorCodes,
1267
- WSDKErrorSeverity: WSDKErrorSeverity,
1268
- };
1269
- var RoktKit_1 = RoktKit.register;
1270
- var RoktKit_2 = RoktKit.ReportingTransport;
1271
- var RoktKit_3 = RoktKit.ErrorReportingService;
1272
- var RoktKit_4 = RoktKit.LoggingService;
1273
- var RoktKit_5 = RoktKit.RateLimiter;
1274
- var RoktKit_6 = RoktKit.ErrorCodes;
1275
- var RoktKit_7 = RoktKit.WSDKErrorSeverity;
1276
-
1277
- exports.ErrorCodes = RoktKit_6;
1278
- exports.ErrorReportingService = RoktKit_3;
1279
- exports.LoggingService = RoktKit_4;
1280
- exports.RateLimiter = RoktKit_5;
1281
- exports.ReportingTransport = RoktKit_2;
1282
- exports.WSDKErrorSeverity = RoktKit_7;
1283
- exports.default = RoktKit;
1284
- exports.register = RoktKit_1;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g="Rokt",I=181,F="selectPlacements",G="apps.roktecommerce.com",z=.1,Q=14,N={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},w={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},V="apps.rokt-api.com/v1/log",W="apps.rokt-api.com/v1/errors",Y=10;function s(){return window.mParticle}function M(n,t){const o=["https://",typeof n<"u"?n:"apps.rokt.com","/wsdk/integrations/launcher.js"].join("");return!t||t.length===0?o:o+"?extensions="+t.join(",")}function S(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function y(n){if(!n)return[];try{return JSON.parse(n.replace(/&quot;/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function T(n){const t=n?y(n):[],e=[];for(let i=0;i<t.length;i++)e.push(t[i].value);return e}function U(n){if(!n)return{};const t={};for(let e=0;e<n.length;e++){const i=n[e];t[i.jsmap]=i.value}return t}function P(n){const t={};if(!Array.isArray(n))return t;for(let e=0;e<n.length;e++){const i=n[e];if(!i||!R(i.value)||!R(i.map))continue;const r=i.value,o=i.map;t[r]||(t[r]=[]),t[r].push({eventAttributeKey:o,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return t}function C(n,t,e){return s().generateHash([n,t,e].join(""))}function A(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function R(n){return typeof n=="string"}function q(n){let i="mParticle_wsdkv_"+s().getVersion()+"_kitv_"+"1.23.0";return n&&(i+="_"+n),i}function j(n){let t=5381;for(let e=0;e<n.length;e++)t=(t<<5)+t+n.charCodeAt(e),t=t&t;return t}function L(n){const t=document.createElement("iframe");t.style.display="none",t.setAttribute("sandbox","allow-scripts allow-same-origin"),t.src=n,t.onload=function(){t.onload=null,t.parentNode&&t.parentNode.removeChild(t)};const e=document.body||document.head;e&&e.appendChild(t)}function D(n,t){const e=j(window.location.origin);if(f._allowedOriginHashes.indexOf(e)===-1||Math.random()>=z)return;const r=window.__rokt_li_guid__;if(!r)return;const o=window.location.href.split("?")[0].split("#")[0],a="version="+encodeURIComponent(t??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(o);L("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+a),L("https://"+G+"/v1/wsdk-init/index.html?"+a+"&isControl=true")}function B(){return typeof window<"u"&&!!window.ROKT_DOMAIN}function J(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function X(){return typeof window<"u"?window.location?.href:void 0}function Z(){return typeof window<"u"?window.navigator?.userAgent:void 0}class H{constructor(){this._logCount={}}incrementAndCheck(t){const i=(this._logCount[t]||0)+1;return this._logCount[t]=i,i>Y}}class O{constructor(t,e,i,r,o){this._reporter="mp-wsdk";const a=t?.isLoggingEnabled===!0||t?.isLoggingEnabled==="true";this._integrationName=e||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=o||new H,this._isEnabled=J()||B()&&a}send(t,e,i,r,o,a){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(e)))try{const c={additionalInformation:{message:i,version:this._integrationName},severity:e,code:r||N.UNKNOWN_ERROR,url:X(),deviceInfo:Z(),stackTrace:o,reporter:this._reporter,integration:this._integrationName},u={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(u["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(u["rokt-account-id"]=this._accountId),fetch(t,{method:"POST",headers:u,body:JSON.stringify(c)}).catch(p=>{console.error("ReportingTransport: Failed to send log",p),a&&a(p)})}catch(c){console.error("ReportingTransport: Failed to send log",c),a&&a(c)}}}class K{constructor(t,e,i,r,o){this._transport=new O(t,e,i,r,o),this._errorUrl="https://"+(t?.errorUrl||W)}report(t){if(!t)return;const e=t.severity||w.ERROR;this._transport.send(this._errorUrl,e,t.message,t.code,t.stackTrace)}}class x{constructor(t,e,i,r,o,a){this._transport=new O(t,i,r,o,a),this._loggingUrl="https://"+(t?.loggingUrl||V),this._errorReportingService=e}log(t){t&&this._transport.send(this._loggingUrl,w.INFO,t.message,t.code,void 0,e=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+e.message,code:N.UNKNOWN_ERROR,severity:w.ERROR})})}}const h=class h{constructor(){this.name=g,this.moduleId=I,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.eventQueue=[],this.eventStreamQueue=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null}getEventAttributeValue(t,e){const i=t&&t.EventAttributes;return!i||typeof i[e]>"u"?null:i[e]}doesEventAttributeConditionMatch(t,e){if(!t||!R(t.operator))return!1;const i=t.operator.toLowerCase(),r=t.attributeValue;return i==="exists"?e!==null:e==null?!1:i==="equals"?String(e)===String(r):i==="contains"?String(e).indexOf(String(r))!==-1:!1}doesEventMatchRule(t,e){if(!e||!R(e.eventAttributeKey))return!1;const i=e.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(t,e.eventAttributeKey);if(i.length===0)return r!==null;for(let o=0;o<i.length;o++)if(!this.doesEventAttributeConditionMatch(i[o],r))return!1;return!0}applyPlacementEventAttributeMapping(t){const e=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<e.length;i++){const r=e[i],o=this.placementEventAttributeMappingLookup[r];if(A(o))continue;let a=!0;for(let c=0;c<o.length;c++)if(!this.doesEventMatchRule(t,o[c])){a=!1;break}a&&s().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(t){if(!t||!t.getUserIdentities)return{};const e=t.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(e)}returnLocalSessionAttributes(){return!s().Rokt||typeof s().Rokt.getLocalSessionAttributes!="function"?{}:A(this.placementEventMappingLookup)&&A(this.placementEventAttributeMappingLookup)?{}:s().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(t){const e={...t||{}},i=this._mappedEmailSha256Key;return i&&t[i]&&(e[h.EMAIL_SHA256_KEY]=t[i]),i&&delete e[i],e}logSelectPlacementsEvent(t){if(!window.mParticle||typeof s().logEvent!="function"||!S(t))return;const e=s().EventType.Other;s().logEvent(F,e,t)}processEventQueue(){this.eventQueue.forEach(t=>{this.process(t)}),this.eventQueue=[]}enrichEvent(t){return{...t,UserAttributes:this.userAttributes}}sendEventStream(t){if(window.Rokt&&typeof window.Rokt.__event_stream__=="function"){if(this.eventStreamQueue.length){const e=this.eventStreamQueue;this.eventStreamQueue=[];for(let i=0;i<e.length;i++)window.Rokt.__event_stream__(this.enrichEvent(e[i]))}window.Rokt.__event_stream__(this.enrichEvent(t))}else this.eventStreamQueue.push(t)}setRoktSessionId(t){if(!(!t||typeof t!="string"))try{const e=s().getInstance();e&&typeof e.setIntegrationAttribute=="function"&&e.setIntegrationAttribute(I,{roktSessionId:t})}catch{}}buildIdentityEvent(t,e){const i=e.getMPID&&typeof e.getMPID=="function"?e.getMPID():null,r=s()&&s().sessionManager&&typeof s().sessionManager.getSession=="function"?s().sessionManager.getSession():null,o=e.getUserIdentities&&typeof e.getUserIdentities=="function"?e.getUserIdentities().userIdentities:null;return{EventName:t,EventDataType:Q,EventCategory:0,Timestamp:Date.now(),MPID:i,SessionId:r,UserIdentities:o}}attachLauncher(t,e){const i=s()&&s().sessionManager&&typeof s().sessionManager.getSession=="function"?s().sessionManager.getSession():void 0,r={accountId:t,...e||{},...i?{mpSessionId:i}:{}};if(this.isPartnerInLocalLauncherTestGroup()){const o=window.Rokt.createLocalLauncher(r);this.initRoktLauncher(o)}else window.Rokt.createLauncher(r).then(o=>this.initRoktLauncher(o)).catch(o=>{console.error("Error creating Rokt launcher:",o)})}initRoktLauncher(t){window.Rokt&&(window.Rokt.currentLauncher=t),this.launcher=t;const e=s().Rokt?.filters;e?(this.filters=e,e.filteredUser||console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,D(this.domain,this.integrationName),s().Rokt.attachKit(this),this.processEventQueue()}fetchOptimizely(){const t=s()._getActiveForwarders().filter(e=>e.name==="Optimizely");try{if(t.length>0&&window.optimizely){const e=window.optimizely.get("state");return!e||!e.getActiveExperimentIds?{}:e.getActiveExperimentIds().reduce((o,a)=>(o["rokt.custom.optimizely.experiment."+a+".variationId"]=e.getVariationMap()[a].id,o),{})}}catch(e){console.error("Error fetching Optimizely attributes:",e)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(s().config&&s().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(t){window&&s()&&s().captureTiming&&t&&s().captureTiming(t)}init(t,e,i,r,o){const a=t.accountId,c=T(t.roktExtensions);this.userAttributes=o||{},this._onboardingExpProvider=t.onboardingExpProvider;const u=y(t.placementEventMapping);this.placementEventMappingLookup=U(u);const p=y(t.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=P(p),t.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=t.hashedEmailUserIdentityType.toLowerCase());const b=s().Rokt?.domain,d={...s().Rokt?.launcherOptions||{}};this.integrationName=q(d.integrationName),d.integrationName=this.integrationName,this.domain=b;const m={loggingUrl:t.loggingUrl,errorUrl:t.errorUrl,isLoggingEnabled:t.isLoggingEnabled==="true"||t.isLoggingEnabled===!0},E=new K(m,this.integrationName,window.__rokt_li_guid__,t.accountId),_=new x(m,E,this.integrationName,window.__rokt_li_guid__,t.accountId);if(this.errorReportingService=E,this.loggingService=_,s()._registerErrorReportingService&&s()._registerErrorReportingService(E),s()._registerLoggingService&&s()._registerLoggingService(_),i){this.testHelpers={generateLauncherScript:M,extractRoktExtensions:T,hashEventMessage:C,parseSettingsString:y,generateMappedEventLookup:U,generateMappedEventAttributeLookup:P,sendAdBlockMeasurementSignals:D,createAutoRemovedIframe:L,djb2:j,setAllowedOriginHashes:v=>{h._allowedOriginHashes=v},ReportingTransport:O,ErrorReportingService:K,LoggingService:x,RateLimiter:H,ErrorCodes:N,WSDKErrorSeverity:w},this.attachLauncher(a,d);return}if(this.isLauncherReadyToAttach())this.attachLauncher(a,d);else{const v=document.head||document.body,l=document.createElement("script");l.type="text/javascript",l.src=M(b,c),l.async=!0,l.crossOrigin="anonymous",l.fetchPriority="high",l.id="rokt-launcher",l.onload=()=>{this.isLauncherReadyToAttach()?this.attachLauncher(a,d):console.error("Rokt object is not available after script load.")},l.onerror=k=>{console.error("Error loading Rokt launcher script:",k)},v.appendChild(l),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)}}process(t){if(!this.isKitReady()){this.eventQueue.push(t);return}if(this.sendEventStream(t),typeof s().Rokt?.setLocalSessionAttribute!="function"||(A(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(t),A(this.placementEventMappingLookup)))return;const e=C(t.EventDataType,t.EventCategory,t.EventName??"");if(this.placementEventMappingLookup[String(e)]){const i=this.placementEventMappingLookup[String(e)];s().Rokt.setLocalSessionAttribute?.(i,!0)}}setExtensionData(t){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(t)}setUserAttribute(t,e){this.userAttributes[t]=e,this.sendEventStream(this.buildIdentityEvent("set_user_attributes",this.filters.filteredUser??{}))}removeUserAttribute(t){delete this.userAttributes[t]}onUserIdentified(t){this.filters.filteredUser=t,this.userAttributes=t.getAllUserAttributes(),this.sendEventStream(this.buildIdentityEvent("identify",t))}onLoginComplete(t){this.userAttributes=t.getAllUserAttributes(),this.sendEventStream(this.buildIdentityEvent("login",t))}onLogoutComplete(t){this.userAttributes=t.getAllUserAttributes(),this.sendEventStream(this.buildIdentityEvent("logout",t))}onModifyComplete(t){this.userAttributes=t.getAllUserAttributes(),this.sendEventStream(this.buildIdentityEvent("modify_user",t))}selectPlacements(t){const e=t&&t.attributes||{},i={...this.userAttributes,...e},r=this.filters||{},o=r.userAttributeFilters||[],a=r.filteredUser||null,c=a&&a.getMPID&&typeof a.getMPID=="function"?a.getMPID():null;let u;r?r.filterUserAttributes?u=r.filterUserAttributes(i,o):u=i:(console.warn("Rokt Kit: No filters available, using user attributes"),u=i),this.userAttributes=u;const p=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},b=this.returnUserIdentities(a),d=this.returnLocalSessionAttributes(),m={...b,...u,...p,...d,mpid:c},E={...t,attributes:m},_=this.launcher.selectPlacements(E),v=()=>this.logSelectPlacementsEvent(m);return Promise.resolve(_).then(l=>l?.context?.sessionId?.then(k=>this.setRoktSessionId(k))).catch(()=>{}).finally(v),_}hashAttributes(t){return this.isKitReady()?this.launcher.hashAttributes(t):(console.error("Rokt Kit: Not initialized"),null)}use(t){return this.isKitReady()?!t||!R(t)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(t):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let f=h;function $(){return I}function tt(n){if(!n){window.console.log("You must pass a config object to register the kit "+g);return}if(!S(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}S(n.kits)?n.kits[g]={constructor:f}:(n.kits={},n.kits[g]={constructor:f}),window.console.log("Successfully registered "+g+" to your mParticle configuration")}typeof window<"u"&&window.mParticle&&s().addForwarder&&s().addForwarder({name:g,constructor:f,getId:$});exports.register=tt;
2
+ //# sourceMappingURL=Rokt-Kit.common.js.map