@mparticle/web-rokt-kit 1.27.0 → 1.28.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.
- package/dist/Rokt-Kit.common.js +1 -1
- package/dist/Rokt-Kit.esm.js +5 -3
- package/dist/Rokt-Kit.iife.js +1 -1
- package/package.json +1 -1
package/dist/Rokt-Kit.common.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=["billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],q=new Set(V);function z(n){return q.has(n.toLowerCase())}function v(n){const e={},t=n||{},i=Object.keys(t);for(let r=0;r<i.length;r++){const s=i[r];z(s)||(e[s]=t[s])}return e}const d="Rokt",w=181,J="selectPlacements",X="apps.roktecommerce.com",$=.1,A={LOGIN:"login",LOGOUT:"logout",MODIFY_USER:"modify_user",IDENTIFY:"identify"},Z="ThankYouPageJourney",ee="rokt-launcher",te="rokt-thank-you-element",ie="userIdentifiedInWorkspace",ne=500,P={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},L={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},re="apps.rokt-api.com/v1/log",se="apps.rokt-api.com/v1/errors",oe=10;function a(){return window.mParticle}function C(n,e){const i=[W(n),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?i:i+"?extensions="+e.join(",")}function M(n){return[W(n),"/rokt-elements/rokt-element-thank-you.js"].join("")}function W(n){return["https://",typeof n<"u"?n:"apps.rokt-api.com"].join("")}function K(n,e,t){if(document.getElementById(n))return;const i=document.head||document.body,r=document.createElement("script");r.id=n,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),i.appendChild(r)}function T(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function b(n){if(!n)return[];try{return JSON.parse(n.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function D(n){const e=n?b(n):[],t=[],i=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,i.push(Z)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:i,loadThankYouElement:r}}async function ae(n,e){const t=[];if(e)for(const i of n)t.push(e.use(i));return Promise.all(t)}function Y(n){if(!n)return{};const e={};for(let t=0;t<n.length;t++){const i=n[t];e[i.jsmap]=i.value}return e}function x(n){const e={};if(!Array.isArray(n))return e;for(let t=0;t<n.length;t++){const i=n[t];if(!i||!f(i.value)||!f(i.map))continue;const r=i.value,s=i.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return e}function F(n,e,t){return a().generateHash([n,e,t].join(""))}function I(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function f(n){return typeof n=="string"}function ce(n){let i="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"1.27.0";return n&&(i+="_"+n),i}function Q(n){let e=5381;for(let t=0;t<n.length;t++)e=(e<<5)+e+n.charCodeAt(t),e=e&e;return e}function N(n){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=n,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function j(n,e){const t=Q(window.location.origin);if(m._allowedOriginHashes.indexOf(t)===-1||Math.random()>=$)return;const r=window.__rokt_li_guid__;if(!r)return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s);N("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+o),N("https://"+X+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function ue(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function le(){return typeof window<"u"?window.location?.href:void 0}function de(){return typeof window<"u"?window.navigator?.userAgent:void 0}class B{constructor(){this._logCount={}}incrementAndCheck(e){const i=(this._logCount[e]||0)+1;return this._logCount[e]=i,i>oe}}class U{constructor(e,t,i,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=s||new B,this._isEnabled=ue()||o}send(e,t,i,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:i,version:this._integrationName},severity:t,code:r||P.UNKNOWN_ERROR,url:le(),deviceInfo:de(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},l={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(l["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(l["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:l,body:JSON.stringify(c)}).catch(u=>{console.error("ReportingTransport: Failed to send log",u),o&&o(u)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class H{constructor(e,t,i,r,s){this._transport=new U(e,t,i,r,s),this._errorUrl="https://"+(e?.errorUrl||se)}report(e){if(!e)return;const t=e.severity||L.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class G{constructor(e,t,i,r,s,o){this._transport=new U(e,i,r,s,o),this._loggingUrl="https://"+(e?.loggingUrl||re),this._errorReportingService=t}log(e){e&&this._transport.send(this._loggingUrl,L.INFO,e.message,e.code,void 0,t=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+t.message,code:P.UNKNOWN_ERROR,severity:L.ERROR})})}}const h=class h{constructor(){this.name=d,this.id=w,this.moduleId=w,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.batchQueue=[],this.batchStreamQueue=[],this.pendingIdentityEvents=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null}getEventAttributeValue(e,t){const i=e&&e.EventAttributes;return!i||typeof i[t]>"u"?null:i[t]}doesEventAttributeConditionMatch(e,t){if(!e||!f(e.operator))return!1;const i=e.operator.toLowerCase(),r=e.attributeValue;return i==="exists"?t!==null:t==null?!1:i==="equals"?String(t)===String(r):i==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!f(t.eventAttributeKey))return!1;const i=t.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(i.length===0)return r!==null;for(let s=0;s<i.length;s++)if(!this.doesEventAttributeConditionMatch(i[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<t.length;i++){const r=t[i],s=this.placementEventAttributeMappingLookup[r];if(I(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:I(this.placementEventMappingLookup)&&I(this.placementEventAttributeMappingLookup)?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},i=this._mappedEmailSha256Key;return i&&e[i]&&(t[h.EMAIL_SHA256_KEY]=e[i]),i&&delete t[i],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!T(e))return;const t=a().EventType.Other;a().logEvent(J,t,e)}buildIdentityEvent(e,t){const i=t.getMPID(),r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0;return{event_type:e,data:{timestamp_unixtime_ms:Date.now(),session_uuid:r??void 0,mpid:i}}}mergePendingIdentityEvents(e){if(this.pendingIdentityEvents.length===0)return e;const t={...e,events:[...e.events??[],...this.pendingIdentityEvents]};return this.pendingIdentityEvents=[],t}drainBatchQueue(){this.batchQueue.forEach(e=>{this.processBatch(e)}),this.batchQueue=[]}processBatch(e){if(!this.isKitReady())return this.batchQueue.push(e),"Batch queued for forwarder: "+d;const t=this.enrichCommerceEventTypes(this.mergePendingIdentityEvents(e));return this.sendBatchStream(t),"Successfully sent batch to forwarder: "+d}enrichCommerceEventTypes(e){if(!e.events)return e;for(const t of e.events){if(t.event_type!=="commerce_event")continue;const{data:i}=t;if(!i)continue;const r=i.custom_flags?.["Rokt.CommerceEventType"];r&&T(i.product_action)&&(i.product_action.action=r)}return e}sendBatchStream(e){if(window.Rokt&&typeof window.Rokt.__batch_stream__=="function"){if(this.batchStreamQueue.length){const t=this.batchStreamQueue;this.batchStreamQueue=[];for(let i=0;i<t.length;i++)window.Rokt.__batch_stream__(t[i])}window.Rokt.__batch_stream__(e)}else this.batchStreamQueue.push(e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&typeof t.setIntegrationAttribute=="function"&&t.setIntegrationAttribute(w,{roktSessionId:e})}catch{}}attachLauncher(e,t,i=[]){const r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s={accountId:e,...t||{},...r?{mpSessionId:r}:{}};let o;this.isPartnerInLocalLauncherTestGroup()?o=Promise.resolve(window.Rokt.createLocalLauncher(s)):o=window.Rokt.createLauncher(s),o.then(async c=>{await ae(i,c),this.initRoktLauncher(c)}).catch(c=>{console.error("Error creating Rokt launcher:",c)})}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e;const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,j(this.domain,this.integrationName),a().Rokt.attachKit(this),this.drainBatchQueue()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,i,r,s){const o=e,c=o.accountId;this.userAttributes=v(s),this._onboardingExpProvider=o.onboardingExpProvider;const l=b(o.placementEventMapping);this.placementEventMappingLookup=Y(l);const u=b(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=x(u),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=f(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const E=a().Rokt?.domain,{roktExtensionsQueryParams:O,legacyRoktExtensions:k,loadThankYouElement:R}=D(o.roktExtensions),p={...a().Rokt?.launcherOptions||{}};this.integrationName=ce(p.integrationName),p.integrationName=this.integrationName,this.domain=E;const _={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,isLoggingEnabled:a().config?.isLoggingEnabled===!0},y=new H(_,this.integrationName,window.__rokt_li_guid__,o.accountId),S=new G(_,y,this.integrationName,window.__rokt_li_guid__,o.accountId);return this.errorReportingService=y,this.loggingService=S,a()._registerErrorReportingService&&a()._registerErrorReportingService(y),a()._registerLoggingService&&a()._registerLoggingService(S),i?(this.testHelpers={generateLauncherScript:C,generateThankYouElementScript:M,extractRoktExtensionConfig:D,hashEventMessage:F,parseSettingsString:b,generateMappedEventLookup:Y,generateMappedEventAttributeLookup:x,sendAdBlockMeasurementSignals:j,createAutoRemovedIframe:N,djb2:Q,setAllowedOriginHashes:g=>{h._allowedOriginHashes=g},ReportingTransport:U,ErrorReportingService:H,LoggingService:G,RateLimiter:B,ErrorCodes:P,WSDKErrorSeverity:L},this.attachLauncher(c,p),"Successfully initialized: "+d):(R&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),K(te,M(E),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:g=>{console.error("Error loading Rokt Thank You Element script:",g)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,p,k):(K(ee,C(E,O),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,p,k):console.error("Rokt object is not available after script load.")},onError:g=>{console.error("Error loading Rokt launcher script:",g)}}),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(!this.isKitReady())return"Kit not ready for forwarder: "+d;if(typeof a().Rokt?.setLocalSessionAttribute=="function"&&(I(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!I(this.placementEventMappingLookup))){const t=F(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return z(e)||(this.userAttributes[e]=t),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t,i){const r=e;return this.userAttributes=v(e.getAllUserAttributes()),this.pendingIdentityEvents.push(this.buildIdentityEvent(t,r)),"Successfully called "+i+" for forwarder: "+d}onUserIdentified(e){const t=e;return this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t),this.handleIdentityComplete(e,A.IDENTIFY,"onUserIdentified")}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const i=a().Identity?.search;if(typeof i!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const l of Object.keys(r)){const u=r[l];f(u)&&u.length>0&&(s[l]=u)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(l=>`${l}=${s[l]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(l=>{try{i(t,s,u=>{u?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),l()})}catch(u){console.error("Rokt Kit: Workspace IDSync search failed",u),this._workspaceLastSearchedIdentitiesKey=void 0,l()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,A.LOGIN,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.handleIdentityComplete(e,A.LOGOUT,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,A.MODIFY_USER,"onModifyComplete")}selectPlacements(e){if(this._workspaceSearchInFlightPromise){const t=this._workspaceSearchInFlightPromise;return Promise.race([t,new Promise(i=>setTimeout(i,ne))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...v(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,l=c?c.getMPID():null;let u;s?s.filterUserAttributes?u=s.filterUserAttributes(r,o):u=r:(console.warn("Rokt Kit: No filters available, using user attributes"),u=r),this.userAttributes=v(u);const E=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},O=this.returnUserIdentities(c),k=this.returnLocalSessionAttributes(),R={...O,...u,...E,...k,...this.userIdentifiedInWorkspace?{[ie]:!0}:{},mpid:l},p={...e,attributes:R},_=this.launcher.selectPlacements(p),y=()=>this.logSelectPlacementsEvent(R);return Promise.resolve(_).then(S=>S?.context?.sessionId?.then(g=>this.setRoktSessionId(g))).catch(()=>{}).finally(y),_}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!f(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let m=h;function he(){return w}function pe(n){if(!n){window.console.log("You must pass a config object to register the kit "+d);return}if(!T(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}T(n.kits)?n.kits[d]={constructor:m}:(n.kits={},n.kits[d]={constructor:m}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:m,getId:he});exports.register=pe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=["billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],q=new Set(V);function z(n){return q.has(n.toLowerCase())}function A(n){const e={},t=n||{},i=Object.keys(t);for(let r=0;r<i.length;r++){const s=i[r];z(s)||(e[s]=t[s])}return e}const d="Rokt",w=181,J="selectPlacements",X="apps.roktecommerce.com",$=.1,v={LOGIN:"login",LOGOUT:"logout",MODIFY_USER:"modify_user",IDENTIFY:"identify"},Z="ThankYouPageJourney",ee="rokt-launcher",te="rokt-thank-you-element",ie="userIdentifiedInWorkspace",ne=500,P={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},L={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},re="apps.rokt-api.com/v1/log",se="apps.rokt-api.com/v1/errors",oe=10;function a(){return window.mParticle}function C(n,e){const i=[W(n),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?i:i+"?extensions="+e.join(",")}function M(n){return[W(n),"/rokt-elements/rokt-element-thank-you.js"].join("")}function W(n){return["https://",typeof n<"u"?n:"apps.rokt-api.com"].join("")}function K(n,e,t){if(document.getElementById(n))return;const i=document.head||document.body,r=document.createElement("script");r.id=n,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),i.appendChild(r)}function T(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function b(n){if(!n)return[];try{return JSON.parse(n.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function D(n){const e=n?b(n):[],t=[],i=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,i.push(Z)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:i,loadThankYouElement:r}}async function ae(n,e){const t=[];if(e)for(const i of n)t.push(e.use(i));return Promise.all(t)}function Y(n){if(!n)return{};const e={};for(let t=0;t<n.length;t++){const i=n[t];e[i.jsmap]=i.value}return e}function x(n){const e={};if(!Array.isArray(n))return e;for(let t=0;t<n.length;t++){const i=n[t];if(!i||!f(i.value)||!f(i.map))continue;const r=i.value,s=i.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return e}function F(n,e,t){return a().generateHash([n,e,t].join(""))}function I(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function f(n){return typeof n=="string"}function ce(n){let i="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"1.28.0";return n&&(i+="_"+n),i}function Q(n){let e=5381;for(let t=0;t<n.length;t++)e=(e<<5)+e+n.charCodeAt(t),e=e&e;return e}function N(n){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=n,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function j(n,e){const t=Q(window.location.origin);if(m._allowedOriginHashes.indexOf(t)===-1||Math.random()>=$)return;const r=window.__rokt_li_guid__;if(!r)return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s);N("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+o),N("https://"+X+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function ue(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function le(){return typeof window<"u"?window.location?.href:void 0}function de(){return typeof window<"u"?window.navigator?.userAgent:void 0}class B{constructor(){this._logCount={}}incrementAndCheck(e){const i=(this._logCount[e]||0)+1;return this._logCount[e]=i,i>oe}}class U{constructor(e,t,i,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=s||new B,this._isEnabled=ue()||o}send(e,t,i,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:i,version:this._integrationName},severity:t,code:r||P.UNKNOWN_ERROR,url:le(),deviceInfo:de(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},l={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(l["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(l["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:l,body:JSON.stringify(c)}).catch(u=>{console.error("ReportingTransport: Failed to send log",u),o&&o(u)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class H{constructor(e,t,i,r,s){this._transport=new U(e,t,i,r,s),this._errorUrl="https://"+(e?.errorUrl||se)}report(e){if(!e)return;const t=e.severity||L.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class G{constructor(e,t,i,r,s,o){this._transport=new U(e,i,r,s,o),this._loggingUrl="https://"+(e?.loggingUrl||re),this._errorReportingService=t}log(e){e&&this._transport.send(this._loggingUrl,L.INFO,e.message,e.code,void 0,t=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+t.message,code:P.UNKNOWN_ERROR,severity:L.ERROR})})}}const h=class h{constructor(){this.name=d,this.id=w,this.moduleId=w,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.batchQueue=[],this.batchStreamQueue=[],this.pendingIdentityEvents=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null}getEventAttributeValue(e,t){const i=e&&e.EventAttributes;return!i||typeof i[t]>"u"?null:i[t]}doesEventAttributeConditionMatch(e,t){if(!e||!f(e.operator))return!1;const i=e.operator.toLowerCase(),r=e.attributeValue;return i==="exists"?t!==null:t==null?!1:i==="equals"?String(t)===String(r):i==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!f(t.eventAttributeKey))return!1;const i=t.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(i.length===0)return r!==null;for(let s=0;s<i.length;s++)if(!this.doesEventAttributeConditionMatch(i[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<t.length;i++){const r=t[i],s=this.placementEventAttributeMappingLookup[r];if(I(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:I(this.placementEventMappingLookup)&&I(this.placementEventAttributeMappingLookup)?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},i=this._mappedEmailSha256Key;return i&&e[i]&&(t[h.EMAIL_SHA256_KEY]=e[i]),i&&delete t[i],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!T(e))return;const t=a().EventType.Other;a().logEvent(J,t,e)}buildIdentityEvent(e,t){const i=t.getMPID(),r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s=this.returnUserIdentities(t);return{event_type:e,data:{timestamp_unixtime_ms:Date.now(),session_uuid:r??void 0,mpid:i,user_identities:s,user_attributes:this.userAttributes}}}mergePendingIdentityEvents(e){if(this.pendingIdentityEvents.length===0)return e;const t={...e,events:[...e.events??[],...this.pendingIdentityEvents]};return this.pendingIdentityEvents=[],t}drainBatchQueue(){this.batchQueue.forEach(e=>{this.processBatch(e)}),this.batchQueue=[]}processBatch(e){if(!this.isKitReady())return this.batchQueue.push(e),"Batch queued for forwarder: "+d;const t=this.enrichCommerceEventTypes(this.mergePendingIdentityEvents(e));return this.sendBatchStream(t),"Successfully sent batch to forwarder: "+d}enrichCommerceEventTypes(e){if(!e.events)return e;for(const t of e.events){if(t.event_type!=="commerce_event")continue;const{data:i}=t;if(!i)continue;const r=i.custom_flags?.["Rokt.CommerceEventType"];r&&T(i.product_action)&&(i.product_action.action=r)}return e}sendBatchStream(e){if(window.Rokt&&typeof window.Rokt.__batch_stream__=="function"){if(this.batchStreamQueue.length){const t=this.batchStreamQueue;this.batchStreamQueue=[];for(let i=0;i<t.length;i++)window.Rokt.__batch_stream__(t[i])}window.Rokt.__batch_stream__(e)}else this.batchStreamQueue.push(e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&typeof t.setIntegrationAttribute=="function"&&t.setIntegrationAttribute(w,{roktSessionId:e})}catch{}}attachLauncher(e,t,i=[]){const r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s={accountId:e,...t||{},...r?{mpSessionId:r}:{}};let o;this.isPartnerInLocalLauncherTestGroup()?o=Promise.resolve(window.Rokt.createLocalLauncher(s)):o=window.Rokt.createLauncher(s),o.then(async c=>{await ae(i,c),this.initRoktLauncher(c)}).catch(c=>{console.error("Error creating Rokt launcher:",c)})}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e;const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,j(this.domain,this.integrationName),a().Rokt.attachKit(this),this.drainBatchQueue()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,i,r,s){const o=e,c=o.accountId;this.userAttributes=A(s),this._onboardingExpProvider=o.onboardingExpProvider;const l=b(o.placementEventMapping);this.placementEventMappingLookup=Y(l);const u=b(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=x(u),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=f(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const E=a().Rokt?.domain,{roktExtensionsQueryParams:O,legacyRoktExtensions:k,loadThankYouElement:R}=D(o.roktExtensions),p={...a().Rokt?.launcherOptions||{}};this.integrationName=ce(p.integrationName),p.integrationName=this.integrationName,this.domain=E;const _={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,isLoggingEnabled:a().config?.isLoggingEnabled===!0},y=new H(_,this.integrationName,window.__rokt_li_guid__,o.accountId),S=new G(_,y,this.integrationName,window.__rokt_li_guid__,o.accountId);return this.errorReportingService=y,this.loggingService=S,a()._registerErrorReportingService&&a()._registerErrorReportingService(y),a()._registerLoggingService&&a()._registerLoggingService(S),i?(this.testHelpers={generateLauncherScript:C,generateThankYouElementScript:M,extractRoktExtensionConfig:D,hashEventMessage:F,parseSettingsString:b,generateMappedEventLookup:Y,generateMappedEventAttributeLookup:x,sendAdBlockMeasurementSignals:j,createAutoRemovedIframe:N,djb2:Q,setAllowedOriginHashes:g=>{h._allowedOriginHashes=g},ReportingTransport:U,ErrorReportingService:H,LoggingService:G,RateLimiter:B,ErrorCodes:P,WSDKErrorSeverity:L},this.attachLauncher(c,p),"Successfully initialized: "+d):(R&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),K(te,M(E),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:g=>{console.error("Error loading Rokt Thank You Element script:",g)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,p,k):(K(ee,C(E,O),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,p,k):console.error("Rokt object is not available after script load.")},onError:g=>{console.error("Error loading Rokt launcher script:",g)}}),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(!this.isKitReady())return"Kit not ready for forwarder: "+d;if(typeof a().Rokt?.setLocalSessionAttribute=="function"&&(I(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!I(this.placementEventMappingLookup))){const t=F(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return z(e)||(this.userAttributes[e]=t),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t,i){const r=e;return this.userAttributes=A(e.getAllUserAttributes()),this.pendingIdentityEvents.push(this.buildIdentityEvent(t,r)),"Successfully called "+i+" for forwarder: "+d}onUserIdentified(e){const t=e;return this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t),this.handleIdentityComplete(e,v.IDENTIFY,"onUserIdentified")}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const i=a().Identity?.search;if(typeof i!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const l of Object.keys(r)){const u=r[l];f(u)&&u.length>0&&(s[l]=u)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(l=>`${l}=${s[l]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(l=>{try{i(t,s,u=>{u?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),l()})}catch(u){console.error("Rokt Kit: Workspace IDSync search failed",u),this._workspaceLastSearchedIdentitiesKey=void 0,l()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,v.LOGIN,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.handleIdentityComplete(e,v.LOGOUT,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,v.MODIFY_USER,"onModifyComplete")}selectPlacements(e){if(this._workspaceSearchInFlightPromise){const t=this._workspaceSearchInFlightPromise;return Promise.race([t,new Promise(i=>setTimeout(i,ne))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...A(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,l=c?c.getMPID():null;let u;s?s.filterUserAttributes?u=s.filterUserAttributes(r,o):u=r:(console.warn("Rokt Kit: No filters available, using user attributes"),u=r),this.userAttributes=A(u);const E=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},O=this.returnUserIdentities(c),k=this.returnLocalSessionAttributes(),R={...O,...u,...E,...k,...this.userIdentifiedInWorkspace?{[ie]:!0}:{},mpid:l},p={...e,attributes:R},_=this.launcher.selectPlacements(p),y=()=>this.logSelectPlacementsEvent(R);return Promise.resolve(_).then(S=>S?.context?.sessionId?.then(g=>this.setRoktSessionId(g))).catch(()=>{}).finally(y),_}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!f(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let m=h;function he(){return w}function pe(n){if(!n){window.console.log("You must pass a config object to register the kit "+d);return}if(!T(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}T(n.kits)?n.kits[d]={constructor:m}:(n.kits={},n.kits[d]={constructor:m}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:m,getId:he});exports.register=pe;
|
|
2
2
|
//# sourceMappingURL=Rokt-Kit.common.js.map
|
package/dist/Rokt-Kit.esm.js
CHANGED
|
@@ -135,7 +135,7 @@ function f(n) {
|
|
|
135
135
|
return typeof n == "string";
|
|
136
136
|
}
|
|
137
137
|
function ce(n) {
|
|
138
|
-
let i = "mParticle_wsdkv_" + a().getVersion() + "_kitv_" + "1.
|
|
138
|
+
let i = "mParticle_wsdkv_" + a().getVersion() + "_kitv_" + "1.28.0";
|
|
139
139
|
return n && (i += "_" + n), i;
|
|
140
140
|
}
|
|
141
141
|
function Q(n) {
|
|
@@ -322,13 +322,15 @@ const h = class h {
|
|
|
322
322
|
a().logEvent(J, t, e);
|
|
323
323
|
}
|
|
324
324
|
buildIdentityEvent(e, t) {
|
|
325
|
-
const i = t.getMPID(), r = a() && a().sessionManager && typeof a().sessionManager.getSession == "function" ? a().sessionManager.getSession() : void 0;
|
|
325
|
+
const i = t.getMPID(), r = a() && a().sessionManager && typeof a().sessionManager.getSession == "function" ? a().sessionManager.getSession() : void 0, s = this.returnUserIdentities(t);
|
|
326
326
|
return {
|
|
327
327
|
event_type: e,
|
|
328
328
|
data: {
|
|
329
329
|
timestamp_unixtime_ms: Date.now(),
|
|
330
330
|
session_uuid: r ?? void 0,
|
|
331
|
-
mpid: i
|
|
331
|
+
mpid: i,
|
|
332
|
+
user_identities: s,
|
|
333
|
+
user_attributes: this.userAttributes
|
|
332
334
|
}
|
|
333
335
|
};
|
|
334
336
|
}
|
package/dist/Rokt-Kit.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var RoktKit=(function(O){"use strict";const q=["billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],J=new Set(q);function M(n){return J.has(n.toLowerCase())}function k(n){const e={},t=n||{},i=Object.keys(t);for(let r=0;r<i.length;r++){const s=i[r];M(s)||(e[s]=t[s])}return e}const d="Rokt",R=181,X="selectPlacements",$="apps.roktecommerce.com",Z=.1,S={LOGIN:"login",LOGOUT:"logout",MODIFY_USER:"modify_user",IDENTIFY:"identify"},ee="ThankYouPageJourney",te="rokt-launcher",ie="rokt-thank-you-element",ne="userIdentifiedInWorkspace",re=500,N={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},v={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},se="apps.rokt-api.com/v1/log",oe="apps.rokt-api.com/v1/errors",ae=10;function a(){return window.mParticle}function K(n,e){const i=[Y(n),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?i:i+"?extensions="+e.join(",")}function D(n){return[Y(n),"/rokt-elements/rokt-element-thank-you.js"].join("")}function Y(n){return["https://",typeof n<"u"?n:"apps.rokt-api.com"].join("")}function x(n,e,t){if(document.getElementById(n))return;const i=document.head||document.body,r=document.createElement("script");r.id=n,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),i.appendChild(r)}function A(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function w(n){if(!n)return[];try{return JSON.parse(n.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function F(n){const e=n?w(n):[],t=[],i=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,i.push(ee)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:i,loadThankYouElement:r}}async function ce(n,e){const t=[];if(e)for(const i of n)t.push(e.use(i));return Promise.all(t)}function j(n){if(!n)return{};const e={};for(let t=0;t<n.length;t++){const i=n[t];e[i.jsmap]=i.value}return e}function H(n){const e={};if(!Array.isArray(n))return e;for(let t=0;t<n.length;t++){const i=n[t];if(!i||!p(i.value)||!p(i.map))continue;const r=i.value,s=i.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return e}function G(n,e,t){return a().generateHash([n,e,t].join(""))}function E(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function p(n){return typeof n=="string"}function ue(n){let i="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"1.27.0";return n&&(i+="_"+n),i}function z(n){let e=5381;for(let t=0;t<n.length;t++)e=(e<<5)+e+n.charCodeAt(t),e=e&e;return e}function P(n){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=n,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function W(n,e){const t=z(window.location.origin);if(m._allowedOriginHashes.indexOf(t)===-1||Math.random()>=Z)return;const r=window.__rokt_li_guid__;if(!r)return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s);P("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+o),P("https://"+$+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function le(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function de(){return typeof window<"u"?window.location?.href:void 0}function he(){return typeof window<"u"?window.navigator?.userAgent:void 0}class Q{constructor(){this._logCount={}}incrementAndCheck(e){const i=(this._logCount[e]||0)+1;return this._logCount[e]=i,i>ae}}class U{constructor(e,t,i,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=s||new Q,this._isEnabled=le()||o}send(e,t,i,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:i,version:this._integrationName},severity:t,code:r||N.UNKNOWN_ERROR,url:de(),deviceInfo:he(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},l={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(l["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(l["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:l,body:JSON.stringify(c)}).catch(u=>{console.error("ReportingTransport: Failed to send log",u),o&&o(u)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class B{constructor(e,t,i,r,s){this._transport=new U(e,t,i,r,s),this._errorUrl="https://"+(e?.errorUrl||oe)}report(e){if(!e)return;const t=e.severity||v.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class V{constructor(e,t,i,r,s,o){this._transport=new U(e,i,r,s,o),this._loggingUrl="https://"+(e?.loggingUrl||se),this._errorReportingService=t}log(e){e&&this._transport.send(this._loggingUrl,v.INFO,e.message,e.code,void 0,t=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+t.message,code:N.UNKNOWN_ERROR,severity:v.ERROR})})}}const h=class h{constructor(){this.name=d,this.id=R,this.moduleId=R,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.batchQueue=[],this.batchStreamQueue=[],this.pendingIdentityEvents=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null}getEventAttributeValue(e,t){const i=e&&e.EventAttributes;return!i||typeof i[t]>"u"?null:i[t]}doesEventAttributeConditionMatch(e,t){if(!e||!p(e.operator))return!1;const i=e.operator.toLowerCase(),r=e.attributeValue;return i==="exists"?t!==null:t==null?!1:i==="equals"?String(t)===String(r):i==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!p(t.eventAttributeKey))return!1;const i=t.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(i.length===0)return r!==null;for(let s=0;s<i.length;s++)if(!this.doesEventAttributeConditionMatch(i[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<t.length;i++){const r=t[i],s=this.placementEventAttributeMappingLookup[r];if(E(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:E(this.placementEventMappingLookup)&&E(this.placementEventAttributeMappingLookup)?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},i=this._mappedEmailSha256Key;return i&&e[i]&&(t[h.EMAIL_SHA256_KEY]=e[i]),i&&delete t[i],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!A(e))return;const t=a().EventType.Other;a().logEvent(X,t,e)}buildIdentityEvent(e,t){const i=t.getMPID(),r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0;return{event_type:e,data:{timestamp_unixtime_ms:Date.now(),session_uuid:r??void 0,mpid:i}}}mergePendingIdentityEvents(e){if(this.pendingIdentityEvents.length===0)return e;const t={...e,events:[...e.events??[],...this.pendingIdentityEvents]};return this.pendingIdentityEvents=[],t}drainBatchQueue(){this.batchQueue.forEach(e=>{this.processBatch(e)}),this.batchQueue=[]}processBatch(e){if(!this.isKitReady())return this.batchQueue.push(e),"Batch queued for forwarder: "+d;const t=this.enrichCommerceEventTypes(this.mergePendingIdentityEvents(e));return this.sendBatchStream(t),"Successfully sent batch to forwarder: "+d}enrichCommerceEventTypes(e){if(!e.events)return e;for(const t of e.events){if(t.event_type!=="commerce_event")continue;const{data:i}=t;if(!i)continue;const r=i.custom_flags?.["Rokt.CommerceEventType"];r&&A(i.product_action)&&(i.product_action.action=r)}return e}sendBatchStream(e){if(window.Rokt&&typeof window.Rokt.__batch_stream__=="function"){if(this.batchStreamQueue.length){const t=this.batchStreamQueue;this.batchStreamQueue=[];for(let i=0;i<t.length;i++)window.Rokt.__batch_stream__(t[i])}window.Rokt.__batch_stream__(e)}else this.batchStreamQueue.push(e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&typeof t.setIntegrationAttribute=="function"&&t.setIntegrationAttribute(R,{roktSessionId:e})}catch{}}attachLauncher(e,t,i=[]){const r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s={accountId:e,...t||{},...r?{mpSessionId:r}:{}};let o;this.isPartnerInLocalLauncherTestGroup()?o=Promise.resolve(window.Rokt.createLocalLauncher(s)):o=window.Rokt.createLauncher(s),o.then(async c=>{await ce(i,c),this.initRoktLauncher(c)}).catch(c=>{console.error("Error creating Rokt launcher:",c)})}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e;const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,W(this.domain,this.integrationName),a().Rokt.attachKit(this),this.drainBatchQueue()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,i,r,s){const o=e,c=o.accountId;this.userAttributes=k(s),this._onboardingExpProvider=o.onboardingExpProvider;const l=w(o.placementEventMapping);this.placementEventMappingLookup=j(l);const u=w(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=H(u),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=p(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const _=a().Rokt?.domain,{roktExtensionsQueryParams:C,legacyRoktExtensions:b,loadThankYouElement:L}=F(o.roktExtensions),g={...a().Rokt?.launcherOptions||{}};this.integrationName=ue(g.integrationName),g.integrationName=this.integrationName,this.domain=_;const y={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,isLoggingEnabled:a().config?.isLoggingEnabled===!0},I=new B(y,this.integrationName,window.__rokt_li_guid__,o.accountId),T=new V(y,I,this.integrationName,window.__rokt_li_guid__,o.accountId);return this.errorReportingService=I,this.loggingService=T,a()._registerErrorReportingService&&a()._registerErrorReportingService(I),a()._registerLoggingService&&a()._registerLoggingService(T),i?(this.testHelpers={generateLauncherScript:K,generateThankYouElementScript:D,extractRoktExtensionConfig:F,hashEventMessage:G,parseSettingsString:w,generateMappedEventLookup:j,generateMappedEventAttributeLookup:H,sendAdBlockMeasurementSignals:W,createAutoRemovedIframe:P,djb2:z,setAllowedOriginHashes:f=>{h._allowedOriginHashes=f},ReportingTransport:U,ErrorReportingService:B,LoggingService:V,RateLimiter:Q,ErrorCodes:N,WSDKErrorSeverity:v},this.attachLauncher(c,g),"Successfully initialized: "+d):(L&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),x(ie,D(_),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:f=>{console.error("Error loading Rokt Thank You Element script:",f)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,g,b):(x(te,K(_,C),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,g,b):console.error("Rokt object is not available after script load.")},onError:f=>{console.error("Error loading Rokt launcher script:",f)}}),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(!this.isKitReady())return"Kit not ready for forwarder: "+d;if(typeof a().Rokt?.setLocalSessionAttribute=="function"&&(E(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!E(this.placementEventMappingLookup))){const t=G(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return M(e)||(this.userAttributes[e]=t),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t,i){const r=e;return this.userAttributes=k(e.getAllUserAttributes()),this.pendingIdentityEvents.push(this.buildIdentityEvent(t,r)),"Successfully called "+i+" for forwarder: "+d}onUserIdentified(e){const t=e;return this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t),this.handleIdentityComplete(e,S.IDENTIFY,"onUserIdentified")}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const i=a().Identity?.search;if(typeof i!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const l of Object.keys(r)){const u=r[l];p(u)&&u.length>0&&(s[l]=u)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(l=>`${l}=${s[l]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(l=>{try{i(t,s,u=>{u?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),l()})}catch(u){console.error("Rokt Kit: Workspace IDSync search failed",u),this._workspaceLastSearchedIdentitiesKey=void 0,l()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,S.LOGIN,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.handleIdentityComplete(e,S.LOGOUT,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,S.MODIFY_USER,"onModifyComplete")}selectPlacements(e){if(this._workspaceSearchInFlightPromise){const t=this._workspaceSearchInFlightPromise;return Promise.race([t,new Promise(i=>setTimeout(i,re))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...k(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,l=c?c.getMPID():null;let u;s?s.filterUserAttributes?u=s.filterUserAttributes(r,o):u=r:(console.warn("Rokt Kit: No filters available, using user attributes"),u=r),this.userAttributes=k(u);const _=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},C=this.returnUserIdentities(c),b=this.returnLocalSessionAttributes(),L={...C,...u,..._,...b,...this.userIdentifiedInWorkspace?{[ne]:!0}:{},mpid:l},g={...e,attributes:L},y=this.launcher.selectPlacements(g),I=()=>this.logSelectPlacementsEvent(L);return Promise.resolve(y).then(T=>T?.context?.sessionId?.then(f=>this.setRoktSessionId(f))).catch(()=>{}).finally(I),y}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!p(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let m=h;function pe(){return R}function ge(n){if(!n){window.console.log("You must pass a config object to register the kit "+d);return}if(!A(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}A(n.kits)?n.kits[d]={constructor:m}:(n.kits={},n.kits[d]={constructor:m}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:m,getId:pe}),O.register=ge,Object.defineProperty(O,Symbol.toStringTag,{value:"Module"}),O})({});
|
|
1
|
+
var RoktKit=(function(O){"use strict";const q=["billingaddress1","billingaddress2","billingcity","billingstate","billingzipcode","cartitems","ccbin","confirmationref","conversiontype","country","couponcode","currency","language","paymentserviceprovider","paymentserviceproviderattribute","paymenttype","shippingaddress1","shippingcity","shippingcountry","shippingmethod","shippingstate","shippingzipcode","totalprice"],J=new Set(q);function M(n){return J.has(n.toLowerCase())}function k(n){const e={},t=n||{},i=Object.keys(t);for(let r=0;r<i.length;r++){const s=i[r];M(s)||(e[s]=t[s])}return e}const d="Rokt",R=181,X="selectPlacements",$="apps.roktecommerce.com",Z=.1,S={LOGIN:"login",LOGOUT:"logout",MODIFY_USER:"modify_user",IDENTIFY:"identify"},ee="ThankYouPageJourney",te="rokt-launcher",ie="rokt-thank-you-element",ne="userIdentifiedInWorkspace",re=500,N={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},v={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},se="apps.rokt-api.com/v1/log",oe="apps.rokt-api.com/v1/errors",ae=10;function a(){return window.mParticle}function K(n,e){const i=[Y(n),"/wsdk/integrations/launcher.js"].join("");return!e||e.length===0?i:i+"?extensions="+e.join(",")}function D(n){return[Y(n),"/rokt-elements/rokt-element-thank-you.js"].join("")}function Y(n){return["https://",typeof n<"u"?n:"apps.rokt-api.com"].join("")}function x(n,e,t){if(document.getElementById(n))return;const i=document.head||document.body,r=document.createElement("script");r.id=n,r.type="text/javascript",r.src=e,r.async=!0,r.crossOrigin="anonymous",r.fetchPriority="high",t?.onLoad&&(r.onload=t.onLoad),t?.onError&&(r.onerror=t.onError),i.appendChild(r)}function A(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function w(n){if(!n)return[];try{return JSON.parse(n.replace(/"/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function F(n){const e=n?w(n):[],t=[],i=[];let r=!1;for(let s=0;s<e.length;s++){const o=e[s].value;o==="thank-you-journey"?(r=!0,i.push(ee)):t.push(o)}return{roktExtensionsQueryParams:t,legacyRoktExtensions:i,loadThankYouElement:r}}async function ce(n,e){const t=[];if(e)for(const i of n)t.push(e.use(i));return Promise.all(t)}function j(n){if(!n)return{};const e={};for(let t=0;t<n.length;t++){const i=n[t];e[i.jsmap]=i.value}return e}function H(n){const e={};if(!Array.isArray(n))return e;for(let t=0;t<n.length;t++){const i=n[t];if(!i||!p(i.value)||!p(i.map))continue;const r=i.value,s=i.map;e[r]||(e[r]=[]),e[r].push({eventAttributeKey:s,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return e}function G(n,e,t){return a().generateHash([n,e,t].join(""))}function E(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function p(n){return typeof n=="string"}function ue(n){let i="mParticle_wsdkv_"+a().getVersion()+"_kitv_"+"1.28.0";return n&&(i+="_"+n),i}function z(n){let e=5381;for(let t=0;t<n.length;t++)e=(e<<5)+e+n.charCodeAt(t),e=e&e;return e}function P(n){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts allow-same-origin"),e.src=n,e.onload=function(){e.onload=null,e.parentNode&&e.parentNode.removeChild(e)};const t=document.body||document.head;t&&t.appendChild(e)}function W(n,e){const t=z(window.location.origin);if(m._allowedOriginHashes.indexOf(t)===-1||Math.random()>=Z)return;const r=window.__rokt_li_guid__;if(!r)return;const s=window.location.href.split("?")[0].split("#")[0],o="version="+encodeURIComponent(e??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s);P("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+o),P("https://"+$+"/v1/wsdk-init/index.html?"+o+"&isControl=true")}function le(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function de(){return typeof window<"u"?window.location?.href:void 0}function he(){return typeof window<"u"?window.navigator?.userAgent:void 0}class Q{constructor(){this._logCount={}}incrementAndCheck(e){const i=(this._logCount[e]||0)+1;return this._logCount[e]=i,i>ae}}class U{constructor(e,t,i,r,s){this._reporter="mp-wsdk";const o=e.isLoggingEnabled;this._integrationName=t||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=s||new Q,this._isEnabled=le()||o}send(e,t,i,r,s,o){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(t)))try{const c={additionalInformation:{message:i,version:this._integrationName},severity:t,code:r||N.UNKNOWN_ERROR,url:de(),deviceInfo:he(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},l={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(l["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(l["rokt-account-id"]=this._accountId),fetch(e,{method:"POST",headers:l,body:JSON.stringify(c)}).catch(u=>{console.error("ReportingTransport: Failed to send log",u),o&&o(u)})}catch(c){console.error("ReportingTransport: Failed to send log",c),o&&o(c)}}}class B{constructor(e,t,i,r,s){this._transport=new U(e,t,i,r,s),this._errorUrl="https://"+(e?.errorUrl||oe)}report(e){if(!e)return;const t=e.severity||v.ERROR;this._transport.send(this._errorUrl,t,e.message,e.code,e.stackTrace)}}class V{constructor(e,t,i,r,s,o){this._transport=new U(e,i,r,s,o),this._loggingUrl="https://"+(e?.loggingUrl||se),this._errorReportingService=t}log(e){e&&this._transport.send(this._loggingUrl,v.INFO,e.message,e.code,void 0,t=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+t.message,code:N.UNKNOWN_ERROR,severity:v.ERROR})})}}const h=class h{constructor(){this.name=d,this.id=R,this.moduleId=R,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.userIdentifiedInWorkspace=!1,this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.batchQueue=[],this.batchStreamQueue=[],this.pendingIdentityEvents=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null,this._thankYouElementOnLoadCallback=null,this._isThankYouElementLoaded=!1,this._workspaceSearchInFlightPromise=null}getEventAttributeValue(e,t){const i=e&&e.EventAttributes;return!i||typeof i[t]>"u"?null:i[t]}doesEventAttributeConditionMatch(e,t){if(!e||!p(e.operator))return!1;const i=e.operator.toLowerCase(),r=e.attributeValue;return i==="exists"?t!==null:t==null?!1:i==="equals"?String(t)===String(r):i==="contains"?String(t).indexOf(String(r))!==-1:!1}doesEventMatchRule(e,t){if(!t||!p(t.eventAttributeKey))return!1;const i=t.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(e,t.eventAttributeKey);if(i.length===0)return r!==null;for(let s=0;s<i.length;s++)if(!this.doesEventAttributeConditionMatch(i[s],r))return!1;return!0}applyPlacementEventAttributeMapping(e){const t=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<t.length;i++){const r=t[i],s=this.placementEventAttributeMappingLookup[r];if(E(s))continue;let o=!0;for(let c=0;c<s.length;c++)if(!this.doesEventMatchRule(e,s[c])){o=!1;break}o&&a().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(e){if(!e||!e.getUserIdentities)return{};const t=e.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(t)}returnLocalSessionAttributes(){return!a().Rokt||typeof a().Rokt.getLocalSessionAttributes!="function"?{}:E(this.placementEventMappingLookup)&&E(this.placementEventAttributeMappingLookup)?{}:a().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(e){const t={...e||{}},i=this._mappedEmailSha256Key;return i&&e[i]&&(t[h.EMAIL_SHA256_KEY]=e[i]),i&&delete t[i],t}logSelectPlacementsEvent(e){if(!window.mParticle||typeof a().logEvent!="function"||!A(e))return;const t=a().EventType.Other;a().logEvent(X,t,e)}buildIdentityEvent(e,t){const i=t.getMPID(),r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s=this.returnUserIdentities(t);return{event_type:e,data:{timestamp_unixtime_ms:Date.now(),session_uuid:r??void 0,mpid:i,user_identities:s,user_attributes:this.userAttributes}}}mergePendingIdentityEvents(e){if(this.pendingIdentityEvents.length===0)return e;const t={...e,events:[...e.events??[],...this.pendingIdentityEvents]};return this.pendingIdentityEvents=[],t}drainBatchQueue(){this.batchQueue.forEach(e=>{this.processBatch(e)}),this.batchQueue=[]}processBatch(e){if(!this.isKitReady())return this.batchQueue.push(e),"Batch queued for forwarder: "+d;const t=this.enrichCommerceEventTypes(this.mergePendingIdentityEvents(e));return this.sendBatchStream(t),"Successfully sent batch to forwarder: "+d}enrichCommerceEventTypes(e){if(!e.events)return e;for(const t of e.events){if(t.event_type!=="commerce_event")continue;const{data:i}=t;if(!i)continue;const r=i.custom_flags?.["Rokt.CommerceEventType"];r&&A(i.product_action)&&(i.product_action.action=r)}return e}sendBatchStream(e){if(window.Rokt&&typeof window.Rokt.__batch_stream__=="function"){if(this.batchStreamQueue.length){const t=this.batchStreamQueue;this.batchStreamQueue=[];for(let i=0;i<t.length;i++)window.Rokt.__batch_stream__(t[i])}window.Rokt.__batch_stream__(e)}else this.batchStreamQueue.push(e)}setRoktSessionId(e){if(!(!e||typeof e!="string"))try{const t=a().getInstance();t&&typeof t.setIntegrationAttribute=="function"&&t.setIntegrationAttribute(R,{roktSessionId:e})}catch{}}attachLauncher(e,t,i=[]){const r=a()&&a().sessionManager&&typeof a().sessionManager.getSession=="function"?a().sessionManager.getSession():void 0,s={accountId:e,...t||{},...r?{mpSessionId:r}:{}};let o;this.isPartnerInLocalLauncherTestGroup()?o=Promise.resolve(window.Rokt.createLocalLauncher(s)):o=window.Rokt.createLauncher(s),o.then(async c=>{await ce(i,c),this.initRoktLauncher(c)}).catch(c=>{console.error("Error creating Rokt launcher:",c)})}initRoktLauncher(e){window.Rokt&&(window.Rokt.currentLauncher=e),this.launcher=e;const t=a().Rokt?.filters;t?(this.filters=t,t.filteredUser?this._workspaceSearchInFlightPromise=this.search(t.filteredUser):console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,W(this.domain,this.integrationName),a().Rokt.attachKit(this),this.drainBatchQueue()}fetchOptimizely(){const e=a()._getActiveForwarders().filter(t=>t.name==="Optimizely");try{if(e.length>0&&window.optimizely){const t=window.optimizely.get("state");return!t||!t.getActiveExperimentIds?{}:t.getActiveExperimentIds().reduce((s,o)=>(s["rokt.custom.optimizely.experiment."+o+".variationId"]=t.getVariationMap()[o].id,s),{})}}catch(t){console.error("Error fetching Optimizely attributes:",t)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(a().config&&a().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(e){window&&a()&&a().captureTiming&&e&&a().captureTiming(e)}init(e,t,i,r,s){const o=e,c=o.accountId;this.userAttributes=k(s),this._onboardingExpProvider=o.onboardingExpProvider;const l=w(o.placementEventMapping);this.placementEventMappingLookup=j(l);const u=w(o.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=H(u),o.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=o.hashedEmailUserIdentityType.toLowerCase()),this._workspaceIdSyncApiKey=p(o.workspaceIdSyncApiKey)?o.workspaceIdSyncApiKey:void 0;const _=a().Rokt?.domain,{roktExtensionsQueryParams:C,legacyRoktExtensions:b,loadThankYouElement:L}=F(o.roktExtensions),g={...a().Rokt?.launcherOptions||{}};this.integrationName=ue(g.integrationName),g.integrationName=this.integrationName,this.domain=_;const y={loggingUrl:o.loggingUrl,errorUrl:o.errorUrl,isLoggingEnabled:a().config?.isLoggingEnabled===!0},I=new B(y,this.integrationName,window.__rokt_li_guid__,o.accountId),T=new V(y,I,this.integrationName,window.__rokt_li_guid__,o.accountId);return this.errorReportingService=I,this.loggingService=T,a()._registerErrorReportingService&&a()._registerErrorReportingService(I),a()._registerLoggingService&&a()._registerLoggingService(T),i?(this.testHelpers={generateLauncherScript:K,generateThankYouElementScript:D,extractRoktExtensionConfig:F,hashEventMessage:G,parseSettingsString:w,generateMappedEventLookup:j,generateMappedEventAttributeLookup:H,sendAdBlockMeasurementSignals:W,createAutoRemovedIframe:P,djb2:z,setAllowedOriginHashes:f=>{h._allowedOriginHashes=f},ReportingTransport:U,ErrorReportingService:B,LoggingService:V,RateLimiter:Q,ErrorCodes:N,WSDKErrorSeverity:v},this.attachLauncher(c,g),"Successfully initialized: "+d):(L&&(a().Rokt.flushOnShoppableAdsReadyMessageQueue?.(this),x(ie,D(_),{onLoad:()=>{this._isThankYouElementLoaded=!0,this._thankYouElementOnLoadCallback&&this._thankYouElementOnLoadCallback()},onError:f=>{console.error("Error loading Rokt Thank You Element script:",f)}})),this.isLauncherReadyToAttach()?this.attachLauncher(c,g,b):(x(te,K(_,C),{onLoad:()=>{this.isLauncherReadyToAttach()?this.attachLauncher(c,g,b):console.error("Rokt object is not available after script load.")},onError:f=>{console.error("Error loading Rokt launcher script:",f)}}),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)),"Successfully initialized: "+d)}process(e){if(!this.isKitReady())return"Kit not ready for forwarder: "+d;if(typeof a().Rokt?.setLocalSessionAttribute=="function"&&(E(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(e),!E(this.placementEventMappingLookup))){const t=G(e.EventDataType,e.EventCategory,e.EventName??"");this.placementEventMappingLookup[String(t)]&&a().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(t)],!0)}return"Successfully sent to forwarder: "+d}setExtensionData(e){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(e)}setUserAttribute(e,t){return M(e)||(this.userAttributes[e]=t),"Successfully set user attribute for forwarder: "+d}removeUserAttribute(e){return delete this.userAttributes[e],"Successfully removed user attribute for forwarder: "+d}handleIdentityComplete(e,t,i){const r=e;return this.userAttributes=k(e.getAllUserAttributes()),this.pendingIdentityEvents.push(this.buildIdentityEvent(t,r)),"Successfully called "+i+" for forwarder: "+d}onUserIdentified(e){const t=e;return this.filters.filteredUser=t,this._workspaceSearchInFlightPromise=this.search(t),this.handleIdentityComplete(e,S.IDENTIFY,"onUserIdentified")}search(e){const t=this._workspaceIdSyncApiKey;if(!t)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const i=a().Identity?.search;if(typeof i!="function")return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const r=e.getUserIdentities?e.getUserIdentities().userIdentities:null,s={};if(r)for(const l of Object.keys(r)){const u=r[l];p(u)&&u.length>0&&(s[l]=u)}const o=Object.keys(s);if(o.length===0)return this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=void 0,Promise.resolve();const c=o.sort().map(l=>`${l}=${s[l]}`).join("&");return c===this._workspaceLastSearchedIdentitiesKey?this._workspaceSearchInFlightPromise||Promise.resolve():(this.userIdentifiedInWorkspace=!1,this._workspaceLastSearchedIdentitiesKey=c,new Promise(l=>{try{i(t,s,u=>{u?.httpCode===200&&(this.userIdentifiedInWorkspace=!0),l()})}catch(u){console.error("Rokt Kit: Workspace IDSync search failed",u),this._workspaceLastSearchedIdentitiesKey=void 0,l()}}))}onLoginComplete(e,t){return this.handleIdentityComplete(e,S.LOGIN,"onLoginComplete")}onLogoutComplete(e,t){return this.userIdentifiedInWorkspace=!1,this._workspaceSearchInFlightPromise=null,this._workspaceLastSearchedIdentitiesKey=void 0,this.handleIdentityComplete(e,S.LOGOUT,"onLogoutComplete")}onModifyComplete(e,t){return this.handleIdentityComplete(e,S.MODIFY_USER,"onModifyComplete")}selectPlacements(e){if(this._workspaceSearchInFlightPromise){const t=this._workspaceSearchInFlightPromise;return Promise.race([t,new Promise(i=>setTimeout(i,re))]).then(()=>this._dispatchPlacements(e))}return this._dispatchPlacements(e)}_dispatchPlacements(e){const t=e&&e.attributes||{},r={...k(this.userAttributes),...t},s=this.filters||{},o=s.userAttributeFilters||[],c=s.filteredUser||null,l=c?c.getMPID():null;let u;s?s.filterUserAttributes?u=s.filterUserAttributes(r,o):u=r:(console.warn("Rokt Kit: No filters available, using user attributes"),u=r),this.userAttributes=k(u);const _=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},C=this.returnUserIdentities(c),b=this.returnLocalSessionAttributes(),L={...C,...u,..._,...b,...this.userIdentifiedInWorkspace?{[ne]:!0}:{},mpid:l},g={...e,attributes:L},y=this.launcher.selectPlacements(g),I=()=>this.logSelectPlacementsEvent(L);return Promise.resolve(y).then(T=>T?.context?.sessionId?.then(f=>this.setRoktSessionId(f))).catch(()=>{}).finally(I),y}hashAttributes(e){return this.isKitReady()?this.launcher.hashAttributes(e):(console.error("Rokt Kit: Not initialized"),null)}use(e){return this.isKitReady()?!e||!p(e)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(e):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}onShoppableAdsReady(e){this._isThankYouElementLoaded?e():this._thankYouElementOnLoadCallback=e}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let m=h;function pe(){return R}function ge(n){if(!n){window.console.log("You must pass a config object to register the kit "+d);return}if(!A(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}A(n.kits)?n.kits[d]={constructor:m}:(n.kits={},n.kits[d]={constructor:m}),window.console.log("Successfully registered "+d+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&a().addForwarder&&a().addForwarder({name:d,constructor:m,getId:pe}),O.register=ge,Object.defineProperty(O,Symbol.toStringTag,{value:"Module"}),O})({});
|
|
2
2
|
//# sourceMappingURL=Rokt-Kit.iife.js.map
|