@mparticle/web-sdk 3.21.0 → 3.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.
- package/dist/mparticle.common.js +230 -161
- package/dist/mparticle.esm.js +230 -161
- package/dist/mparticle.js +4536 -4111
- package/dist/types/src/batchUploader.d.ts +2 -0
- package/dist/types/src/buttonTracking/buttonDescription.d.ts +2 -1
- package/dist/types/src/buttonTracking/buttonTracker.d.ts +6 -0
- package/dist/types/src/buttonTracking/checkoutIntent.d.ts +7 -1
- package/dist/types/src/buttonTracking/controls.d.ts +3 -0
- package/dist/types/src/pageUrl.d.ts +10 -0
- package/dist/types/src/pageViewTracker.d.ts +2 -0
- package/dist/types/src/roktManager.d.ts +9 -2
- package/dist/types/src/sdkRuntimeModels.d.ts +2 -0
- package/package.json +1 -1
- package/src/batchUploader.ts +36 -3
- package/src/buttonTracking/buttonClickEvent.ts +3 -0
- package/src/buttonTracking/buttonDescription.ts +24 -3
- package/src/buttonTracking/buttonTracker.ts +92 -8
- package/src/buttonTracking/checkoutIntent.ts +199 -66
- package/src/buttonTracking/controls.ts +150 -32
- package/src/mp-instance.ts +5 -8
- package/src/mparticle-instance-manager.ts +3 -0
- package/src/pageUrl.ts +150 -0
- package/src/pageViewTracker.ts +60 -8
- package/src/roktManager.ts +50 -17
- package/src/sdkRuntimeModels.ts +2 -0
- package/src/serverModel.ts +3 -3
- package/src/utils.ts +1 -1
package/dist/mparticle.esm.js
CHANGED
|
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
|
|
|
15
15
|
filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
|
|
16
16
|
isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
|
|
17
17
|
|
|
18
|
-
var version = "3.
|
|
18
|
+
var version = "3.23.0";
|
|
19
19
|
|
|
20
20
|
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
21
21
|
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
|
|
@@ -149,7 +149,7 @@ var Messages$a=Constants.Messages,createCookieString=function(a){return replaceC
|
|
|
149
149
|
generateUniqueId// random hex digits
|
|
150
150
|
)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d,e){var f=replaceAmpWithAmpersand(b),g=c?replaceAmpWithAmpersand(c):null,h=replaceMPID(f,a),i=g?replaceMPID(g,a):"",j=h+encodeURIComponent(i);if(d){var k=j.includes("?")?"&":"?";j+="".concat(k,"domain=").concat(d);}if(e){var k=j.includes("?")?"&":"?";j+="".concat(k,"google_hm=").concat(e);}return j},WEB_SAFE_BASE64_REPLACEMENTS={"+":"-","/":"_","=":""},isLatin1=function(a){return !/[^\u0000-\u00ff]/.test(a)},toWebSafeBase64=function(a){return isLatin1(a)?btoa(a).replace(/[+/=]/g,function(a){return WEB_SAFE_BASE64_REPLACEMENTS[a]}):void 0},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers
|
|
151
151
|
return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},hasOwnProp=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)},isReservedStoredPropertyName=function(a){return "__proto__"===a||"constructor"===a},isUncopyableMergeName=function(a){return isReservedStoredPropertyName(a)||"prototype"===a},isReservedKitPropertyName=function(a){return isReservedStoredPropertyName(a)||"hasOwnProperty"===a},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=a.toLowerCase();// Callers pass their own key list, so `name` may not be from this URL.
|
|
152
|
-
hasOwnProp(e,b)&&e[b]&&(d[a]=e[b]);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)// Keys come straight off the URL, so `?hasOwnProperty=1` would
|
|
152
|
+
hasOwnProp(e,b)&&e[b]&&(d[a]=e[b]);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("#")[0].split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)// Keys come straight off the URL, so `?hasOwnProperty=1` would
|
|
153
153
|
// shadow the method and `params.hasOwnProperty(key)` would throw.
|
|
154
154
|
hasOwnProp(b,c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie
|
|
155
155
|
var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
|
|
@@ -514,6 +514,144 @@ return g=Object.assign(g,b),{event_type:dist.EventTypeEnum.applicationStateTrans
|
|
|
514
514
|
//spanning_mpids: sdkEvent.SessionMpids
|
|
515
515
|
};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionEnd,data:c}}function convertSessionStartEvent(a){var b=convertBaseEventData(a),c={};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionStart,data:c}}function convertPageViewEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,screen_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.screenView,data:c}}function convertOptOutEvent(a){var b=convertBaseEventData(a),c={is_opted_out:a.OptOut};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.optOut,data:c}}function convertCustomEvent(a){var b=convertBaseEventData(a),c={custom_event_type:convertSdkEventType(a.EventCategory),custom_flags:a.CustomFlags,event_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.customEvent,data:c}}function convertSdkEventType(a){return a===Types.EventType.Other?dist.CustomEventDataCustomEventTypeEnum.other:a===Types.EventType.Location?dist.CustomEventDataCustomEventTypeEnum.location:a===Types.EventType.Navigation?dist.CustomEventDataCustomEventTypeEnum.navigation:a===Types.EventType.Search?dist.CustomEventDataCustomEventTypeEnum.search:a===Types.EventType.Social?dist.CustomEventDataCustomEventTypeEnum.social:a===Types.EventType.Transaction?dist.CustomEventDataCustomEventTypeEnum.transaction:a===Types.EventType.UserContent?dist.CustomEventDataCustomEventTypeEnum.userContent:a===Types.EventType.UserPreference?dist.CustomEventDataCustomEventTypeEnum.userPreference:a===Types.EventType.Media?dist.CustomEventDataCustomEventTypeEnum.media:a===Types.CommerceEventType.ProductAddToCart?dist.CommerceEventDataCustomEventTypeEnum.addToCart:a===Types.CommerceEventType.ProductAddToWishlist?dist.CommerceEventDataCustomEventTypeEnum.addToWishlist:a===Types.CommerceEventType.ProductCheckout?dist.CommerceEventDataCustomEventTypeEnum.checkout:a===Types.CommerceEventType.ProductCheckoutOption?dist.CommerceEventDataCustomEventTypeEnum.checkoutOption:a===Types.CommerceEventType.ProductClick?dist.CommerceEventDataCustomEventTypeEnum.click:a===Types.CommerceEventType.ProductImpression?dist.CommerceEventDataCustomEventTypeEnum.impression:a===Types.CommerceEventType.ProductPurchase?dist.CommerceEventDataCustomEventTypeEnum.purchase:a===Types.CommerceEventType.ProductRefund?dist.CommerceEventDataCustomEventTypeEnum.refund:a===Types.CommerceEventType.ProductRemoveFromCart?dist.CommerceEventDataCustomEventTypeEnum.removeFromCart:a===Types.CommerceEventType.ProductRemoveFromWishlist?dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist:a===Types.CommerceEventType.ProductViewDetail?dist.CommerceEventDataCustomEventTypeEnum.viewDetail:a===Types.CommerceEventType.PromotionClick?dist.CommerceEventDataCustomEventTypeEnum.promotionClick:a===Types.CommerceEventType.PromotionView?dist.CommerceEventDataCustomEventTypeEnum.promotionView:dist.CustomEventDataCustomEventTypeEnum.unknown}function convertBaseEventData(a){var b={timestamp_unixtime_ms:a.Timestamp,session_uuid:a.SessionId,session_start_unixtime_ms:a.SessionStartDate,custom_attributes:a.EventAttributes,location:convertSDKLocation(a.Location),source_message_id:a.SourceMessageId,active_time_on_site_ms:a.ActiveTimeOnSite,total_time_on_site_ms:a.TotalTimeOnSite,page_url:a.PageUrl};return b}function convertSDKLocation(a){return a&&Object.keys(a).length?{latitude:a.lat,longitude:a.lng}:null}function convertUserAttributeChangeEvent(a){var b=convertBaseEventData(a),c={user_attribute_name:a.UserAttributeChanges.UserAttributeName,new:a.UserAttributeChanges.New,old:a.UserAttributeChanges.Old,deleted:a.UserAttributeChanges.Deleted,is_new_attribute:a.UserAttributeChanges.IsNewAttribute};return c=__assign(__assign({},c),b),{event_type:dist.EventTypeEnum.userAttributeChange,data:c}}function convertUserIdentityChangeEvent(a){var b=convertBaseEventData(a),c={new:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.New.IdentityType),identity:a.UserIdentityChanges.New.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.New.CreatedThisBatch},old:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.Old.IdentityType),identity:a.UserIdentityChanges.Old.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.Old.CreatedThisBatch}};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.userIdentityChange,data:c}}function convertUserIdentityTypeToServerIdentityType(a){return a===SDKIdentityTypeEnum.other?dist.IdentityTypeEnum.other:a===SDKIdentityTypeEnum.customerId?dist.IdentityTypeEnum.customerId:a===SDKIdentityTypeEnum.facebook?dist.IdentityTypeEnum.facebook:a===SDKIdentityTypeEnum.twitter?dist.IdentityTypeEnum.twitter:a===SDKIdentityTypeEnum.google?dist.IdentityTypeEnum.google:a===SDKIdentityTypeEnum.microsoft?dist.IdentityTypeEnum.microsoft:a===SDKIdentityTypeEnum.yahoo?dist.IdentityTypeEnum.yahoo:a===SDKIdentityTypeEnum.email?dist.IdentityTypeEnum.email:a===SDKIdentityTypeEnum.alias?dist.IdentityTypeEnum.alias:a===SDKIdentityTypeEnum.facebookCustomAudienceId?dist.IdentityTypeEnum.facebookCustomAudienceId:a===SDKIdentityTypeEnum.otherId2?dist.IdentityTypeEnum.otherId2:a===SDKIdentityTypeEnum.otherId3?dist.IdentityTypeEnum.otherId3:a===SDKIdentityTypeEnum.otherId4?dist.IdentityTypeEnum.otherId4:a===SDKIdentityTypeEnum.otherId5?dist.IdentityTypeEnum.otherId5:a===SDKIdentityTypeEnum.otherId6?dist.IdentityTypeEnum.otherId6:a===SDKIdentityTypeEnum.otherId7?dist.IdentityTypeEnum.otherId7:a===SDKIdentityTypeEnum.otherId8?dist.IdentityTypeEnum.otherId8:a===SDKIdentityTypeEnum.otherId9?dist.IdentityTypeEnum.otherId9:a===SDKIdentityTypeEnum.otherId10?dist.IdentityTypeEnum.otherId10:a===SDKIdentityTypeEnum.mobileNumber?dist.IdentityTypeEnum.mobileNumber:a===SDKIdentityTypeEnum.phoneNumber2?dist.IdentityTypeEnum.phoneNumber2:a===SDKIdentityTypeEnum.phoneNumber3?dist.IdentityTypeEnum.phoneNumber3:void 0}
|
|
516
516
|
|
|
517
|
+
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
518
|
+
// returns the single function that undoes it \u2014 or null when nothing was
|
|
519
|
+
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
520
|
+
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
521
|
+
// references out of the tracker entirely: there is no half-patched state for a
|
|
522
|
+
// caller to inspect, and no way to restore the wrong pair.
|
|
523
|
+
var patchHistory=function(a,b){if(window.history.pushState[WRAPPED_MARKER])return b("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED"),null;var c={},d={};HISTORY_METHODS.forEach(function(b){var e=window.history[b];c[b]=e;var f=function(){for(var c=[],d=0;d<arguments.length;d++)c[d]=arguments[d];var f=e.apply(this,c);return a(b),f};Object.defineProperty(f,WRAPPED_MARKER,{value:!0,enumerable:!1}),d[b]=f;});// Restore per method: a third party may have patched one of the two on top of
|
|
524
|
+
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
525
|
+
// leave anything that is no longer ours in place.
|
|
526
|
+
var e=function(){return HISTORY_METHODS.forEach(function(a){window.history[a]===d[a]?(window.history[a]=c[a],b("[teardown] restored original ".concat(a))):b("[teardown] ".concat(a," no longer ours; leaving in place, gating callback to no-op"));})};try{HISTORY_METHODS.forEach(function(a){window.history[a]=d[a];});}catch(a){b("[error] failed to patch history methods (frozen/sealed), rolling back: ".concat(a));try{e();}catch(a){b("[error] failed to restore history methods after patch failure: ".concat(a));}return null}return e};// One History patch for the whole SDK, so page-view tracking and preselection do not
|
|
527
|
+
// stack two wrappers.
|
|
528
|
+
//
|
|
529
|
+
// State lives on `window`, not module scope, because Next.js re-executes the bundle per
|
|
530
|
+
// SPA navigation while the patch from the previous execution stays installed.
|
|
531
|
+
var WIN_ROUTE_MONITOR_KEY="__mpRouteMonitor__";var monitorState=function(){var a=window;return a[WIN_ROUTE_MONITOR_KEY]||(a[WIN_ROUTE_MONITOR_KEY]={listeners:{},undoHistoryPatch:null,popStateListener:null}),a[WIN_ROUTE_MONITOR_KEY]},emit=function(a){Object.values(monitorState().listeners).forEach(function(b){try{b(a);}catch(a){// One subscriber must not stop the others, and must never break navigation.
|
|
532
|
+
}});},install=function(a,b){a.undoHistoryPatch||a.popStateListener||(a.undoHistoryPatch=patchHistory(emit,b),a.popStateListener=function(){return emit("popstate")},window.addEventListener("popstate",a.popStateListener));},uninstall=function(a){a.popStateListener&&(window.removeEventListener("popstate",a.popStateListener),a.popStateListener=null),a.undoHistoryPatch&&(a.undoHistoryPatch(),a.undoHistoryPatch=null);};// Reads the shared state at call time, so a wrapper installed by a previous bundle
|
|
533
|
+
// execution still reaches the current listeners.
|
|
534
|
+
// Installs on the first subscriber and tears down after the last leaves, so a workspace
|
|
535
|
+
// that needs neither is never patched. Unsubscribing only removes the listener while it
|
|
536
|
+
// still owns its key, so an outgoing instance cannot remove its replacement.
|
|
537
|
+
var subscribeToRouteChange=function(a,b,c){if(void 0===c&&(c=function(){}),!supportsHistoryTracking("undefined"==typeof window?null:window))return function(){};var d=monitorState();return d.listeners[a]=b,install(d,c),function(){d.listeners[a]!==b||(delete d.listeners[a],0===Object.keys(d.listeners).length&&uninstall(d));}};
|
|
538
|
+
|
|
539
|
+
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
540
|
+
// tracking is live.
|
|
541
|
+
//
|
|
542
|
+
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
543
|
+
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
544
|
+
// but `window` persists for the lifetime of the tab.
|
|
545
|
+
//
|
|
546
|
+
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
547
|
+
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
548
|
+
// survives the reset.
|
|
549
|
+
var WIN_APV_KEY="__mpApv__";// The query params an auto page view may carry. An allowlist, not a denylist:
|
|
550
|
+
// partner URLs routinely hold order ids, email addresses and session tokens, and
|
|
551
|
+
// none of those should reach the event stream because someone forgot to exclude
|
|
552
|
+
// them. Anything absent from this list is dropped.
|
|
553
|
+
//
|
|
554
|
+
// SECURITY: `code`, `state` and `nonce` are the OAuth 2.0 / OIDC authorization
|
|
555
|
+
// code and the CSRF/replay tokens. They are credentials until redeemed, and
|
|
556
|
+
// attaching them here persists them in the event store and forwards them to
|
|
557
|
+
// every configured kit. They are on the list by explicit product decision \u2014
|
|
558
|
+
// deleting that line is the whole of the fix if that decision is revisited.
|
|
559
|
+
var ALLOWED_QUERY_PARAMS=[// Campaign attribution
|
|
560
|
+
"utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","utm_source_platform","utm_creative_format","utm_marketing_tactic","gad_source","gad_campaignid","mc_cid",// Ad-network click ids
|
|
561
|
+
"gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid","srsltid","epik","ScCid","irclickid","rtid","rclid",// OAuth / OIDC \u2014 see the SECURITY note above
|
|
562
|
+
"client_id","redirect_uri","response_type","scope","state","code","nonce",// Pagination
|
|
563
|
+
"page","limit","offset","cursor","per_page",// Site search term, as the common platforms spell it. Matching is
|
|
564
|
+
// case-insensitive. `s` is WordPress and WooCommerce search; other
|
|
565
|
+
// single-letter names are too generic. `oq` is a storefront search term.
|
|
566
|
+
"q","s","oq","search","query","keyword","keywords","term","text","searchTerm","searchText","search_query","search_text","Ntt",// Product and variant identifiers. `cid` is not a category: it is a
|
|
567
|
+
// customer id on many sites.
|
|
568
|
+
"pid","productId","sku","skuId","variant","color","colour","size",// Category
|
|
569
|
+
"category",// Referral
|
|
570
|
+
"ref","referrer"];// Params matched by name prefix, for platforms that put a per-product id in the
|
|
571
|
+
// name. Salesforce Commerce Cloud spells a variant choice
|
|
572
|
+
// `dwvar_<productId>_<attribute>`, e.g. `dwvar_12345_color=navy`.
|
|
573
|
+
var ALLOWED_QUERY_PARAM_PREFIXES=["dwvar_"];var hasAllowedPrefix=function(a){return ALLOWED_QUERY_PARAM_PREFIXES.some(function(b){return 0===a.indexOf(b)})},ALLOWED_QUERY_PARAMS_LOWER=ALLOWED_QUERY_PARAMS.map(function(a){return a.toLowerCase()});// Whether a query param name, in any case, is one an auto page view captures.
|
|
574
|
+
var isAllowedQueryParam=function(a){var b=a.toLowerCase();return -1!==ALLOWED_QUERY_PARAMS_LOWER.indexOf(b)||hasAllowedPrefix(b)};// ---------------------------------------------------------------------------
|
|
575
|
+
// Pure helpers. No `this`, no globals, no side effects \u2014 callable and assertable
|
|
576
|
+
// on their own, which is where the interesting rules live.
|
|
577
|
+
// ---------------------------------------------------------------------------
|
|
578
|
+
// Pulls the allowlisted query params off a URL. Delegates to the SDK's own
|
|
579
|
+
// parser, which lowercases keys (so `?UTM_Source=` and `?utm_source=` land on one
|
|
580
|
+
// attribute), drops empty values, and carries the fallback for browsers without
|
|
581
|
+
// URLSearchParams. Tolerates an empty href, so SSR yields no params rather than
|
|
582
|
+
// throwing.
|
|
583
|
+
var allowedQueryParams=function(a){var b=queryStringParser(a,ALLOWED_QUERY_PARAMS),c=queryStringParser(a);return Object.keys(c).filter(function(a){return hasAllowedPrefix(a)&&c[a]}).forEach(function(a){b[a]=c[a];}),b};var AUTO_PAGE_VIEW_ATTRIBUTE="is_auto_page_view";// Absent rather than false on a manual page view, so the attribute is only ever
|
|
584
|
+
// added by the automatic emitters. Shared by both of them so the key and that
|
|
585
|
+
// rule have one definition instead of two that can drift.
|
|
586
|
+
var autoPageViewAttribute=function(a){var b;return a?(b={},b[AUTO_PAGE_VIEW_ATTRIBUTE]=!0,b):{}};// The captured params, in allowlist order, then prefix-matched names sorted.
|
|
587
|
+
// Neither depends on the object's insertion order, so reordering the query
|
|
588
|
+
// string cannot produce a different key.
|
|
589
|
+
//
|
|
590
|
+
// Membership is an own-property check, not `in`. `in` walks the prototype
|
|
591
|
+
// chain, so a name matching an Object.prototype member reports as present on
|
|
592
|
+
// any plain object. ALLOWED_QUERY_PARAMS contains no such name, which was the
|
|
593
|
+
// only thing making `in` safe here \u2014 and it stops being a safe assumption the
|
|
594
|
+
// moment this list can be extended from configuration.
|
|
595
|
+
var capturedNames=function(a){return ALLOWED_QUERY_PARAMS.filter(function(b){return hasOwnProp(a,b)}).concat(Object.keys(a).filter(hasAllowedPrefix).sort())};// The dedup key: pathname plus the allowlisted params in a fixed order, so that
|
|
596
|
+
// reordering the query string is not a new page. Params outside the allowlist
|
|
597
|
+
// never make it into `page.params` and so cannot key a view \u2014 nor can the hash.
|
|
598
|
+
//
|
|
599
|
+
// Values are re-encoded because queryStringParser hands them back DECODED. A
|
|
600
|
+
// value holding the pair delimiters would otherwise serialize exactly like two
|
|
601
|
+
// separate params \u2014 `{q: 'a&search=b'}` and `{q: 'a', search: 'b'}` both becoming
|
|
602
|
+
// `q=a&search=b` \u2014 and dedup would treat a real navigation between them as the
|
|
603
|
+
// same page and drop the view. `q`, `search` and `redirect_uri` carry `&` and `=`
|
|
604
|
+
// routinely, so this is reachable rather than theoretical.
|
|
605
|
+
var pageKey=function(a){var b=capturedNames(a.params).map(function(b){return "".concat(b,"=").concat(encodeURIComponent(a.params[b]))}).join("&");return b?"".concat(a.path,"?").concat(b):a.path};// Dedup keys on the pageKey above: a change to any captured param is a new page
|
|
606
|
+
// (`?page=2` is a distinct pagination view), while a hash-only change, or a
|
|
607
|
+
// change confined to params we do not capture, is the same page.
|
|
608
|
+
var isNewPage=function(a,b){return b!==a};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
609
|
+
// path and query params captured when the navigation was accepted rather than the
|
|
610
|
+
// live location.
|
|
611
|
+
var buildPageViewEvent=function(a){var b=a.params,c=a.hostname,d=a.title,e=a.path,f=a.isAutoPageView;return {messageType:MessageType$1.PageView,name:"PageView",// Params spread first, then the core fields by name, so a core field always
|
|
612
|
+
// wins. No allowlist entry collides with hostname/title/path today; naming
|
|
613
|
+
// them here is what keeps a later addition from silently overwriting one.
|
|
614
|
+
data:__assign(__assign(__assign({},b),{hostname:c,title:d,path:e}),autoPageViewAttribute(f)),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
615
|
+
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
616
|
+
// neither the tracker nor mp-instance touches `window` directly and
|
|
617
|
+
// `typeof window` is checked in exactly one place.
|
|
618
|
+
// ---------------------------------------------------------------------------
|
|
619
|
+
var apvWindow=function(){return "undefined"==typeof window?null:window},freshState=function(){return {initialPageViewFired:!1}},readState=function(){var a=apvWindow();return a?a[WIN_APV_KEY]:void 0},writeState=function(){var a=apvWindow();return a?(a[WIN_APV_KEY]||(a[WIN_APV_KEY]=freshState()),a[WIN_APV_KEY]):null};// Reads tolerate absent state, so a read never mutates `window`. Only the
|
|
620
|
+
// writers below create it.
|
|
621
|
+
var getActiveTracker=function(){var a=readState();return a?a.tracker:void 0};var hasInitialPageViewFired=function(){var a=readState();return !!(a&&a.initialPageViewFired)};var markInitialPageViewFired=function(){var a=writeState();a&&(a.initialPageViewFired=!0);};// Returns the page to its pre-APV state: stops the active tracker (restoring the
|
|
622
|
+
// history methods it patched), then swaps in fresh state. The state object is the
|
|
623
|
+
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
624
|
+
var resetPageViewTracking=function(){var a=apvWindow();if(a){var b=getActiveTracker();b&&b.teardown(),a[WIN_APV_KEY]=freshState();}};var setActiveTracker=function(a){var b=writeState();b&&(b.tracker=a);},clearActiveTracker=function(a){var b=readState();b&&b.tracker===a&&(b.tracker=void 0);},currentPage=function(){return {path:window.location.pathname,params:allowedQueryParams(getHref())}},describePage=function(a){if(!a)return "";var b=capturedNames(a.params);return b.length?"".concat(a.path," (params: ").concat(b.join(),")"):a.path},PageViewTracker=/** @class */function(){function a(a,b){this.lastPage=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.mpInstance=a,this.isAutoPageView=!!(b&&b.isAutoPageView);}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
625
|
+
// navigations. Flips to false on teardown, including the teardown a
|
|
626
|
+
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
627
|
+
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
628
|
+
get:function get(){return this.active},enumerable:!1,configurable:!0}),a.prototype.init=function(){var a=this;if(this.log("[init] PageViewTracker Init"),!supportsHistoryTracking(apvWindow()))return void this.log("[init] unsupported environment (no History API), not starting");// Take over from whichever tracker is currently active: one left behind by
|
|
629
|
+
// a previous module load, or this same tracker on a repeat
|
|
630
|
+
// mParticle.init(). Their pending navigations are transferred rather than
|
|
631
|
+
// dropped \u2014 a route change may have queued a deferred fire that has not
|
|
632
|
+
// flushed yet, and dropping it loses a page view entirely.
|
|
633
|
+
var b=getActiveTracker(),c=this.retire(b);this.active&&b!==this&&(c=c.concat(this.retire(this))),this.active=!0,this.lastPage=currentPage(),this.log("[init] seeded lastPage: ".concat(describePage(this.lastPage))),this.undoHistoryPatch=subscribeToRouteChange("pageView",function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),setActiveTracker(this),this.log("[init] patched pushState/replaceState + listening for popstate"),c.forEach(function(b){return a.scheduleFire(b)});},a.prototype.teardown=function(){this.takePendingNavigations(),this.undoHistoryPatch&&(this.undoHistoryPatch(),this.undoHistoryPatch=null),this.active=!1,clearActiveTracker(this);},a.prototype.retire=function(a){if(!a)return [];this.log(a===this?"[init] retiring this tracker for a repeat mParticle.init() \u2014 transferring pending navigations and tearing down":"[init] retiring a tracker from a previous module load \u2014 transferring pending navigations and tearing down");var b=a.takePendingNavigations();return a.teardown(),b},a.prototype.takePendingNavigations=function(){var a=this.pendingNavigations;return this.pendingNavigations=[],a.forEach(function(a){var b=a.timeoutId;return clearTimeout(b)}),a.map(function(a){var b=a.page;return b})},a.prototype.safeHandleNavigation=function(a){// An orphaned wrapper still calls in: teardown can only restore a history
|
|
634
|
+
// method that is still ours, so one a third party patched over stays
|
|
635
|
+
// installed and keeps firing at a dead tracker. Bail before touching
|
|
636
|
+
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
637
|
+
// rather than at each wrapper also covers the popstate path.
|
|
638
|
+
if(this.active)try{this.handleNavigation(a);}catch(b){this.log("[error] navigation handler threw (".concat(a,"), page view skipped: ").concat(b));}},a.prototype.handleNavigation=function(a){var b=currentPage(),c=this.lastPage?pageKey(this.lastPage):null;return this.log("[detect] navigation signal (source: ".concat(a,", candidate: ").concat(describePage(b),", last: ").concat(describePage(this.lastPage),")")),isNewPage(c,pageKey(b))?void(this.log("[accept] page changed, scheduling fire (source: ".concat(a,", from: ").concat(describePage(this.lastPage),", to: ").concat(describePage(b),")")),this.lastPage=b,this.scheduleFire(b)):void this.log("[dedupe] page unchanged, skipping (source: ".concat(a,", page: ").concat(describePage(b),")"))},a.prototype.scheduleFire=function(a){var b=this,c=setTimeout(function(){return b.pendingNavigations=b.pendingNavigations.filter(function(a){return a.timeoutId!==c}),b.active?void(b.mpInstance._SessionManager.resetSessionTimer(),b.firePageView(a)):void b.log("[defer] fire aborted, tracker inactive (torn down before flush)")},0);this.pendingNavigations.push({page:a,timeoutId:c});},a.prototype.firePageView=function(a){var b=window.document.title,c=buildPageViewEvent(__assign(__assign({},a),{hostname:window.location.hostname,title:b,isAutoPageView:this.isAutoPageView}));this.log("[fire] deferred flush -> _Events.logEvent(PageView) (page: ".concat(describePage(a),", title: ").concat(b,")")),this.mpInstance._Events.logEvent(c);},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle APV: ".concat(a));},a}();// Log-safe description of a page: the path, plus the NAMES of the captured
|
|
639
|
+
|
|
640
|
+
// `mParticle._cleanUrl`. `path` keeps scheme, host and path. `full` adds the
|
|
641
|
+
// query params an auto page view may capture, then the fragment.
|
|
642
|
+
var UrlMode={Path:"path",Full:"full"};// OAuth 2.0 / OIDC authorization-flow params. They stay off URLs even where the
|
|
643
|
+
// page view allowlist admits them, because a URL travels on every event.
|
|
644
|
+
var EXCLUDED_URL_QUERY_PARAMS=["client_id","redirect_uri","response_type","scope","state","code","nonce"];// An OAuth implicit or OIDC fragment response puts its tokens in `#k=v&...`.
|
|
645
|
+
var EXCLUDED_URL_FRAGMENT_PARAMS=EXCLUDED_URL_QUERY_PARAMS.concat(["access_token","id_token","refresh_token","provider_token","provider_refresh_token"]);// Allowlisted params whose value is itself a URL, so it can carry a query.
|
|
646
|
+
var URL_VALUED_QUERY_PARAMS=["ref","referrer"],USERINFO=/^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/]*@/i,decodeQueryComponent=function(a){return decodeURIComponent(a.replace(/\+/g," "))},cleanQueryPair=function(a){var b,c=a.indexOf("="),d=-1===c?a:a.slice(0,c);try{b=decodeQueryComponent(d);}catch(a){return null}var e=b.toLowerCase();if(!b||!isAllowedQueryParam(b)||-1!==EXCLUDED_URL_QUERY_PARAMS.indexOf(e))return null;if(-1===c||-1===URL_VALUED_QUERY_PARAMS.indexOf(e))return a;var f;try{f=decodeQueryComponent(a.slice(c+1));}catch(a){return null}var g=cleanUrl(f,UrlMode.Path);return g===f?a:"".concat(d,"=").concat(encodeURIComponent(g))},cleanQuery=function(a){return a.split("&").map(cleanQueryPair).filter(function(a){return null!==a}).join("&")},keepsFragmentPair=function(a){try{var b=decodeQueryComponent(a.split("=")[0]);return -1===EXCLUDED_URL_FRAGMENT_PARAMS.indexOf(b.toLowerCase())}catch(a){return !1}},cleanFragment=function(a){var b=a.indexOf("?"),c=-1===b?a:a.slice(0,b),d=/^#[/!]/.test(a)||-1!==b&&-1===c.indexOf("=");if(d&&-1!==b){var e=cleanQuery(a.slice(b+1));return c+(e?"?".concat(e):"")}if(-1===a.indexOf("="))return a;var f=a.slice(1).split("&").filter(keepsFragmentPair).join("&");return f?"#".concat(f):""};// A hash route (`#/...`, `#!...`, or a path with no `=` before its `?`) keeps
|
|
647
|
+
// its path; a query inside it gets the same allowlist as the URL's own query.
|
|
648
|
+
// A fragment of bare pairs loses the OAuth/OIDC ones.
|
|
649
|
+
// String-based rather than `new URL`, so kept pairs and the fragment go out
|
|
650
|
+
// exactly as the browser reported them and no environment can parse differently.
|
|
651
|
+
// An unknown mode is treated as `path`.
|
|
652
|
+
var cleanUrl=function(a,b){if("string"!=typeof a||!a)return "";var c=a.indexOf("#"),d=-1===c?"":a.slice(c),e=-1===c?a:a.slice(0,c),f=e.indexOf("?"),g=(-1===f?e:e.slice(0,f)).replace(USERINFO,"$1");if(b!==UrlMode.Full)return g;var h=-1===f?"":cleanQuery(e.slice(f+1));return g+(h?"?".concat(h):"")+cleanFragment(d)};// The current page as it may appear on an event.
|
|
653
|
+
var cleanPageHref=function(){return cleanUrl(getHref(),UrlMode.Full)};
|
|
654
|
+
|
|
517
655
|
// `Unavailable` covers storage being blocked/disabled (e.g. SecurityError),
|
|
518
656
|
// where retrying with a smaller payload cannot succeed.
|
|
519
657
|
var StorageResult;(function(a){a.Success="Success",a.QuotaExceeded="QuotaExceeded",a.Unavailable="Unavailable";})(StorageResult||(StorageResult={}));var isQuotaExceededError=function(a){return a instanceof DOMException&&(// Standard quota errors, plus Firefox's legacy name/code.
|
|
@@ -556,7 +694,7 @@ function appendUserInfo(a,b){if(b){if(!a)return b.MPID=null,b.ConsentState=null,
|
|
|
556
694
|
* Creates an instance of a BatchUploader
|
|
557
695
|
* @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance
|
|
558
696
|
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
559
|
-
*/function a(b,c){var d,e,f;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.uploadIntervalTimerId=null,this.exitHandler=null,this.visibilityChangeHandler=null,this.destroyed=!1,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable();// When noFunctional is true, prevent events/batches storage
|
|
697
|
+
*/function a(b,c){var d,e,f;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.uploadIntervalTimerId=null,this.exitHandler=null,this.visibilityChangeHandler=null,this.destroyed=!1,this.batchOrder=new Map,this.nextBatchOrder=0,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable();// When noFunctional is true, prevent events/batches storage
|
|
560
698
|
var g=null===(e=b._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional();this.offlineStorageEnabled&&!g&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events")),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches")),(d=this.eventsQueuedForProcessing).push.apply(d,null!==(f=this.eventVault.retrieve())&&void 0!==f?f:[]));var h=this.mpInstance._Store,i=h.SDKConfig,j=h.devToken,k=this.mpInstance._Helpers.createServiceUrl(i.v3SecureServiceUrl,j);this.uploadUrl="".concat(k,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}/**
|
|
561
699
|
* Cleans up timers and event listeners to prevent leaks when the SDK
|
|
562
700
|
* is re-initialized (e.g. between tests or on repeated init calls).
|
|
@@ -564,17 +702,20 @@ var g=null===(e=b._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional();
|
|
|
564
702
|
// TODO: Handle cases where Local Storage is unavailable
|
|
565
703
|
// Potentially shared between Vault and Persistence as well
|
|
566
704
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
567
|
-
return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a,b=Date.now(),c=this.mpInstance,d=c._Store,e=c.Identity,f=c._timeOnSiteTimer,g=c._Helpers,h=d.sessionId,i=d.deviceId,j=d.sessionStartDate,k=d.SDKConfig,l=g.generateUniqueId,m=g.getFeatureFlag,n=e.getCurrentUser,o={AppName:k.appName,AppVersion:k.appVersion,Package:k["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:b,SessionId:h,DeviceId:i,IsFirstRun:!1,SourceMessageId:l(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===j||void 0===j?void 0:j.getTime())||b,Debug:k.isDevelopmentMode,ActiveTimeOnSite:(null===f||void 0===f?void 0:f.getTimeInForeground())||0,TotalTimeOnSite:(null===(a=d.getTotalTimeOnSite)||void 0===a?void 0:a.call(d))||0,PageUrl:
|
|
705
|
+
return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a,b=Date.now(),c=this.mpInstance,d=c._Store,e=c.Identity,f=c._timeOnSiteTimer,g=c._Helpers,h=d.sessionId,i=d.deviceId,j=d.sessionStartDate,k=d.SDKConfig,l=g.generateUniqueId,m=g.getFeatureFlag,n=e.getCurrentUser,o={AppName:k.appName,AppVersion:k.appVersion,Package:k["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:b,SessionId:h,DeviceId:i,IsFirstRun:!1,SourceMessageId:l(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===j||void 0===j?void 0:j.getTime())||b,Debug:k.isDevelopmentMode,ActiveTimeOnSite:(null===f||void 0===f?void 0:f.getTimeInForeground())||0,TotalTimeOnSite:(null===(a=d.getTotalTimeOnSite)||void 0===a?void 0:a.call(d))||0,PageUrl:cleanPageHref()||null,IsBackgroundAST:!0},p=__assign({},o.CustomFlags),q=d.integrationAttributes;// https://go.mparticle.com/work/SQDSDKS-5053
|
|
568
706
|
if(isIntegrationCaptureEnabled(m)){this.mpInstance._IntegrationCapture.capture();var r=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();p=__assign(__assign({},r),p);var s=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();q=__assign(__assign({},s),q);}return o.CustomFlags=p,o.IntegrationAttributes=q,appendUserInfo(n(),o),o},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
|
|
569
707
|
var c=a.mpInstance._Helpers.getFeatureFlag,d=Constants.FeatureFlags.AstBackgroundEvents;if(c(d)){if(b.shouldDebounceAndUpdateLastASTTime())return;// Add application state transition event to queue
|
|
570
708
|
var e=b.createBackgroundASTEvent();b.queueEvent(e);}// Then trigger the upload with beacon
|
|
571
709
|
b.prepareAndUpload(!1,b.isBeaconAvailable());};this.exitHandler=c,this.visibilityChangeHandler=function(){"hidden"===document.visibilityState&&c();},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),this.uploadIntervalTimerId=setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){if(this.eventsQueuedForProcessing.push(a),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),this.mpInstance.Logger.isVerbose()){var b=obfuscateDevData(a,this.mpInstance._Store.SDKConfig.isDevelopmentMode);this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(b))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length));}this.shouldTriggerImmediateUpload(a.EventDataType)&&this.prepareAndUpload(!1,!1);}},a.prototype.shouldTriggerImmediateUpload=function(a){var b=[MessageType$1.Commerce,MessageType$1.UserIdentityChange];return !this.batchingEnabled||b.includes(a)},(a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
|
|
572
710
|
for(var d,e=[],f=new Map,g=0,h=a;g<h.length;g++){//on initial startup, there may be events logged without an mpid.
|
|
573
|
-
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){var d;return void 0===b&&(b=!1),void 0===c&&(c=!1),__awaiter(this,void 0,void 0,function(){var e,f,g,h,i,j,k,l;return __generator(this,function(
|
|
574
|
-
|
|
711
|
+
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){var d;return void 0===b&&(b=!1),void 0===c&&(c=!1),__awaiter(this,void 0,void 0,function(){var e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return e=this.mpInstance.Identity.getCurrentUser(),f=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),g=[],isEmpty(f)||(g=a.createNewBatches(f,e,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((k=this.batchesQueuedForProcessing).unshift.apply(k,null!==(d=this.batchVault.retrieve())&&void 0!==d?d:[]),this.batchVault.purge()),isEmpty(g)||(l=this.batchesQueuedForProcessing).push.apply(l,g),h=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],h.forEach(function(a){n.batchOrder.has(a.source_request_id)||n.batchOrder.set(a.source_request_id,n.nextBatchOrder++);}),[4/*yield*/,this.uploadBatches(h,c)];case 1:return i=o.sent(),j=(i||[]).map(function(a){return a.source_request_id}),h.forEach(function(a){-1===j.indexOf(a.source_request_id)&&n.batchOrder["delete"](a.source_request_id);}),isEmpty(i)||(m=this.batchesQueuedForProcessing).unshift.apply(m,i),!c&&this.offlineStorageEnabled&&this.batchVault&&this.storeBatchesQueuedForProcessing(),b&&!this.destroyed&&this.triggerUploadInterval(b,!1),[2/*return*/]}})})},a.prototype.storeBatchesQueuedForProcessing=function(){var a,b=this,c=function(a){var c;return null!==(c=b.batchOrder.get(a.source_request_id))&&void 0!==c?c:-1},d=__spreadArray(__spreadArray([],this.batchesQueuedForProcessing,!0),null!==(a=this.batchVault.retrieve())&&void 0!==a?a:[],!0).sort(function(d,a){var b,e;return c(d)-c(a)||(null!==(b=d.timestamp_unixtime_ms)&&void 0!==b?b:0)-(null!==(e=a.timestamp_unixtime_ms)&&void 0!==e?e:0)});// Another upload may have stored its failed batches while this one was
|
|
712
|
+
// in flight. Merge them in creation order, whichever upload finished
|
|
713
|
+
// first, so they are not overwritten and quota trimming drops the oldest.
|
|
714
|
+
// Nothing to persist: reset offline storage to an empty state.
|
|
715
|
+
if(isEmpty(d))return this.batchVault.store([]),void(this.batchesQueuedForProcessing=[]);// Drop oldest batches until storage accepts the payload. Only quota
|
|
575
716
|
// failures are recoverable by trimming; if storage is unavailable,
|
|
576
717
|
// dropping batches won't help, so retain them in memory.
|
|
577
|
-
for(var
|
|
718
|
+
for(var e,f=0;f<d.length;f++){if(e=this.batchVault.store(d.slice(f)),e===StorageResult.Success)return this.logDroppedOfflineBatches(f),void(this.batchesQueuedForProcessing=[]);if(e===StorageResult.Unavailable)return void this.mpInstance.Logger.warning("Offline batch storage is unavailable. Retaining batches in memory.")}// Every attempt stayed over quota, even down to the newest batch.
|
|
578
719
|
// Retain them in memory rather than dropping everything.
|
|
579
720
|
this.mpInstance.Logger.warning("Offline batch storage is over quota. Retaining batches in memory.");},a.prototype.logDroppedOfflineBatches=function(a){0<a&&this.mpInstance.Logger.warning("Offline batch storage is over quota. Dropped "+"".concat(a," oldest batch(es)."));},a.prototype.uploadBatches=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,j,k;return __generator(this,function(i){switch(i.label){case 0:if(d=b.filter(function(a){return !isEmpty(a.events)}),isEmpty(d))return [2/*return*/,null];this.mpInstance.Logger.isVerbose()&&(e=obfuscateDevData(d,this.mpInstance._Store.SDKConfig.isDevelopmentMode),this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(e))),this.mpInstance.Logger.verbose("Batch count: ".concat(d.length))),f=0,i.label=1;case 1:return f<d.length?(g={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(d[f])},!(c&&this.isBeaconAvailable()))?[3/*break*/,2]:(h=new Blob([g.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,h),[3/*break*/,5]):[3/*break*/,6];case 2:return i.trys.push([2,4,,5]),[4/*yield*/,this.uploader.upload(g)];case 3:if(j=i.sent(),200<=j.status&&300>j.status)this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(d[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
|
|
580
721
|
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," received")),[2/*return*/,d.slice(f,d.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
@@ -851,125 +992,6 @@ if(null===(c=a._CookieConsentManager)||void 0===c||!c.getNoFunctional()){var d,e
|
|
|
851
992
|
return new Date().getTime();var c=D.getPersistence();return c&&c[b]&&c[b].lst?c[b].lst:null},this.setLastSeenTime=function(b,c){if(b){c||(c=new Date().getTime());var d=D.getPersistence();d&&a._Helpers.isObject(d[b])&&(d[b].lst=c,D.savePersistence(d));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
852
993
|
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,D.update();},this.resetPersistence=function(){localStorage.clear(),D.expireCookies(StorageNames.cookieName),D.expireCookies(StorageNames.cookieNameV2),D.expireCookies(StorageNames.cookieNameV3),D.expireCookies(StorageNames.cookieNameV4),D.expireCookies(a._Store.storageName);var b=getMParticleManager();if(null===b||void 0===b?void 0:b._isTestEnv){localStorage.removeItem(a._Helpers.createMainStorageName("abcdef")),D.expireCookies(a._Helpers.createMainStorageName("abcdef"));}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]};}
|
|
853
994
|
|
|
854
|
-
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
855
|
-
// returns the single function that undoes it \u2014 or null when nothing was
|
|
856
|
-
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
857
|
-
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
858
|
-
// references out of the tracker entirely: there is no half-patched state for a
|
|
859
|
-
// caller to inspect, and no way to restore the wrong pair.
|
|
860
|
-
var patchHistory=function(a,b){if(window.history.pushState[WRAPPED_MARKER])return b("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED"),null;var c={},d={};HISTORY_METHODS.forEach(function(b){var e=window.history[b];c[b]=e;var f=function(){for(var c=[],d=0;d<arguments.length;d++)c[d]=arguments[d];var f=e.apply(this,c);return a(b),f};Object.defineProperty(f,WRAPPED_MARKER,{value:!0,enumerable:!1}),d[b]=f;});// Restore per method: a third party may have patched one of the two on top of
|
|
861
|
-
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
862
|
-
// leave anything that is no longer ours in place.
|
|
863
|
-
var e=function(){return HISTORY_METHODS.forEach(function(a){window.history[a]===d[a]?(window.history[a]=c[a],b("[teardown] restored original ".concat(a))):b("[teardown] ".concat(a," no longer ours; leaving in place, gating callback to no-op"));})};try{HISTORY_METHODS.forEach(function(a){window.history[a]=d[a];});}catch(a){b("[error] failed to patch history methods (frozen/sealed), rolling back: ".concat(a));try{e();}catch(a){b("[error] failed to restore history methods after patch failure: ".concat(a));}return null}return e};// One History patch for the whole SDK, so page-view tracking and preselection do not
|
|
864
|
-
// stack two wrappers.
|
|
865
|
-
//
|
|
866
|
-
// State lives on `window`, not module scope, because Next.js re-executes the bundle per
|
|
867
|
-
// SPA navigation while the patch from the previous execution stays installed.
|
|
868
|
-
var WIN_ROUTE_MONITOR_KEY="__mpRouteMonitor__";var monitorState=function(){var a=window;return a[WIN_ROUTE_MONITOR_KEY]||(a[WIN_ROUTE_MONITOR_KEY]={listeners:{},undoHistoryPatch:null,popStateListener:null}),a[WIN_ROUTE_MONITOR_KEY]},emit=function(a){Object.values(monitorState().listeners).forEach(function(b){try{b(a);}catch(a){// One subscriber must not stop the others, and must never break navigation.
|
|
869
|
-
}});},install=function(a,b){a.undoHistoryPatch||a.popStateListener||(a.undoHistoryPatch=patchHistory(emit,b),a.popStateListener=function(){return emit("popstate")},window.addEventListener("popstate",a.popStateListener));},uninstall=function(a){a.popStateListener&&(window.removeEventListener("popstate",a.popStateListener),a.popStateListener=null),a.undoHistoryPatch&&(a.undoHistoryPatch(),a.undoHistoryPatch=null);};// Reads the shared state at call time, so a wrapper installed by a previous bundle
|
|
870
|
-
// execution still reaches the current listeners.
|
|
871
|
-
// Installs on the first subscriber and tears down after the last leaves, so a workspace
|
|
872
|
-
// that needs neither is never patched. Unsubscribing only removes the listener while it
|
|
873
|
-
// still owns its key, so an outgoing instance cannot remove its replacement.
|
|
874
|
-
var subscribeToRouteChange=function(a,b,c){if(void 0===c&&(c=function(){}),!supportsHistoryTracking("undefined"==typeof window?null:window))return function(){};var d=monitorState();return d.listeners[a]=b,install(d,c),function(){d.listeners[a]!==b||(delete d.listeners[a],0===Object.keys(d.listeners).length&&uninstall(d));}};
|
|
875
|
-
|
|
876
|
-
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
877
|
-
// tracking is live.
|
|
878
|
-
//
|
|
879
|
-
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
880
|
-
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
881
|
-
// but `window` persists for the lifetime of the tab.
|
|
882
|
-
//
|
|
883
|
-
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
884
|
-
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
885
|
-
// survives the reset.
|
|
886
|
-
var WIN_APV_KEY="__mpApv__";// The query params an auto page view may carry. An allowlist, not a denylist:
|
|
887
|
-
// partner URLs routinely hold order ids, email addresses and session tokens, and
|
|
888
|
-
// none of those should reach the event stream because someone forgot to exclude
|
|
889
|
-
// them. Anything absent from this list is dropped.
|
|
890
|
-
//
|
|
891
|
-
// SECURITY: `code`, `state` and `nonce` are the OAuth 2.0 / OIDC authorization
|
|
892
|
-
// code and the CSRF/replay tokens. They are credentials until redeemed, and
|
|
893
|
-
// attaching them here persists them in the event store and forwards them to
|
|
894
|
-
// every configured kit. They are on the list by explicit product decision \u2014
|
|
895
|
-
// deleting that line is the whole of the fix if that decision is revisited.
|
|
896
|
-
var ALLOWED_QUERY_PARAMS=[// Campaign attribution
|
|
897
|
-
"utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id",// Ad-network click ids
|
|
898
|
-
"gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid",// OAuth / OIDC \u2014 see the SECURITY note above
|
|
899
|
-
"client_id","redirect_uri","response_type","scope","state","code","nonce",// Pagination
|
|
900
|
-
"page","limit","offset","cursor","per_page",// Site search term, as the common platforms spell it. Matching is
|
|
901
|
-
// case-insensitive; single-letter names other than `q` are too generic.
|
|
902
|
-
"q","search","query","keyword","keywords","term","text","searchTerm","searchText","search_query","search_text","Ntt",// Product and variant identifiers. `cid` is not a category: it is a
|
|
903
|
-
// customer id on many sites.
|
|
904
|
-
"pid","productId","sku","skuId","variant",// Category
|
|
905
|
-
"category",// Referral
|
|
906
|
-
"ref","referrer"];// ---------------------------------------------------------------------------
|
|
907
|
-
// Pure helpers. No `this`, no globals, no side effects \u2014 callable and assertable
|
|
908
|
-
// on their own, which is where the interesting rules live.
|
|
909
|
-
// ---------------------------------------------------------------------------
|
|
910
|
-
// Pulls the allowlisted query params off a URL. Delegates to the SDK's own
|
|
911
|
-
// parser, which lowercases keys (so `?UTM_Source=` and `?utm_source=` land on one
|
|
912
|
-
// attribute), drops empty values, and carries the fallback for browsers without
|
|
913
|
-
// URLSearchParams. Tolerates an empty href, so SSR yields no params rather than
|
|
914
|
-
// throwing.
|
|
915
|
-
var allowedQueryParams=function(a){return queryStringParser(a,ALLOWED_QUERY_PARAMS)};var AUTO_PAGE_VIEW_ATTRIBUTE="is_auto_page_view";// Absent rather than false on a manual page view, so the attribute is only ever
|
|
916
|
-
// added by the automatic emitters. Shared by both of them so the key and that
|
|
917
|
-
// rule have one definition instead of two that can drift.
|
|
918
|
-
var autoPageViewAttribute=function(a){var b;return a?(b={},b[AUTO_PAGE_VIEW_ATTRIBUTE]=!0,b):{}};// The captured params, in allowlist order. Ordering comes from the constant
|
|
919
|
-
// rather than a sort: it is deterministic without needing a comparator, and it
|
|
920
|
-
// does not depend on the object's insertion order, so reordering the query string
|
|
921
|
-
// cannot produce a different key.
|
|
922
|
-
//
|
|
923
|
-
// Membership is an own-property check, not `in`. `in` walks the prototype
|
|
924
|
-
// chain, so a name matching an Object.prototype member reports as present on
|
|
925
|
-
// any plain object. ALLOWED_QUERY_PARAMS contains no such name, which was the
|
|
926
|
-
// only thing making `in` safe here \u2014 and it stops being a safe assumption the
|
|
927
|
-
// moment this list can be extended from configuration.
|
|
928
|
-
var capturedNames=function(a){return ALLOWED_QUERY_PARAMS.filter(function(b){return hasOwnProp(a,b)})};// The dedup key: pathname plus the allowlisted params in a fixed order, so that
|
|
929
|
-
// reordering the query string is not a new page. Params outside the allowlist
|
|
930
|
-
// never make it into `page.params` and so cannot key a view \u2014 nor can the hash.
|
|
931
|
-
//
|
|
932
|
-
// Values are re-encoded because queryStringParser hands them back DECODED. A
|
|
933
|
-
// value holding the pair delimiters would otherwise serialize exactly like two
|
|
934
|
-
// separate params \u2014 `{q: 'a&search=b'}` and `{q: 'a', search: 'b'}` both becoming
|
|
935
|
-
// `q=a&search=b` \u2014 and dedup would treat a real navigation between them as the
|
|
936
|
-
// same page and drop the view. `q`, `search` and `redirect_uri` carry `&` and `=`
|
|
937
|
-
// routinely, so this is reachable rather than theoretical.
|
|
938
|
-
var pageKey=function(a){var b=capturedNames(a.params).map(function(b){return "".concat(b,"=").concat(encodeURIComponent(a.params[b]))}).join("&");return b?"".concat(a.path,"?").concat(b):a.path};// Dedup keys on the pageKey above: a change to any captured param is a new page
|
|
939
|
-
// (`?page=2` is a distinct pagination view), while a hash-only change, or a
|
|
940
|
-
// change confined to params we do not capture, is the same page.
|
|
941
|
-
var isNewPage=function(a,b){return b!==a};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
942
|
-
// path and query params captured when the navigation was accepted rather than the
|
|
943
|
-
// live location.
|
|
944
|
-
var buildPageViewEvent=function(a){var b=a.params,c=a.hostname,d=a.title,e=a.path,f=a.isAutoPageView;return {messageType:MessageType$1.PageView,name:"PageView",// Params spread first, then the core fields by name, so a core field always
|
|
945
|
-
// wins. No allowlist entry collides with hostname/title/path today; naming
|
|
946
|
-
// them here is what keeps a later addition from silently overwriting one.
|
|
947
|
-
data:__assign(__assign(__assign({},b),{hostname:c,title:d,path:e}),autoPageViewAttribute(f)),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
948
|
-
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
949
|
-
// neither the tracker nor mp-instance touches `window` directly and
|
|
950
|
-
// `typeof window` is checked in exactly one place.
|
|
951
|
-
// ---------------------------------------------------------------------------
|
|
952
|
-
var apvWindow=function(){return "undefined"==typeof window?null:window},freshState=function(){return {initialPageViewFired:!1}},readState=function(){var a=apvWindow();return a?a[WIN_APV_KEY]:void 0},writeState=function(){var a=apvWindow();return a?(a[WIN_APV_KEY]||(a[WIN_APV_KEY]=freshState()),a[WIN_APV_KEY]):null};// Reads tolerate absent state, so a read never mutates `window`. Only the
|
|
953
|
-
// writers below create it.
|
|
954
|
-
var getActiveTracker=function(){var a=readState();return a?a.tracker:void 0};var hasInitialPageViewFired=function(){var a=readState();return !!(a&&a.initialPageViewFired)};var markInitialPageViewFired=function(){var a=writeState();a&&(a.initialPageViewFired=!0);};// Returns the page to its pre-APV state: stops the active tracker (restoring the
|
|
955
|
-
// history methods it patched), then swaps in fresh state. The state object is the
|
|
956
|
-
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
957
|
-
var resetPageViewTracking=function(){var a=apvWindow();if(a){var b=getActiveTracker();b&&b.teardown(),a[WIN_APV_KEY]=freshState();}};var setActiveTracker=function(a){var b=writeState();b&&(b.tracker=a);},clearActiveTracker=function(a){var b=readState();b&&b.tracker===a&&(b.tracker=void 0);},currentPage=function(){return {path:window.location.pathname,params:allowedQueryParams(getHref())}},describePage=function(a){if(!a)return "";var b=capturedNames(a.params);return b.length?"".concat(a.path," (params: ").concat(b.join(),")"):a.path},PageViewTracker=/** @class */function(){function a(a,b){this.lastPage=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.mpInstance=a,this.isAutoPageView=!!(b&&b.isAutoPageView);}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
958
|
-
// navigations. Flips to false on teardown, including the teardown a
|
|
959
|
-
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
960
|
-
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
961
|
-
get:function get(){return this.active},enumerable:!1,configurable:!0}),a.prototype.init=function(){var a=this;if(this.log("[init] PageViewTracker Init"),!supportsHistoryTracking(apvWindow()))return void this.log("[init] unsupported environment (no History API), not starting");// Take over from whichever tracker is currently active: one left behind by
|
|
962
|
-
// a previous module load, or this same tracker on a repeat
|
|
963
|
-
// mParticle.init(). Their pending navigations are transferred rather than
|
|
964
|
-
// dropped \u2014 a route change may have queued a deferred fire that has not
|
|
965
|
-
// flushed yet, and dropping it loses a page view entirely.
|
|
966
|
-
var b=getActiveTracker(),c=this.retire(b);this.active&&b!==this&&(c=c.concat(this.retire(this))),this.active=!0,this.lastPage=currentPage(),this.log("[init] seeded lastPage: ".concat(describePage(this.lastPage))),this.undoHistoryPatch=subscribeToRouteChange("pageView",function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),setActiveTracker(this),this.log("[init] patched pushState/replaceState + listening for popstate"),c.forEach(function(b){return a.scheduleFire(b)});},a.prototype.teardown=function(){this.takePendingNavigations(),this.undoHistoryPatch&&(this.undoHistoryPatch(),this.undoHistoryPatch=null),this.active=!1,clearActiveTracker(this);},a.prototype.retire=function(a){if(!a)return [];this.log(a===this?"[init] retiring this tracker for a repeat mParticle.init() \u2014 transferring pending navigations and tearing down":"[init] retiring a tracker from a previous module load \u2014 transferring pending navigations and tearing down");var b=a.takePendingNavigations();return a.teardown(),b},a.prototype.takePendingNavigations=function(){var a=this.pendingNavigations;return this.pendingNavigations=[],a.forEach(function(a){var b=a.timeoutId;return clearTimeout(b)}),a.map(function(a){var b=a.page;return b})},a.prototype.safeHandleNavigation=function(a){// An orphaned wrapper still calls in: teardown can only restore a history
|
|
967
|
-
// method that is still ours, so one a third party patched over stays
|
|
968
|
-
// installed and keeps firing at a dead tracker. Bail before touching
|
|
969
|
-
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
970
|
-
// rather than at each wrapper also covers the popstate path.
|
|
971
|
-
if(this.active)try{this.handleNavigation(a);}catch(b){this.log("[error] navigation handler threw (".concat(a,"), page view skipped: ").concat(b));}},a.prototype.handleNavigation=function(a){var b=currentPage(),c=this.lastPage?pageKey(this.lastPage):null;return this.log("[detect] navigation signal (source: ".concat(a,", candidate: ").concat(describePage(b),", last: ").concat(describePage(this.lastPage),")")),isNewPage(c,pageKey(b))?void(this.log("[accept] page changed, scheduling fire (source: ".concat(a,", from: ").concat(describePage(this.lastPage),", to: ").concat(describePage(b),")")),this.lastPage=b,this.scheduleFire(b)):void this.log("[dedupe] page unchanged, skipping (source: ".concat(a,", page: ").concat(describePage(b),")"))},a.prototype.scheduleFire=function(a){var b=this,c=setTimeout(function(){return b.pendingNavigations=b.pendingNavigations.filter(function(a){return a.timeoutId!==c}),b.active?void(b.mpInstance._SessionManager.resetSessionTimer(),b.firePageView(a)):void b.log("[defer] fire aborted, tracker inactive (torn down before flush)")},0);this.pendingNavigations.push({page:a,timeoutId:c});},a.prototype.firePageView=function(a){var b=window.document.title,c=buildPageViewEvent(__assign(__assign({},a),{hostname:window.location.hostname,title:b,isAutoPageView:this.isAutoPageView}));this.log("[fire] deferred flush -> _Events.logEvent(PageView) (page: ".concat(describePage(a),", title: ").concat(b,")")),this.mpInstance._Events.logEvent(c);},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle APV: ".concat(a));},a}();// Log-safe description of a page: the path, plus the NAMES of the captured
|
|
972
|
-
|
|
973
995
|
var Messages$3=Constants.Messages;function Events(a){var b=this;// The auto page view for the landing page. The SPA navigations that follow it
|
|
974
996
|
// come from PageViewTracker instead, so both emitters attach the same
|
|
975
997
|
// allowlisted query params \u2014 and this is the one that matters for campaign
|
|
@@ -1042,8 +1064,8 @@ if(a._Store.sessionId||b.messageType===Types.MessageType.OptOut||a._Store.webvie
|
|
|
1042
1064
|
if(isIntegrationCaptureEnabled(l)){a._IntegrationCapture.capture();var m=a._IntegrationCapture.getClickIdsAsCustomFlags();j=__assign(__assign({},m),j);var n=a._IntegrationCapture.getClickIdsAsIntegrationAttributes();k=__assign(__assign({},n),k);}h=b.hasOwnProperty("toEventAPIObject")?b.toEventAPIObject():{// This is an artifact from v2 events where SessionStart/End and AST event
|
|
1043
1065
|
// names are numbers (1, 2, or 10), but going forward with v3, these lifecycle
|
|
1044
1066
|
// events do not have names, but are denoted by their `event_type`
|
|
1045
|
-
EventName:b.name||b.messageType+"",EventCategory:b.eventType,EventAttributes:a._Helpers.sanitizeAttributes(b.data,b.name),ActiveTimeOnSite:null===(d=a._timeOnSiteTimer)||void 0===d?void 0:d.getTimeInForeground(),TotalTimeOnSite:null===(f=(e=a._Store).getTotalTimeOnSite)||void 0===f?void 0:f.call(e),PageUrl:
|
|
1046
|
-
Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store.sessionId,SessionStartDate:a._Store.sessionStartDate?a._Store.sessionStartDate.getTime():0,Debug:a._Store.SDKConfig.isDevelopmentMode,Location:a._Store.currentPosition,OptOut:i,ExpandedEventCount:0,AppVersion:a.getAppVersion(),AppName:a.getAppName(),Package:a._Store.SDKConfig["package"],ClientGeneratedId:a._Store.clientId,DeviceId:a._Store.deviceId,IntegrationAttributes:k,CurrencyCode:a._Store.currencyCode,DataPlan:a._Store.SDKConfig.dataPlan?a._Store.SDKConfig.dataPlan:{}},h.EventDataType===MessageType.AppStateTransition&&(h.IsFirstRun=a._Store.isFirstRun,h.LaunchReferral=
|
|
1067
|
+
EventName:b.name||b.messageType+"",EventCategory:b.eventType,EventAttributes:a._Helpers.sanitizeAttributes(b.data,b.name),ActiveTimeOnSite:null===(d=a._timeOnSiteTimer)||void 0===d?void 0:d.getTimeInForeground(),TotalTimeOnSite:null===(f=(e=a._Store).getTotalTimeOnSite)||void 0===f?void 0:f.call(e),PageUrl:cleanPageHref()||null,SourceMessageId:b.sourceMessageId||a._Helpers.generateUniqueId(),EventDataType:b.messageType,CustomFlags:j,UserAttributeChanges:b.userAttributeChanges,UserIdentityChanges:b.userIdentityChanges},b.messageType!==Types.MessageType.SessionEnd&&(a._Store.dateLastEventSent=new Date),g={// FIXME: Deprecate when we get rid of V2
|
|
1068
|
+
Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store.sessionId,SessionStartDate:a._Store.sessionStartDate?a._Store.sessionStartDate.getTime():0,Debug:a._Store.SDKConfig.isDevelopmentMode,Location:a._Store.currentPosition,OptOut:i,ExpandedEventCount:0,AppVersion:a.getAppVersion(),AppName:a.getAppName(),Package:a._Store.SDKConfig["package"],ClientGeneratedId:a._Store.clientId,DeviceId:a._Store.deviceId,IntegrationAttributes:k,CurrencyCode:a._Store.currencyCode,DataPlan:a._Store.SDKConfig.dataPlan?a._Store.SDKConfig.dataPlan:{}},h.EventDataType===MessageType.AppStateTransition&&(h.IsFirstRun=a._Store.isFirstRun,h.LaunchReferral=cleanPageHref()||null),h.CurrencyCode=a._Store.currencyCode;var o=c||a.Identity.getCurrentUser();return appendUserInfo(o,h),b.messageType===Types.MessageType.SessionEnd&&(h.SessionLength=a._Store.dateLastEventSent.getTime()-a._Store.sessionStartDate.getTime(),h.currentSessionMPIDs=a._Store.currentSessionMPIDs,h.EventAttributes=a._Store.sessionAttributes,a._Store.currentSessionMPIDs=[],a._Store.sessionStartDate=null),g.Timestamp=a._Store.dateLastEventSent.getTime(),extend({},h,g)}return null},this.convertEventToV2DTO=function(c){var d={n:c.EventName,et:c.EventCategory,ua:c.UserAttributes,ui:c.UserIdentities,ia:c.IntegrationAttributes,str:c.Store,attrs:c.EventAttributes,sdk:c.SDKVersion,sid:c.SessionId,sl:c.SessionLength,ssd:c.SessionStartDate,dt:c.EventDataType,dbg:c.Debug,ct:c.Timestamp,lc:c.Location,o:c.OptOut,eec:c.ExpandedEventCount,av:c.AppVersion,cgid:c.ClientGeneratedId,das:c.DeviceId,mpid:c.MPID,smpids:c.currentSessionMPIDs};c.DataPlan&&c.DataPlan.PlanId&&(d.dp_id=c.DataPlan.PlanId,c.DataPlan.PlanVersion&&(d.dp_v=c.DataPlan.PlanVersion));var e=b.convertToConsentStateV2DTO(c.ConsentState);return e&&(d.con=e),c.EventDataType===MessageType.AppStateTransition&&(d.fr=c.IsFirstRun,d.iu=!1,d.at=ApplicationTransitionType.AppInit,d.lr=c.LaunchReferral,d.attrs=null),c.CustomFlags&&convertCustomFlags(c,d),c.EventDataType===MessageType.Commerce?(d.cu=c.CurrencyCode,c.ProductAction?d.pd={an:c.ProductAction.ProductActionType,cs:a._Helpers.parseNumber(c.ProductAction.CheckoutStep),co:c.ProductAction.CheckoutOptions,pl:convertProductListToV2DTO(c.ProductAction.ProductList),ti:c.ProductAction.TransactionId,ta:c.ProductAction.Affiliation,tcc:c.ProductAction.CouponCode,tr:a._Helpers.parseNumber(c.ProductAction.TotalAmount),ts:a._Helpers.parseNumber(c.ProductAction.ShippingAmount),tt:a._Helpers.parseNumber(c.ProductAction.TaxAmount)}:c.PromotionAction?d.pm={an:c.PromotionAction.PromotionActionType,pl:c.PromotionAction.PromotionList.map(function(a){return {id:a.Id,nm:a.Name,cr:a.Creative,ps:a.Position?a.Position:0}})}:c.ProductImpressions&&(d.pi=c.ProductImpressions.map(function(a){return {pil:a.ProductImpressionList,pl:convertProductListToV2DTO(a.ProductList)}}))):c.EventDataType===MessageType.Profile&&(d.pet=c.ProfileMessageType),d};}
|
|
1047
1069
|
|
|
1048
1070
|
function forwardingStatsUploader(a){function b(){var b=a._Forwarders.getForwarderStatsQueue(),c=a._Persistence.forwardingStatsBatches.uploadsTable,d=Date.now();for(var e in b.length&&(c[d]={uploading:!1,data:b},a._Forwarders.setForwarderStatsQueue([])),c)(function(b){if(c.hasOwnProperty(b)&&!1===c[b].uploading){var d=function(){4===e.readyState&&(200===e.status||202===e.status?(a.Logger.verbose("Successfully sent "+e.statusText+" from server"),delete c[b]):"4"===e.status.toString()[0]?429!==e.status&&delete c[b]:c[b].uploading=!1);},e=a._Helpers.createXHR(d),f=c[b].data;c[b].uploading=!0,a._APIClient.sendBatchForwardingStatsToServer(f,e);}})(e);}this.startForwardingStatsTimer=function(){window.mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
1049
1071
|
|
|
@@ -1325,17 +1347,17 @@ var PASSBACK_CONVERSION_TRACKING_ID="passbackconversiontrackingid",CHECKOUT_INTE
|
|
|
1325
1347
|
// it while a second named instance keeps its own.
|
|
1326
1348
|
function a(a){this.instanceName=a,this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1,this.isShoppableAdsLoaded=!1,this.stopRouteChangeWatch=null,this.pendingCheckoutIntents=[];}/**
|
|
1327
1349
|
* Sets a callback to be invoked when RoktManager becomes ready
|
|
1328
|
-
*/return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g,h,i,j){var
|
|
1350
|
+
*/return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g,h,i,j,k){var l,m,n=a||{},o=n.userAttributeFilters,p=n.settings,q=p||{},r=q.placementAttributesMapping,s=q.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(l=null===s||void 0===s?void 0:s.toLowerCase())&&void 0!==l?l:null,this.identityService=c,this.store=d,this.logger=e,this.errorReporter=h,this.loggingService=i,this.captureTiming=g,this.integrationCapture=j,this.createFilteredUser=k,null===(m=this.captureTiming)||void 0===m?void 0:m.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:o,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(r);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
|
|
1329
1351
|
// It is set here and passed in to the createLauncher method in the Rokt Kit
|
|
1330
1352
|
// This is not to be confused for the `sandbox` flag in the selectPlacements attributes
|
|
1331
1353
|
// as that is independent of this setting, though they share the same name.
|
|
1332
|
-
var
|
|
1354
|
+
var t=(null===f||void 0===f?void 0:f.sandbox)||!1,u=normalizeRoktLauncherOptions(null===f||void 0===f?void 0:f.launcherOptions);// Launcher options are set here for the kit to pick up and pass through
|
|
1333
1355
|
// to the Rokt Launcher.
|
|
1334
|
-
this.launcherOptions=__assign({sandbox:
|
|
1356
|
+
this.launcherOptions=__assign({sandbox:t},u),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,this.watchRouteChanges(),this.flushCheckoutIntents(),(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.watchRouteChanges=function(){var a,b,c,d=this;return isFunction(null===(a=this.kit)||void 0===a?void 0:a.onRouteChange)?void(// A full navigation or a re-init lands on the trigger route without a route change
|
|
1335
1357
|
// of its own.
|
|
1336
|
-
this.isAutoLogPageViewEnabled()?(null===(c=this.stopRouteChangeWatch)||void 0===c?void 0:c.call(this),this.stopRouteChangeWatch=null):!this.stopRouteChangeWatch&&(this.stopRouteChangeWatch=subscribeToRouteChange("rokt:".concat(this.instanceName),function(){return d.notifyRouteChange()})),this.notifyRouteChange()):(null===(b=this.stopRouteChangeWatch)||void 0===b?void 0:b.call(this),void(this.stopRouteChangeWatch=null))},a.prototype.notifyRouteChange=function(){var a,b,c;try{null===(b=null===(a=this.kit)||void 0===a?void 0:a.onRouteChange)||void 0===b?void 0:b.call(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onRouteChange: ".concat(getErrorMessage(a)));}},a.prototype.isCheckoutIntentSuppressed=function(){var a,b,c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags;if(!c||!0!==c[Constants.FeatureFlags.AutoButtonTracking]||!this.store.isEnabled)return !0;var d=this.launcherOptions||{};if(d.noFunctional||d.noTargeting||d.doNotShareOrSell)return !0;var e="undefined"==typeof navigator?void 0:navigator;return !!e&&!0===e.globalPrivacyControl},a.prototype.notifyCheckoutIntent=function(a,b){var c;if(void 0===b&&(b=window.location.pathname),!this.isCheckoutIntentSuppressed()){var d=this.kit;if(!d)return void(this.pendingCheckoutIntents=this.pendingCheckoutIntents.filter(function(b){return b.signal.kind!==a.kind}).concat({signal:a,pathname:b}).slice(-CHECKOUT_INTENT_BUFFER_LIMIT));try{isFunction(d.onCheckoutIntent)&&d.onCheckoutIntent(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onCheckoutIntent: ".concat(getErrorMessage(a)));}}},a.prototype.discardCheckoutIntents=function(){this.pendingCheckoutIntents=[];},a.prototype.flushCheckoutIntents=function(){var a=this,b=this.pendingCheckoutIntents;this.pendingCheckoutIntents=[];var c=Date.now(),d=window.location.pathname;b.filter(function(a){var b=a.signal,e=a.pathname;return c-b.t<CHECKOUT_INTENT_MAX_AGE_MS&&e===d}).sort(function(c,a){return c.signal.t-a.signal.t}).forEach(function(b){var c=b.signal;return a.notifyCheckoutIntent(c)});},a.prototype.isAutoLogPageViewEnabled=function(){var a,b,c;return !0===(null===(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags)||void 0===c?void 0:c[Constants.FeatureFlags.AutoLogPageView])},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q;return __awaiter(this,void 0,void 0,function(){var
|
|
1337
|
-
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];try{if(
|
|
1338
|
-
try{this.identityService.identify({userIdentities:__assign(__assign({},
|
|
1358
|
+
this.isAutoLogPageViewEnabled()?(null===(c=this.stopRouteChangeWatch)||void 0===c?void 0:c.call(this),this.stopRouteChangeWatch=null):!this.stopRouteChangeWatch&&(this.stopRouteChangeWatch=subscribeToRouteChange("rokt:".concat(this.instanceName),function(){return d.notifyRouteChange()})),this.notifyRouteChange()):(null===(b=this.stopRouteChangeWatch)||void 0===b?void 0:b.call(this),void(this.stopRouteChangeWatch=null))},a.prototype.notifyRouteChange=function(){var a,b,c;try{null===(b=null===(a=this.kit)||void 0===a?void 0:a.onRouteChange)||void 0===b?void 0:b.call(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onRouteChange: ".concat(getErrorMessage(a)));}},a.prototype.isCheckoutIntentSuppressed=function(){var a,b,c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags;if(!c||!0!==c[Constants.FeatureFlags.AutoButtonTracking]||!this.store.isEnabled)return !0;var d=this.launcherOptions||{};if(d.noFunctional||d.noTargeting||d.doNotShareOrSell)return !0;var e="undefined"==typeof navigator?void 0:navigator;return !!e&&!0===e.globalPrivacyControl},a.prototype.isCheckoutIntentLive=function(){return !this.isCheckoutIntentSuppressed()&&"undefined"!=typeof Event&&isFunction(Event.prototype.composedPath)},a.prototype.notifyCheckoutIntent=function(a,b){var c;if(void 0===b&&(b=window.location.pathname),!this.isCheckoutIntentSuppressed()){var d=this.kit;if(!d)return void(this.pendingCheckoutIntents=this.pendingCheckoutIntents.filter(function(b){return b.signal.kind!==a.kind}).concat({signal:a,pathname:b}).slice(-CHECKOUT_INTENT_BUFFER_LIMIT));try{isFunction(d.onCheckoutIntent)&&d.onCheckoutIntent(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onCheckoutIntent: ".concat(getErrorMessage(a)));}}},a.prototype.discardCheckoutIntents=function(){this.pendingCheckoutIntents=[];},a.prototype.flushCheckoutIntents=function(){var a=this,b=this.pendingCheckoutIntents;this.pendingCheckoutIntents=[];var c=Date.now(),d=window.location.pathname;b.filter(function(a){var b=a.signal,e=a.pathname;return c-b.t<CHECKOUT_INTENT_MAX_AGE_MS&&e===d}).sort(function(c,a){return c.signal.t-a.signal.t}).forEach(function(b){var c=b.signal;return a.notifyCheckoutIntent(c)});},a.prototype.isAutoLogPageViewEnabled=function(){var a,b,c;return !0===(null===(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags)||void 0===c?void 0:c[Constants.FeatureFlags.AutoLogPageView])},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return __awaiter(this,void 0,void 0,function(){var s,t,u,v,w,x,y,z,A,B,C,D,E,F,F,G,H,I,J,K,L,M,N,O,P,Q=this;return __generator(this,function(){// Queue if kit isn't ready OR if identity is in flight
|
|
1359
|
+
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];try{if(s=a.attributes,t=(null===s||void 0===s?void 0:s.sandbox)||null,u=this.mapPlacementAttributes(s,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(v=obfuscateDevData(s,null===(f=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode),this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(v,null,2)))),this.currentUser=this.identityService.getCurrentUser(),w=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},x=w.email,y=u.email,z=void 0,A=void 0,B=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),B&&(z=w[this.mappedEmailShaIdentityType],A=u.emailsha256||u[this.mappedEmailShaIdentityType]||void 0),C=this.hasIdentityChanged(x,y),D=this.hasIdentityChanged(z,A),E={},C&&(E.email=y,y&&(F="Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(i=this.errorReporter)||void 0===i?void 0:i.report({message:F,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING}))),D&&(E[this.mappedEmailShaIdentityType]=A,F="emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(j=this.errorReporter)||void 0===j?void 0:j.report({message:F,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING})),G=this.toUserAttributes(u),isEmpty(E))this.setUserAttributes(this.currentUser,G);else// Fire-and-forget identify \u2014 best-effort, does not block selectPlacements
|
|
1360
|
+
try{this.identityService.identify({userIdentities:__assign(__assign({},w),E)},function(a){var b,c=+(null===a||void 0===a?void 0:a.httpCode);c&&(400<=c||0>c)&&Q.logger.error("Background identify failed with HTTP "+c),Q.setUserAttributes(null===(b=null===a||void 0===a?void 0:a.getUser)||void 0===b?void 0:b.call(a),G,E),Q.processMessageQueue();});}catch(a){this.logger.error("Background identify threw an error: "+getErrorMessage(a)),this.setUserAttributes(this.identityService.getCurrentUser(),G,E);}return H=this.currentUser&&this.createFilteredUser?this.createFilteredUser(this.currentUser.getMPID()):null,I=(null===(k=null===H||void 0===H?void 0:H.getUserIdentities())||void 0===k?void 0:k.userIdentities)||{},J=null===(m=null===(l=this.store)||void 0===l?void 0:l.getTimeOnSite)||void 0===m?void 0:m.call(l),K=null===(o=null===(n=this.store)||void 0===n?void 0:n.getTotalTimeOnSite)||void 0===o?void 0:o.call(n),L=__assign(__assign(__assign(__assign({},u),null===t?{}:{sandbox:t}),J?{active_time_on_site_ms:J}:{}),K?{total_time_on_site_ms:K}:{}),L.email||(I.email?L.email=I.email:w.email&&this.logFilteredIdentity("email")),!B||L.emailsha256||L[this.mappedEmailShaIdentityType]||(M=I[this.mappedEmailShaIdentityType],M?L.emailsha256=M:w[this.mappedEmailShaIdentityType]&&this.logFilteredIdentity(this.mappedEmailShaIdentityType)),L[PASSBACK_CONVERSION_TRACKING_ID]||(null===(p=this.integrationCapture)||void 0===p?void 0:p.capture(),N=null===(q=this.integrationCapture)||void 0===q?void 0:q.getClickIdsAsIntegrationAttributes(),O=null===(r=null===N||void 0===N?void 0:N[PARTNER_MODULE_IDS.Rokt])||void 0===r?void 0:r[PASSBACK_CONVERSION_TRACKING_ID],O&&(L[PASSBACK_CONVERSION_TRACKING_ID]=O)),this.filters.filteredUser=H||this.filters.filteredUser||null,P=__assign(__assign({},a),{attributes:L}),[2/*return*/,this.kit.selectPlacements(P)]}catch(a){return [2/*return*/,Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))]}return [2/*return*/]})})},a.prototype.logFilteredIdentity=function(a){var b;null===(b=this.logger)||void 0===b?void 0:b.verbose("mParticle.Rokt selectPlacements did not add the ".concat(a," user identity to the attributes because the Rokt connection does not allow it"));},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m=this;return __generator(this,function(n){switch(n.label){case 0:return (n.trys.push([0,2,,3]),!a||"object"!==_typeof(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(m,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=n.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=n.sent(),this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(getErrorMessage(l))),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){throw new Error("Error setting extension data: "+getErrorMessage(a))}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.terminate=function(){var a,b,c;return __awaiter(this,void 0,void 0,function(){var d;return __generator(this,function(e){switch(e.label){case 0:if(!this.isReady())return null===(a=this.logger)||void 0===a?void 0:a.verbose("mParticle.Rokt.terminate called before the Rokt kit was ready. Nothing to terminate."),[2/*return*/];if(!isFunction(this.kit.terminate))return null===(b=this.logger)||void 0===b?void 0:b.error("mParticle.Rokt.terminate is not supported by the attached Rokt Kit version."),[2/*return*/];e.label=1;case 1:return e.trys.push([1,3,,4]),[4/*yield*/,this.kit.terminate()];case 2:return e.sent(),[3/*break*/,4];case 3:return d=e.sent(),null===(c=this.logger)||void 0===c?void 0:c.error("Failed to terminate the Rokt launcher: ".concat(getErrorMessage(d))),[3/*break*/,4];case 4:return [2/*return*/]}})})},a.prototype.onShoppableAdsReady=function(a){if(!this.kit||!this.isShoppableAdsLoaded)return void this.deferredCall("onShoppableAdsReady",a);try{this.kit.onShoppableAdsReady(a);}catch(a){this.logger.error("Failed to register onShoppableAdsReady callback: ".concat(getErrorMessage(a)));}},a.prototype.flushOnShoppableAdsReadyMessageQueue=function(a){var b=this;this.kit=a,this.messageQueue.forEach(function(c,d){var f;if(c.methodName===ON_SHOPPABLE_ADS_READY_METHOD){try{a.onShoppableAdsReady(c.payload);}catch(a){null===(f=b.logger)||void 0===f?void 0:f.error("RoktManager: Error flushing onShoppableAdsReady: "+a);}b.messageQueue["delete"](d);}}),this.isShoppableAdsLoaded=!0;},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c;return __generator(this,function(d){switch(d.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];d.label=1;case 1:return d.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,d.sent()];case 3:return c=d.sent(),this.logger.error("Failed to hashSha256, returning undefined: ".concat(getErrorMessage(c))),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
|
|
1339
1361
|
return !!(this.kit&&this.kit.launcher)},a.prototype.toUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}return c},a.prototype.setUserAttributes=function(a,b,c){if(void 0===c&&(c={}),!a)return void this.logger.warning("selectPlacements attributes were not set because there is no user to set them on.");try{if(this.hasContradictingIdentity(a,c))return void this.logger.warning("selectPlacements attributes were not set because identify did not resolve to a user with the passed email or hashed email.");a.setUserAttributes(b);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.hasContradictingIdentity=function(a,b){return Object.keys(b).some(function(c){var d,e,f=null===(e=null===(d=a.getUserIdentities())||void 0===d?void 0:d.userIdentities)||void 0===e?void 0:e[c];return !!f&&f!==b[c]})},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
|
|
1340
1362
|
this.messageQueue.clear(),c.forEach(function(a){var c,d,e,f;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));if(null===(d=b.logger)||void 0===d?void 0:d.isVerbose()){var g=obfuscateDevData(a.payload,null===(f=null===(e=b.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode);b.logger.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(g)));}// Capture resolve/reject functions before async processing
|
|
1341
1363
|
var h=a.resolve,i=a.reject,j=function(c){var d;null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(getErrorMessage(c))),i&&i(c);};try{var k=b[a.methodName](a.payload);// Handle both sync and async methods
|
|
@@ -1364,17 +1386,33 @@ var BUTTON_CLICK_EVENT_NAME="Auto Button Click";// One custom event per click, l
|
|
|
1364
1386
|
// page fields that auto page views carry. No intent: classifying clicks is left
|
|
1365
1387
|
// to whoever reads the data.
|
|
1366
1388
|
var buildButtonClickEvent=function(a,b){// Optional fields are left out when the button has no safe value for them.
|
|
1367
|
-
for(var c,d,e=(c={label_source:a.labelSource,element:a.element,type:a.type,path:b,hostname:window.location.hostname},c[AUTO_BUTTON_ATTRIBUTE]=!0,c),f={label:a.label,aria_label:a.ariaLabel,icon:a.icon,element_id:a.elementId,element_name:a.elementName,test_id:a.testId,controls:a.controls,form:a.form,link_type:a.linkType,link_domain:a.linkDomain,file_extension:a.fileExtension},g=0,h=Object.keys(f);g<h.length;g++)d=h[g],f[d]&&(e[d]=f[d]);return {messageType:MessageType$1.PageEvent,name:BUTTON_CLICK_EVENT_NAME,data:e,eventType:EventType.Other}};
|
|
1389
|
+
for(var c,d,e=(c={label_source:a.labelSource,element:a.element,type:a.type,path:b,hostname:window.location.hostname},c[AUTO_BUTTON_ATTRIBUTE]=!0,c),f={label:a.label,aria_label:a.ariaLabel,icon:a.icon,element_id:a.elementId,element_name:a.elementName,test_id:a.testId,controls:a.controls,form:a.form,link_type:a.linkType,link_domain:a.linkDomain,file_extension:a.fileExtension},g=0,h=Object.keys(f);g<h.length;g++)d=h[g],f[d]&&(e[d]=f[d]);return void 0!==a.checked&&(e.checked=a.checked),{messageType:MessageType$1.PageEvent,name:BUTTON_CLICK_EVENT_NAME,data:e,eventType:EventType.Other}};
|
|
1368
1390
|
|
|
1369
1391
|
// descriptions. Rokt's own elements, disabled controls and anything under
|
|
1370
1392
|
// data-mp-no-track are never returned.
|
|
1371
1393
|
var CONTROL_SELECTOR="button, input[type=\"submit\"], input[type=\"button\"], input[type=\"image\"], [role=\"button\"]";// closest() over the composed tree: slots, parents, then shadow hosts.
|
|
1372
|
-
function hasComposedAncestor(a,b){for(var c=a;c;){if(c.matches(b))return !0;var d=isFunction(c.getRootNode)?c.getRootNode():null;c=c.assignedSlot||c.parentElement||d&&d.host||null;}return !1}
|
|
1373
|
-
function
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1394
|
+
function hasComposedAncestor(a,b){for(var c=a;c;){if(c.matches(b))return !0;var d=isFunction(c.getRootNode)?c.getRootNode():null;c=c.assignedSlot||c.parentElement||d&&d.host||null;}return !1}var ROKT_SELECTOR="[data-core-type], #rokt-controller-frame";// A Rokt frame or script is served from a /wsdk/ path.
|
|
1395
|
+
function hasRoktSrc(a){var b=a.getAttribute("src");if(!b)return !1;try{return -1!==new URL(b,"https://example.test").pathname.indexOf("/wsdk/")}catch(a){// An unparseable src is not a Rokt element.
|
|
1396
|
+
return !1}}// Rokt's own placements and frames never count as partner checkout controls.
|
|
1397
|
+
function isRoktElement(a){return hasComposedAncestor(a,ROKT_SELECTOR)||hasRoktSrc(a)}// Wallet and quick-pay buttons as their vendors render them: official custom
|
|
1398
|
+
// elements and documented classes, ids and attributes.
|
|
1399
|
+
var CARD_FORM_BUTTON="paypal-basic-card-button",VENDOR_BUTTON="apple-pay-button, .apple-pay-button, .gpay-button, .gpay-card-info-container, #gpay-button-online-api-id, paypal-button, venmo-button, paypal-pay-later-button, paypal-credit-button, shop-pay-button, shop-pay-wallet-button, shopify-accelerated-checkout, shopify-accelerated-checkout-cart, shopify-apple-pay-button, shopify-google-pay-button, shopify-paypal-button, shopify-amazon-pay-button, .amazonpay-button-focusable, #AmazonPayButton, [data-amazon-pay-button], [data-afterpay-entry-point], "+CARD_FORM_BUTTON,NOT_A_PAYMENT=["set-up","add-money","reload","top-up"].map(function(a){return "apple-pay-button[type=\""+a+"\"]"}).join(", ");// PayPal's card button opens a card form, so it is a step rather than a wallet.
|
|
1400
|
+
// Apple's set-up and top-up buttons manage a wallet rather than pay with it.
|
|
1401
|
+
// What a vendor's own button markup says about a control. Only the control or
|
|
1402
|
+
// the shadow host that owns it counts, so a merchant wrapper reusing a vendor
|
|
1403
|
+
// class never turns its children into wallet buttons.
|
|
1404
|
+
function vendorButtonKind(a){var b=a.matches(VENDOR_BUTTON)?a:null;if(!b){var c=isFunction(a.getRootNode)?a.getRootNode():null;b=c&&c.host&&c.host.matches(VENDOR_BUTTON)?c.host:null;}return b?b.matches(NOT_A_PAYMENT)?"none":b.matches(CARD_FORM_BUTTON)?"checkout_step":"wallet":void 0}function isWalletElement(a){return "wallet"===vendorButtonKind(a)}// Pickers and toggles choose a payment method or open a panel; they never pay.
|
|
1405
|
+
var PICKER="input[type=\"radio\"], input[type=\"checkbox\"], label, [role=\"radio\"], [role=\"tab\"], [role=\"option\"], [role=\"checkbox\"], [role=\"switch\"], [role=\"menuitemradio\"], [role=\"menuitemcheckbox\"], [aria-checked], [aria-selected]",PICKER_GROUP="[role=\"radiogroup\"], [role=\"tablist\"], [role=\"listbox\"]",MESSAGING="klarna-placement, afterpay-placement, square-placement, .affirm-as-low-as, .affirm-site-modal, .affirm-product-modal, [data-pp-message]";// Pay-later and financing messages link to details rather than pay.
|
|
1406
|
+
// A control that is still logged as a click but never counts as checkout intent.
|
|
1407
|
+
function isQuietIntentControl(a,b){return !!a.matches(PICKER)||!!hasComposedAncestor(a,PICKER_GROUP)||!!(!b&&(a.hasAttribute("aria-expanded")||a.hasAttribute("aria-pressed")))||hasComposedAncestor(a,MESSAGING)}// A checkbox or radio is a control of its own only when no button or link
|
|
1408
|
+
// around it takes the click, so a tappable row keeps its own name.
|
|
1409
|
+
var OPTION_INPUT="input[type=\"checkbox\"], input[type=\"radio\"]";// Walks at most 12 entries of an event's composed path for the nearest control.
|
|
1410
|
+
// One composed walk from the target rules out Rokt elements and anything under
|
|
1411
|
+
// data-mp-no-track; disabled controls are skipped.
|
|
1412
|
+
function findControl(a){for(var b,c,d=a.slice(0,12),e=0,f=d;e<f.length;e++)if(c=f[e],c instanceof Element){b=c;break}if(b&&!hasComposedAncestor(b,"[data-core-type], #rokt-controller-frame, [data-mp-no-track]")){for(var g,h,c,i=0;i<(void 0).length;i++)if(c=(void 0)[i],!!(c instanceof Element)){if(hasRoktSrc(c))return;!g&&c.matches("button, input[type=\"submit\"], input[type=\"button\"], input[type=\"image\"], [role=\"button\"], a[href], "+VENDOR_BUTTON)?g=c:!g&&!h&&c.matches(OPTION_INPUT)&&(h=c);}return g=g||h,!g||g.matches(":disabled, [aria-disabled=\"true\"]")?void 0:g}}// fields, editable regions, and anything under data-mp-no-track.
|
|
1413
|
+
function isUnsafeTextSource(a){return a.matches("input, select, textarea, option, optgroup, datalist, [contenteditable]:not([contenteditable=\"false\"])")||!!a.querySelector("input, select, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")||hasComposedAncestor(a,"select, datalist, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")}// A label around a checkbox or radio holds no typed text, so only the other
|
|
1414
|
+
// fields rule its text out.
|
|
1415
|
+
function isUnsafeLabelSource(a){return !!a.querySelector("input:not([type=\"checkbox\"]):not([type=\"radio\"]), select, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")||hasComposedAncestor(a,"select, datalist, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")}
|
|
1378
1416
|
|
|
1379
1417
|
// Masks a button label before it is logged. Button text can carry personal data,
|
|
1380
1418
|
// so this is the privacy boundary for every label and aria-label.
|
|
@@ -1385,12 +1423,14 @@ function createDigitPatterns(){try{return {run:/\p{Nd}{6,}/u,number:/\p{Nd}+(?:[
|
|
|
1385
1423
|
function maskLabel(a){if(a&&!(128<a.length)&&digitPatterns){var b=a.replace(/\s+/g," ").trim().toLowerCase();if(b&&-1===b.indexOf("@")&&!digitPatterns.run.test(b.replace(/[\s()\-\u2010-\u2015]/g,""))){var c=b.replace(digitPatterns.number,"#").slice(0,64).trim();return c||void 0}}}
|
|
1386
1424
|
|
|
1387
1425
|
var DOWNLOAD_EXTENSIONS=/\.(pdf|zip|csv|txt|ics|docx?|xlsx?|pptx?|dmg|exe|apk|mp3|mp4)$/i;function elementKind(a){if(isWalletElement(a))return "wallet";var b=a.tagName.toLowerCase();return "button"===b||"input"===b?b:a.matches("a[href]:not([role=\"button\"])")?"link":"role"}function textOf(a){return a&&!isUnsafeTextSource(a)&&a.textContent?a.textContent.trim():""}function nonBlank(a){return a&&a.trim()?a:void 0}// The button's name as a screen reader would read it, simplified: the first of
|
|
1388
|
-
// aria-labelledby, aria-label, own text (or an inner image's alt), title,
|
|
1389
|
-
// inputs their value
|
|
1390
|
-
//
|
|
1426
|
+
// aria-labelledby, aria-label, own text (or an inner image's alt), title, for
|
|
1427
|
+
// inputs their value, and for checkboxes and radios their label's text. The text
|
|
1428
|
+
// sources are skipped for controls that hold form fields or more than four
|
|
1429
|
+
// children, so a typed value is never read.
|
|
1391
1430
|
function accessibleName(a){var b=a.getAttribute("aria-labelledby");if(b){var c=isFunction(a.getRootNode)?a.getRootNode():document,d=b.split(/\s+/).map(function(a){return textOf(c.getElementById?c.getElementById(a):null)}).filter(function(a){return !!a}).join(" ");if(d)return {raw:d,source:"labelledby"}}var e=nonBlank(a.getAttribute("aria-label"));if(e)return {raw:e,source:"aria"};var f=4>=a.children.length&&!isUnsafeTextSource(a);if(a instanceof HTMLInputElement){// The browser's normalised type: an unknown value reads as 'text'.
|
|
1392
1431
|
var g=a.type;if("image"===g){var h=nonBlank(a.getAttribute("alt"));if(h)return {raw:h,source:"alt"}}else if("submit"===g||"button"===g||"reset"===g){var i=nonBlank(a.value);if(i)return {raw:i,source:"value"};if("button"!==g)// What the browser shows on an input without a value.
|
|
1393
|
-
return {raw:g,source:"value"}}
|
|
1432
|
+
return {raw:g,source:"value"}}else if("checkbox"===g||"radio"===g){// The label the browser ties to the box, never the box's value.
|
|
1433
|
+
var j=a.labels?a.labels[0]:void 0,d=j&&!isUnsafeLabelSource(j)&&j.textContent?j.textContent.trim():"";if(d)return {raw:d,source:"label"}}}else if(f){var d=textOf(a);if(d)return {raw:d,source:"text"};var k=a.querySelector("img[alt]"),h=k?nonBlank(k.getAttribute("alt")):void 0;if(h)return {raw:h,source:"alt"}}var l=nonBlank(a.getAttribute("title"));return l?{raw:l,source:"title"}:{source:"none"}}var ICON_CLASS=/^(?:fa|fas|far|fal|icon|bi|glyphicon|ti|mdi|ri|la|lucide|ion|feather|ph)-([a-z][a-z-]{1,31})$/,ICON_MODIFIER=/^(?:solid|regular|light|thin|duotone|brands|sharp|fw|lg|xs|sm|xl|spin|pulse|border|inverse|stack|flip(?:-[a-z]+)?|rotate(?:-[a-z]+)?|pull-[a-z]+)$/;// Size, style and animation classes that share the icon prefixes.
|
|
1394
1434
|
function iconToken(a){if(a){var b=a.toLowerCase().replace(/^icon-/,"");return /^[a-z][a-z-]{1,31}$/.test(b)?b:void 0}}// An icon name from an SVG sprite reference or an icon-font class, for buttons
|
|
1395
1435
|
// whose only content is an icon. Letters and hyphens only.
|
|
1396
1436
|
function iconHint(a){var b=function(a){return !hasComposedAncestor(a,"[data-mp-no-track]")},c=Array.from(a.querySelectorAll("use")).filter(b)[0];if(c){var d=c.getAttribute("href")||c.getAttribute("xlink:href")||"",e=d.indexOf("#"),f=iconToken(-1===e?null:d.slice(e+1));if(f)return f}for(var g=[a].concat(Array.from(a.querySelectorAll("i, span, svg"))).filter(b).slice(0,5),h=0,i=g;h<i.length;h++)for(var j=i[h],k=(j.getAttribute("class")||"").split(/\s+/),l=0,m=k;l<m.length;l++){var n=m[l],o=ICON_CLASS.exec(n.toLowerCase());if(o&&!ICON_MODIFIER.test(o[1]))return o[1]}}// Words of letters, each optionally ending in up to three digits, joined by
|
|
@@ -1413,32 +1453,60 @@ function describeLink(a){var b=(a.getAttribute("href")||"").trim();if(!b||"#"===
|
|
|
1413
1453
|
// views can't see the click, and carries its link type.
|
|
1414
1454
|
function describeButtonClick(a){var b;if(!(a.matches("a[href]:not([role=\"button\"])")&&(b=describeLink(a),!b))){var c=elementKind(a),d=accessibleName(a),e=maskLabel(d.raw);return {label:e,labelSource:e?d.source:"none",// Kept on its own as well: it often says more than the visible text,
|
|
1415
1455
|
// such as which item a remove button removes.
|
|
1416
|
-
ariaLabel:maskLabel(a.getAttribute("aria-label")),icon:iconHint(a),elementId:stableIdentifier(a.getAttribute("id")),elementName:stableIdentifier(a.getAttribute("name")),testId:firstIdentifier(a,TEST_ID_ATTRIBUTES),controls:controlsIdentifier(a),form:formIdentifier(a),element:c,type:controlType(a,c),linkType:b?b.type:void 0,linkDomain:b?b.domain:void 0,fileExtension:b?b.fileExtension:void 0
|
|
1417
|
-
|
|
1418
|
-
|
|
1456
|
+
ariaLabel:maskLabel(a.getAttribute("aria-label")),icon:iconHint(a),elementId:stableIdentifier(a.getAttribute("id")),elementName:stableIdentifier(a.getAttribute("name")),testId:firstIdentifier(a,TEST_ID_ATTRIBUTES),controls:controlsIdentifier(a),form:formIdentifier(a),element:c,type:controlType(a,c),linkType:b?b.type:void 0,linkDomain:b?b.domain:void 0,fileExtension:b?b.fileExtension:void 0,// The box as the click left it: the browser toggles it before the click
|
|
1457
|
+
// reaches listeners, and puts it back if the click is cancelled.
|
|
1458
|
+
checked:a instanceof HTMLInputElement&&("checkbox"===a.type||"radio"===a.type)?a.checked:void 0}}}
|
|
1459
|
+
|
|
1460
|
+
var checkoutPath=/(?:^|\/)(?:checkouts?|payment|order|kasse|paiement|commander?|pago)(?:\/|$)/i,englishExclusions=/\b(?:coupon|promo(?: code)?|newsletter|sign in|sign up|log in|login|add to (?:cart|bag|basket)|gift card balance|(?:add|apply|redeem|check|enter|use) (?:a |an |your )?gift card|pay later|interest free|as low as|learn more|prequalify|apply (?:now|for)|payment plan|available|accepted|we accept|set up|add money|reload|top up|add to (?:apple|google) wallet|connect|link your|unlink|remove|delete|edit|change|manage|use a different|switch)\b|^pay in$|\bpay in (?:installments|instalments)\b/,otherExclusions=new RegExp("gutschein|anmelden|warenkorb|bon cadeau|connexion|panier|cup\xF3n|iniciar sesi\xF3n|carrito|carrello|codice sconto|accedi|buono regalo|winkelwagen|kortingscode|inloggen|cadeaubon|achteraf betalen|\u30AB\u30FC\u30C8|\u30AF\u30FC\u30DD\u30F3|\u30ED\u30B0\u30A4\u30F3|\u4F1A\u54E1\u767B\u9332|\u30AE\u30D5\u30C8|\u5F8C\u6255\u3044|\u30E1\u30EB\u30DE\u30AC"),englishCommits="(?:(?:agree|accept|review) and )?(?:place|submit|complete|confirm|finali[sz]e)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?! (?:[^ ]+ )?gift card)(?: [^ ]+){0,2} (?:order|purchase|booking|reservation|payment|checkout|transaction)(?: now| securely| and pay| (?:with|using) [^ ]+(?: [^ ]+)?)?(?: (?:total|subtotal|items?|tickets?))?|pay(?: securely)?(?: now)?|(?:confirm|agree|accept|submit|order|book) and pay|pay and place (?:my |your )?order|order with obligation to pay",otherCommits="(?:jetzt )?(?:zahlungs|kosten)pflichtig (?:bestellen|buchen)|(?:jetzt )?bezahlen|kauf abschlie\xDFen|bestellung abschlie\xDFen|commander et payer|payer(?: maintenant)?|(?:confirmer|finaliser) (?:ma |la )?commande|valider et payer|confirmer et payer|commande avec obligation de paiement|finaliser l'achat|(?:realizar|confirmar|completar) (?:el |mi |la )?(?:pedido|compra|reserva)|finalizar (?:el |mi )?pedido|pagar(?: ahora)?|pedido con obligaci\xF3n de pago|(?:effettua|conferma|concludi|completa) (?:l'|il )?(?:ordine|acquisto)|ordine con obbligo di pagamento|paga(?: ora| adesso)?|ordina e paga|(?:nu )?betalen|bestellen en betalen|bestelling plaatsen|plaats bestelling|bestelling afronden|bestelling met betalingsverplichting|(?:\u3053\u306E\u5185\u5BB9\u3067|\u4E0A\u8A18\u306E?\u5185\u5BB9\u3067)?\u3054?(?:\u6CE8\u6587|\u8CFC\u5165|\u4E88\u7D04|\u6C7A\u6E08|\u304A?\u652F\u6255\u3044?)\u3092?(?:\u78BA\u5B9A|\u5B8C\u4E86)(?:\u3059\u308B)?|(?:\u3053\u306E\u5185\u5BB9\u3067|\u4E0A\u8A18\u306E?\u5185\u5BB9\u3067)\u3054?(?:\u6CE8\u6587|\u8CFC\u5165|\u4E88\u7D04)\u3059\u308B|\u3054?\u6CE8\u6587\u3059\u308B|\u6C7A\u6E08\u3059\u308B|(?:\u4ECA\u3059\u3050|\u3092)?\u652F\u6255\u3046",commits=new RegExp("^(?:"+englishCommits+"|"+otherCommits+")$"),linkCommits=new RegExp("^(?:(?:place|submit|complete)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?: [^ ]+){0,2} (?:order|purchase)|"+otherCommits+")$"),routeGatedCommits=/^(?:buy now|purchase|jetzt kaufen|kaufen|commander|(?:passer|valider) (?:la |ma )?commande|finalizar (?:la |mi )?compra|comprar ahora|acquista ora|nu kopen|\u4ECA\u3059\u3050\u8CFC\u5165|\u8CFC\u5165\u3059\u308B|\u3053\u306E\u5185\u5BB9\u3067\u7533\u3057\u8FBC\u3080)$/,steps=new RegExp("^(?:"+"(?:let's |lets |go to |proceed to |secure )?(?:check ?out|checkout)(?: now| securely| as guest)?|(?:continue|proceed) to (?:payment|review|billing|shipping|delivery|order review)|review (?:my |your )?order|guest checkout|(?:pay|continue|check ?out) (?:with|by) (?:card|credit card|debit card|credit or debit card)|zur kasse|zur kasse gehen|auschecken|weiter zur zahlung|passer \xE0 la caisse|continuer vers le paiement|proc\xE9der au paiement|ir a caja|continuar al pago|tramitar pedido|procedi al checkout|procedi all'acquisto|procedi al pagamento|vai alla cassa|afrekenen|verder naar betalen|doorgaan naar betalen|\u30EC\u30B8\u306B\u9032\u3080|\u3054?(?:\u8CFC\u5165|\u6CE8\u6587)\u624B\u7D9A\u304D(?:\u3078|\u306B)(?:\u9032\u3080)?|\u304A?\u652F\u6255\u3044(?:\u3078|\u306B)\u9032\u3080|(?:\u3054\u6CE8\u6587\u5185\u5BB9\u306E)?\u78BA\u8A8D\u753B\u9762\u3078(?:\u9032\u3080)?"+")$"),WALLET_NAMES="apple pay|google pay|paypal|venmo|amazon pay|shop pay|klarna|afterpay|clearpay|cash app(?: pay)?|affirm|sezzle|samsung pay",WALLET_VERBS="pay|buy|purchase|order|book|donate|subscribe|check ?out|checkout|express checkout|continue|proceed|complete purchase|place (?:my |your )?order",walletPhrases=new RegExp("^(?:(?:"+WALLET_VERBS+")(?: now| securely)? (?:with|using|via|through|by) (?:"+WALLET_NAMES+")(?: express(?: checkout)?| checkout)?|(?:continue|proceed|go) (?:to|with) (?:"+WALLET_NAMES+"))$"),walletBrands=new RegExp("^(?:"+WALLET_NAMES+")(?: (?:checkout|check out|express(?: checkout)?|express pay|buy now|pay now|pay|now)| (?:logo|icon|mark|button)(?: (?:logo|icon|mark|button))*)?$"),walletFrameHosts=new Set(["pay.google.com","applepay.cdn-apple.com","payments.amazon.com","pay.shopify.com"]),paypalFrameHosts=new Set(["www.paypal.com","www.sandbox.paypal.com"]),PAYPAL_BUTTON_FRAME=/^\/smart\/(?:buttons|menu)(?:\/|$)/,STRIPE_WALLET_FRAME=/\/elements-inner-(?:payment-request|express-checkout)-/,CARD_FRAME_DOMAINS=["adyen.com","braintreegateway.com","cybersource.com","squarecdn.com","checkout.com"],TYPOGRAPHIC_APOSTROPHES=/[\u2019\u2018]/g,CURRENCY_AND_NUMBER_CHARS=/[0-9\uFF10-\uFF19$\u20AC\u00A3\u00A5\uFFE5\u20B9\u5186.,\uFF0C]/g,BRACKETED=/\([^()]*\)|\[[^[\]]*\]|\uFF08[^\uFF08\uFF09]*\uFF09|\uFF3B[^\uFF3B\uFF3D]*\uFF3D|\u3010[^\u3010\u3011]*\u3011/g,EDGE="[\\s!-/:-@\\[-`{-~\\u00A1-\\u00BF\\u00D7\\u00F7\\u2000-\\u206F\\u20A0-\\u20CF\\u2190-\\u2BFF\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u30FB\\uD800-\\uDFFF\\uFE00-\\uFE0F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65]+",EDGE_SYMBOLS=new RegExp("^"+EDGE+"|"+EDGE+"$","g");// English look-alikes are whole words; the other languages stay substring
|
|
1461
|
+
// matches, since several of them do not separate words with spaces.
|
|
1462
|
+
// A plain link is navigation, so in English only an order or purchase it
|
|
1463
|
+
// places, submits or completes counts as the confirm click.
|
|
1464
|
+
// "Pay with Klarna", "Buy with GPay", "Continue to PayPal".
|
|
1465
|
+
// A wallet's own name on a button: "PayPal", "Klarna checkout", "Apple Pay logo".
|
|
1466
|
+
// Exact HTTPS hosts of hosted wallet button frames.
|
|
1467
|
+
// PayPal serves its buttons and its card fields and pay-later messages from
|
|
1468
|
+
// the same hosts; only the button frames are wallet taps.
|
|
1469
|
+
// Stripe's quick-pay button frames; its other frames are card and form fields.
|
|
1470
|
+
// Hosted card-entry and fingerprint frames: focus there is typing card details.
|
|
1419
1471
|
// Keep these classes ASCII-only in source bytes to avoid mojibake parse failures
|
|
1420
1472
|
// when a host page forces non-UTF-8 decoding before JavaScript parse.
|
|
1421
|
-
|
|
1422
|
-
//
|
|
1423
|
-
|
|
1424
|
-
function
|
|
1425
|
-
|
|
1426
|
-
function
|
|
1473
|
+
// Spaces, punctuation, separators, arrows and symbols, CJK and full-width forms
|
|
1474
|
+
// included, plus emoji halves and variation selectors.
|
|
1475
|
+
function getIntentRouteClass(a){return checkoutPath.test(a)?"checkout_path":"other"}var SEPARATORS=/[-_|\u00B7\u2022]/g,CURRENCY_CODES=/(?:^| )(?:usd|aud|cad|nzd|gbp|eur|chf|sgd|hkd|jpy|inr|mxn)(?= |$)|\b(?:a|au|ca|c|us|nz|hk|s)\$/g,WALLET_ALIASES=[[/\bapplepay\b/g,"apple pay"],[/\bg ?pay\b/g,"google pay"],[/\bamazonpay\b/g,"amazon pay"],[/\bshoppay\b/g,"shop pay"],[/\bcashapp\b/g,"cash app"]],MAX_LABEL_WORDS=8;// Labels longer than this are sentences: they neither match nor veto intent.
|
|
1476
|
+
function normalize(a){if(a&&!(128<a.length)){var b=a.toLowerCase().replace(TYPOGRAPHIC_APOSTROPHES,"'").replace(/[&+]/g," and ").replace(SEPARATORS," ").replace(CURRENCY_CODES," ").replace(CURRENCY_AND_NUMBER_CHARS,"").replace(/\s+/g," ").trim();return WALLET_ALIASES.forEach(function(a){var c=a[0],d=a[1];b=b.replace(c,d);}),b.split(" ").length>MAX_LABEL_WORDS?void 0:b}}// The label without bracketed asides or the separators and symbols left at its
|
|
1477
|
+
// edges, so "place order -" and "place order ( items)" both read "place order".
|
|
1478
|
+
function coreLabel(a){var b=a.replace(BRACKETED," ").replace(/\s+/g," ").replace(EDGE_SYMBOLS,"");return b||a.replace(EDGE_SYMBOLS,"")}// Labels come from aria-label then visible text. Only submit and button inputs
|
|
1479
|
+
// have their value read, so a typed field value is never touched. A control
|
|
1480
|
+
// holding form fields or more than four children gives only its aria-label.
|
|
1481
|
+
function labelSources(a){if(a instanceof HTMLInputElement){var b=a.type,c=null;return "submit"===b||"button"===b?c=a.value:"image"===b&&(c=a.getAttribute("alt")),[a.getAttribute("aria-label"),c]}return 4<a.children.length||isUnsafeTextSource(a)?[a.getAttribute("aria-label")]:[a.getAttribute("aria-label"),a.textContent]}function labels(a){return labelSources(a).map(normalize).filter(function(a){return !!a})}// "Buy now" and "Purchase" count only on a checkout route, and never on a plain
|
|
1482
|
+
// link, which is navigation.
|
|
1483
|
+
function isCommitLabel(a,b,c){return b?linkCommits.test(a):commits.test(a)||routeGatedCommits.test(a)&&"checkout_path"===getIntentRouteClass(c)}// Classifies a clicked or submitting control found by findControl, in order:
|
|
1484
|
+
// pickers, toggles and pay-later messages never count; a vendor's own wallet
|
|
1485
|
+
// button counts before any label rule; a confirm label on any source counts
|
|
1486
|
+
// before the look-alike exclusions veto; then wallet phrases and steps.
|
|
1487
|
+
function classifyIntent(a,b){var c=vendorButtonKind(a);if(!(isQuietIntentControl(a,"wallet"===c)||"none"===c)){if(c)return {kind:c,source:"vendor"};var d=labels(a),e=d.map(coreLabel),f=a.matches("a[href]:not([role=\"button\"])");if(e.some(function(a){return isCommitLabel(a,f,b)}))return {kind:"commit",source:"label"};if(!d.concat(e).some(function(a){return englishExclusions.test(a)||otherExclusions.test(a)}))for(var g,h=!f&&a.matches(CONTROL_SELECTOR),i=0;i<(void 0).length;i++){if(g=(void 0)[i],h&&walletPhrases.test(g))return {kind:"wallet",source:"label"};if(h&&walletBrands.test(g))return {kind:"wallet",source:"brand"};if(steps.test(g))return {kind:"checkout_step",source:"label"}}}}function isOnDomain(a,b){return a===b||a.length>b.length&&a.slice(a.length-b.length-1)==="."+b}// Focus moving into a visible hosted wallet button counts as a wallet click;
|
|
1488
|
+
// focus into hosted card fields or messages is only a frame.
|
|
1489
|
+
function classifyIntentFrame(a,b){if("visible"===b.document.visibilityState&&a instanceof HTMLIFrameElement&&!(isRoktElement(a)||hasComposedAncestor(a,"[data-mp-no-track]")))try{var c=new URL(a.src),d="https:"===c.protocol?c.hostname:"";if(paypalFrameHosts.has(d))return PAYPAL_BUTTON_FRAME.test(c.pathname)?"wallet":"frame";if(walletFrameHosts.has(d))return "wallet";if("js.stripe.com"===d)return STRIPE_WALLET_FRAME.test(c.pathname)?"wallet":"frame";if(CARD_FRAME_DOMAINS.some(function(a){return isOnDomain(d,a)}))return "frame"}catch(a){// An unparseable frame src is not a wallet frame.
|
|
1427
1490
|
}}
|
|
1428
1491
|
|
|
1429
1492
|
// listeners. Inspect `window.__mpBtn__` in a console to see if one is live.
|
|
1430
|
-
var WIN_BTN_KEY="__mpBtn__";var THROTTLE_MS=2e3,SUBMIT_AFTER_COMMIT_CLICK_MS=1e3,PATH_LIMIT=12,PAGE_EVENT_LIMIT=100,btnWindow=function(){return "undefined"==typeof window?null:window};// A ceiling, not a dedupe: a held Enter key or browser automation fires a
|
|
1493
|
+
var WIN_BTN_KEY="__mpBtn__";var THROTTLE_MS=2e3,SUBMIT_AFTER_COMMIT_CLICK_MS=1e3,PATH_LIMIT=12,PAGE_EVENT_LIMIT=100,UPLOAD_DEBOUNCE_MS=100,btnWindow=function(){return "undefined"==typeof window?null:window};// A ceiling, not a dedupe: a held Enter key or browser automation fires a
|
|
1431
1494
|
// trusted click per repeat, and each one is forwarded to every kit.
|
|
1495
|
+
// A click uploads at once. Taps that follow it this quickly are held and share
|
|
1496
|
+
// one upload once they stop.
|
|
1432
1497
|
var getActiveButtonTracker=function(){var a=btnWindow(),b=a?a[WIN_BTN_KEY]:void 0;return b?b.tracker:void 0};// Stops whichever tracker is active, including one from an earlier bundle load.
|
|
1433
1498
|
var resetButtonTracking=function(){var a=btnWindow();if(a){var b=getActiveButtonTracker();b&&b.teardown(),a[WIN_BTN_KEY]={};}};// Runs once the browser has painted the page's response to the interaction, so
|
|
1434
1499
|
// describing and logging a click never delays that paint.
|
|
1435
|
-
var afterNextPaint=function(a){isFunction(window.requestAnimationFrame)&&"hidden"!==document.visibilityState?requestAnimationFrame(function(){setTimeout(a,0);}):setTimeout(a,0);},CAPTURE_PASSIVE={capture:!0,passive:!0},PASSIVE={passive:!0},ButtonTracker=/** @class */function(){function a(a){var b=this;this.active=!1,this.hasRoktKit=!1,this.generation=0,this.lastCommitClick=-Infinity,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.pending=[],this.drain=function(){var a=b.pending;b.pending=[],a.forEach(function(a){return a()});},this.onHide=function(a){("beforeunload"===a.type||"pagehide"===a.type||"hidden"===document.visibilityState)
|
|
1500
|
+
var afterNextPaint=function(a){isFunction(window.requestAnimationFrame)&&"hidden"!==document.visibilityState?requestAnimationFrame(function(){setTimeout(a,0);}):setTimeout(a,0);},CAPTURE_PASSIVE={capture:!0,passive:!0},PASSIVE={passive:!0},ButtonTracker=/** @class */function(){function a(a){var b=this;this.active=!1,this.hasRoktKit=!1,this.generation=0,this.lastCommitClick=-Infinity,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.pending=[],this.uploadTimerId=null,this.uploadHeld=!1,this.leaving=!1,this.drain=function(){var a=b.pending;b.pending=[],a.forEach(function(a){return a()});},this.onHide=function(a){if("beforeunload"===a.type||"pagehide"===a.type||"hidden"===document.visibilityState){b.leaving=!0;try{b.drain();}finally{b.leaving=!1;}// The SDK's exit upload sends the queue, held taps included.
|
|
1501
|
+
b.cancelUpload();}},this.onPageShow=function(a){a.persisted&&b.reset();},this.onEvent=function(a){try{b.observe(a);}catch(a){b.log("[error] event handler threw: "+a);}},this.mpInstance=a;}return Object.defineProperty(a.prototype,"isActive",{get:function get(){return this.active},enumerable:!1,configurable:!0}),a.prototype.init=function(a){var b=btnWindow();if(b){var c=getActiveButtonTracker();return c&&c.teardown(),this.active&&this.teardown(),this.hasRoktKit=a.hasRoktKit,!this.eventsEnabled()&&this.isKitSuppressed()?void this.log("opted out, not starting"):void(b.document.addEventListener("click",this.onEvent,CAPTURE_PASSIVE),b.document.addEventListener("submit",this.onEvent,CAPTURE_PASSIVE),b.addEventListener("blur",this.onEvent,PASSIVE),b.addEventListener("pageshow",this.onPageShow,PASSIVE),b.addEventListener("beforeunload",this.onHide,CAPTURE_PASSIVE),b.addEventListener("pagehide",this.onHide,CAPTURE_PASSIVE),b.document.addEventListener("visibilitychange",this.onHide,CAPTURE_PASSIVE),this.active=!0,!b[WIN_BTN_KEY]&&(b[WIN_BTN_KEY]={}),b[WIN_BTN_KEY].tracker=this,this.log("listening"))}},a.prototype.teardown=function(){var a=btnWindow();if(a){a.document.removeEventListener("click",this.onEvent,!0),a.document.removeEventListener("submit",this.onEvent,!0),a.removeEventListener("blur",this.onEvent),a.removeEventListener("pageshow",this.onPageShow),a.removeEventListener("beforeunload",this.onHide,!0),a.removeEventListener("pagehide",this.onHide,!0),a.document.removeEventListener("visibilitychange",this.onHide,!0);var b=a[WIN_BTN_KEY];b&&b.tracker===this&&(b.tracker=void 0);}this.active=!1,this.clearPending();},a.prototype.clearPending=function(){this.reset();var a=this.mpInstance._RoktManager;a&&a.discardCheckoutIntents();},a.prototype.reset=function(){this.generation++,this.pending=[],this.lastCommitClick=-Infinity,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.cancelUpload();},a.prototype.enqueue=function(a){this.pending.push(a),1===this.pending.length&&afterNextPaint(this.drain);},a.prototype.observe=function(a){var b=this;if(this.active&&a.isTrusted){// The button is read now, while the click is still being dispatched:
|
|
1436
1502
|
// this capture listener runs before the page's own handlers, so a
|
|
1437
1503
|
// button that disables or relabels itself is seen as it was clicked.
|
|
1438
1504
|
// Logging and the kit hand-off wait for the next paint.
|
|
1439
|
-
var c=a.type,d="click"===c&&this.eventsEnabled(),e=!this.isKitSuppressed();if(d||e){var f,g,h=Date.now(),
|
|
1440
|
-
var
|
|
1441
|
-
|
|
1505
|
+
var c=a.type,d="click"===c&&this.eventsEnabled(),e=!this.isKitSuppressed();if(d||e){var f,g,h,i,j=Date.now(),k=window.location.pathname,l=!1;if("click"===c){// The composed path is only populated during dispatch.
|
|
1506
|
+
var m=findControl(isFunction(a.composedPath)?a.composedPath().slice(0,PATH_LIMIT):[]);if(m){f=d?describeButtonClick(m):void 0,f&&void 0!==f.checked&&(g=m);// Checkout intent is only worked out when the kit can use it.
|
|
1507
|
+
var n=e?classifyIntent(m,k):void 0;h=n?n.kind:void 0,i=n?n.source:void 0;}}else if("submit"===c){var o=a.submitter,m=o?findControl([o]):void 0;// A form submitted without a submitter only counts right after a
|
|
1508
|
+
// commit click, which is known once that click is delivered.
|
|
1509
|
+
if(!o)h="commit",i="submit";else if(m){var n=classifyIntent(m,k);h=n?n.kind:void 0,i=n?n.source:void 0;}l=!o;}var p=this.generation;this.enqueue(function(){if(p===b.generation)try{"blur"===c?(h=classifyIntentFrame(document.activeElement,window),i="frame"):l&&j-b.lastCommitClick>SUBMIT_AFTER_COMMIT_CLICK_MS&&(h=void 0),f&&d&&(g&&a.defaultPrevented&&(f.checked="checkbox"===g.type?!f.checked:g.checked),b.logClick(f,k)),h&&b.emit(h,i,c,j,k);}catch(a){b.log("[error] delivery threw: "+a);}});}}},a.prototype.logClick=function(a,b){if(this.eventsEnabled()&&(b!==this.pagePath&&(this.pagePath=b,this.pageEvents=0),!(this.pageEvents>=PAGE_EVENT_LIMIT))){this.pageEvents++,this.mpInstance._SessionManager.resetSessionTimer();var c=this.queuedForUpload();this.mpInstance._Events.logEvent(buildButtonClickEvent(a,b)),!this.leaving&&void 0===a.checked&&this.queuedForUpload()>c&&this.uploadNow();}},a.prototype.queuedForUpload=function(){var a=this.mpInstance._APIClient.uploader;return a?a.eventsQueuedForProcessing.length:0},a.prototype.uploadNow=function(){var a=this;null===this.uploadTimerId?this.mpInstance.upload():(clearTimeout(this.uploadTimerId),this.uploadHeld=!0),this.uploadTimerId=setTimeout(function(){a.uploadTimerId=null,a.uploadHeld&&(a.uploadHeld=!1,a.mpInstance.upload());},UPLOAD_DEBOUNCE_MS);},a.prototype.cancelUpload=function(){null!==this.uploadTimerId&&(clearTimeout(this.uploadTimerId),this.uploadTimerId=null),this.uploadHeld=!1;},a.prototype.emit=function(a,b,c,d,e){if(!this.isKitSuppressed()){"commit"===a&&"click"===c&&(this.lastCommitClick=d);var f=this.lastSent[a];f&&f.pathname===e&&d-f.t<THROTTLE_MS||(this.lastSent[a]={t:d,pathname:e},this.mpInstance._RoktManager.notifyCheckoutIntent(Object.freeze({kind:a,t:d,source:b,pathname:e}),e));}},a.prototype.eventsEnabled=function(){var a=this.mpInstance._Store;return !!a&&a.isEnabled},a.prototype.isKitSuppressed=function(){var a=this.mpInstance._RoktManager;return !this.hasRoktKit||!a||a.isCheckoutIntentSuppressed()},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle button tracking: "+a);},a}();// Logs every button click as an mParticle event, and hands checkout intent to the
|
|
1442
1510
|
|
|
1443
1511
|
var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
|
|
1444
1512
|
* <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
|
|
@@ -1578,7 +1646,7 @@ function completeSDKInitialization(a,b,c){var d,e,f,g,h=createKitBlocker(b,c),i=
|
|
|
1578
1646
|
if((null===(d=c._APIClient)||void 0===d?void 0:d.uploader)&&c._APIClient.uploader.destroy(),c._APIClient=new APIClient(c,h),c._Forwarders=new Forwarders(c,h),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a),resetButtonTracking();else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
|
|
1579
1647
|
var m=c.Identity.getCurrentUser(),n=m?m.getMPID():null,o=m?m.getUserIdentities().userIdentities:{};// https://go.mparticle.com/work/SQDSDKS-7639
|
|
1580
1648
|
if(c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:o}:c._Store.SDKConfig.identifyRequest,i(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),isIntegrationCaptureEnabled(i)){var p=i(CaptureIntegrationSpecificIds),q=i(CaptureIntegrationSpecificIdsV2),r=void 0;p||q===CaptureIntegrationSpecificIdsV2Modes.All?r="all":q===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(r="roktonly"),c._IntegrationCapture=new IntegrationCapture(r),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
|
|
1581
|
-
var s=parseConfig(b,"Rokt",181);if(s){var t=null===(e=s.settings)||void 0===e?void 0:e.accountId;c._Store.setRoktAccountId(t);var u=
|
|
1649
|
+
var s=parseConfig(b,"Rokt",181);if(s){var t=null===(e=s.settings)||void 0===e?void 0:e.accountId;c._Store.setRoktAccountId(t);var u=function(a){return filteredMparticleUser(a,s,c,h)},v={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};c._RoktManager.init(s,u(n),c.Identity,c._Store,c.Logger,v,c.captureTiming,c._ErrorReportingDispatcher,c._LoggingDispatcher,c._IntegrationCapture,u);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),i(k)?(!c._PageViewTracker&&(c.Logger.verbose("mParticle APV: [sdk-init] creating new PageViewTracker for this instance"),c._PageViewTracker=new PageViewTracker(c,{isAutoPageView:!0})),hasInitialPageViewFired()?c.Logger.verbose("mParticle APV: [sdk-init] initial page view already logged this page load, skipping"):(markInitialPageViewFired(),c._Events.logPageView({isAutoPageView:!0})),c._PageViewTracker.init()):c._PageViewTracker&&c._PageViewTracker.teardown(),i(l)?(!c._ButtonTracker&&(c._ButtonTracker=new ButtonTracker(c)),c._ButtonTracker.init({hasRoktKit:!!s})):resetButtonTracking(),processIdentityCallback(c,m,n,o);}// We will continue to clear out the ready queue as part of the initial init flow
|
|
1582
1650
|
// if an identify request is unnecessary, such as if there is an existing session
|
|
1583
1651
|
(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,null===(f=c._CookieConsentManager)||void 0===f?void 0:f.syncNoTargetingAttribute(c.Identity.getCurrentUser()),c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue,c.Logger)),null===(g=c.processQueueOnNoFunctional)||void 0===g?void 0:g.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
|
|
1584
1652
|
function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
|
|
@@ -1614,6 +1682,7 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot
|
|
|
1614
1682
|
* @param {String} apiKey your mParticle assigned API key
|
|
1615
1683
|
* @param {Object} [config] an options object for additional configuration
|
|
1616
1684
|
* @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples.
|
|
1617
|
-
*/
|
|
1685
|
+
*/ // Kits clean every URL they send with the same rule as core events.
|
|
1686
|
+
this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.RoktEvents=RoktEvents,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);},search:function search(b,c,d){a.getInstance().Identity.search(b,c,d);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this._cleanUrl=cleanUrl,this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this._registerErrorReportingService=function(b){a.getInstance()._registerErrorReportingService(b);},this._registerLoggingService=function(b){a.getInstance()._registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator);
|
|
1618
1687
|
|
|
1619
1688
|
export { mParticleManager as default };
|