@mparticle/web-sdk 2.79.3 → 2.80.1
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 +220 -574
- package/dist/mparticle.esm.js +220 -574
- package/dist/mparticle.js +1489 -1793
- package/dist/types/src/configAPIClient.d.ts +1 -0
- package/dist/types/src/ecommerce.d.ts +3 -53
- package/dist/types/src/ecommerce.interfaces.d.ts +11 -12
- package/dist/types/src/events.interfaces.d.ts +1 -1
- package/dist/types/src/forwarders.d.ts +4 -26
- package/dist/types/src/forwarders.interfaces.d.ts +41 -10
- package/dist/types/src/identity-utils.d.ts +3 -3
- package/dist/types/src/identity.d.ts +3 -0
- package/dist/types/src/identity.interfaces.d.ts +45 -11
- package/dist/types/src/identityApiClient.d.ts +5 -4
- package/dist/types/src/mp-instance.d.ts +2 -2
- package/dist/types/src/pageViewTracker.d.ts +12 -5
- package/dist/types/src/persistence.d.ts +3 -44
- package/dist/types/src/persistence.interfaces.d.ts +12 -13
- package/dist/types/src/sdkRuntimeModels.d.ts +3 -2
- package/dist/types/src/store.d.ts +5 -3
- package/package.json +1 -1
- package/src/configAPIClient.ts +1 -0
- package/src/ecommerce.interfaces.ts +12 -21
- package/src/{ecommerce.js → ecommerce.ts} +144 -73
- package/src/events.interfaces.ts +1 -1
- package/src/events.ts +10 -2
- package/src/forwarders.interfaces.ts +73 -10
- package/src/{forwarders.js → forwarders.ts} +214 -176
- package/src/helpers.ts +7 -3
- package/src/identity-utils.ts +2 -2
- package/src/identity.interfaces.ts +58 -14
- package/src/{identity.js → identity.ts} +237 -192
- package/src/identityApiClient.ts +9 -9
- package/src/mp-instance.ts +2 -2
- package/src/pageViewTracker.ts +176 -42
- package/src/persistence.interfaces.ts +12 -13
- package/src/persistence.ts +1210 -0
- package/src/sdkRuntimeModels.ts +3 -1
- package/src/store.ts +5 -3
- package/src/persistence.js +0 -985
package/dist/mparticle.common.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 = "2.
|
|
18
|
+
var version = "2.80.1";
|
|
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",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",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",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,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
|
|
@@ -33,14 +33,14 @@ CaptureIntegrationSpecificIdsV2:"captureIntegrationSpecificIds.V2",AstBackground
|
|
|
33
33
|
var NO_TARGETING_ATTRIBUTE="$NoTargeting";// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
|
|
34
34
|
var HTTP_OK=200;var HTTP_ACCEPTED=202;var HTTP_BAD_REQUEST=400;var HTTP_NOT_FOUND=404;var HTTP_SERVER_ERROR=500;
|
|
35
35
|
|
|
36
|
-
function _typeof
|
|
36
|
+
function _typeof(o) {
|
|
37
37
|
"@babel/helpers - typeof";
|
|
38
38
|
|
|
39
|
-
return _typeof
|
|
39
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
40
40
|
return typeof o;
|
|
41
41
|
} : function (o) {
|
|
42
42
|
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
43
|
-
}, _typeof
|
|
43
|
+
}, _typeof(o);
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
/******************************************************************************
|
|
@@ -156,7 +156,7 @@ return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[
|
|
|
156
156
|
if(null===a||a===void 0)return a;// Handle arrays - recursively obfuscate each element
|
|
157
157
|
if(Array.isArray(a))return a.map(function(a){return obfuscateData(a)});// Handle objects - recursively obfuscate each property
|
|
158
158
|
if(isObject(a)){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=obfuscateData(a[c]));return b}// For primitives and other types, return the type as a string
|
|
159
|
-
return _typeof
|
|
159
|
+
return _typeof(a)},obfuscateDevData=function(a,b){return b?a:obfuscateData(a)};/**
|
|
160
160
|
* Returns a value between 1-100 inclusive.
|
|
161
161
|
*/ // Google's cookie matching service requires `google_hm` values to be web-safe
|
|
162
162
|
// base64 (RFC 4648 §5) without padding, otherwise the write to the hosted
|
|
@@ -198,7 +198,7 @@ return _typeof$1(a)},obfuscateDevData=function(a,b){return b?a:obfuscateData(a)}
|
|
|
198
198
|
*/ // Standalone version of jQuery.extend, from https://github.com/dansdom/extend
|
|
199
199
|
// https://go.mparticle.com/work/SQDSDKS-6047
|
|
200
200
|
function extend(){for(var a=[],b=0;b<arguments.length;b++)a[b]=arguments[b];var c,d,e,f,g,h,j={hasOwn:Object.prototype.hasOwnProperty,class2type:{},type:function type(a){return null==a?a+"":j.class2type[Object.prototype.toString.call(a)]||"object"},isPlainObject:function isPlainObject(a){if(!a||"object"!==j.type(a)||a.nodeType||j.isWindow(a))return !1;try{if(a.constructor&&!j.hasOwn.call(a,"constructor")&&!j.hasOwn.call(a.constructor.prototype,"isPrototypeOf"))return !1}catch(a){return !1}for(var b in a);// eslint-disable-line no-empty
|
|
201
|
-
return b===void 0||j.hasOwn.call(a,b)},isArray:Array.isArray||function(a){return "array"===j.type(a)},isFunction:function(a){return "function"===j.type(a)},isWindow:function isWindow(a){return null!=a&&a==a.window}},k=a[0]||{},l=1,m=!1,n=a.length;for("boolean"==typeof k&&(m=k,k=a[1]||{},l=2),"object"===_typeof
|
|
201
|
+
return b===void 0||j.hasOwn.call(a,b)},isArray:Array.isArray||function(a){return "array"===j.type(a)},isFunction:function(a){return "function"===j.type(a)},isWindow:function isWindow(a){return null!=a&&a==a.window}},k=a[0]||{},l=1,m=!1,n=a.length;for("boolean"==typeof k&&(m=k,k=a[1]||{},l=2),"object"===_typeof(k)||j.isFunction(k)||(k={}),n===l&&(k={},--l);l<n;l++)if(null!=(c=a[l]))for(d in c)"__proto__"!==d&&"constructor"!==d&&"prototype"!==d&&Object.prototype.hasOwnProperty.call(c,d)&&(e=k[d],f=c[d],k!==f)&&(m&&f&&(j.isPlainObject(f)||(g=j.isArray(f)))?(g?(g=!1,h=e&&j.isArray(e)?e:[]):h=e&&j.isPlainObject(e)?e:{},k[d]=extend(m,h,f)):void 0!==f&&(k[d]=f));return k}var getErrorMessage=function(a,b){return void 0===b&&(b="unknown error"),a instanceof Error?a.message:"string"==typeof a?a:a&&"object"===_typeof(a)&&"string"==typeof a.message?a.message:b;// fetch-mock and some network libs reject with { message } rather than Error
|
|
202
202
|
};
|
|
203
203
|
|
|
204
204
|
var MessageType$1={SessionStart:1,SessionEnd:2,PageView:3,PageEvent:4,CrashReport:5,OptOut:6,AppStateTransition:10,Profile:14,Commerce:16,Media:20,UserAttributeChange:17,UserIdentityChange:18};var EventType={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8,Media:9,getName:function getName(a){return a===EventType.Unknown?"Unknown":a===EventType.Navigation?"Navigation":a===EventType.Location?"Location":a===EventType.Search?"Search":a===EventType.Transaction?"Transaction":a===EventType.UserContent?"User Content":a===EventType.UserPreference?"User Preference":a===EventType.Social?"Social":a===CommerceEventType.ProductAddToCart?"Product Added to Cart":a===CommerceEventType.ProductAddToWishlist?"Product Added to Wishlist":a===CommerceEventType.ProductCheckout?"Product Checkout":a===CommerceEventType.ProductCheckoutOption?"Product Checkout Options":a===CommerceEventType.ProductClick?"Product Click":a===CommerceEventType.ProductImpression?"Product Impression":a===CommerceEventType.ProductPurchase?"Product Purchased":a===CommerceEventType.ProductRefund?"Product Refunded":a===CommerceEventType.ProductRemoveFromCart?"Product Removed From Cart":a===CommerceEventType.ProductRemoveFromWishlist?"Product Removed from Wishlist":a===CommerceEventType.ProductViewDetail?"Product View Details":a===CommerceEventType.PromotionClick?"Promotion Click":a===CommerceEventType.PromotionView?"Promotion View":"Other"}};// Continuation of EventType enum above, but in seperate object since we don't expose these to end user
|
|
@@ -211,10 +211,6 @@ getExpansionName:function getExpansionName(a){return a===PromotionActionType.Pro
|
|
|
211
211
|
|
|
212
212
|
var SDKProductActionType;(function(a){a[a.Unknown=0]="Unknown",a[a.AddToCart=1]="AddToCart",a[a.RemoveFromCart=2]="RemoveFromCart",a[a.Checkout=3]="Checkout",a[a.CheckoutOption=4]="CheckoutOption",a[a.Click=5]="Click",a[a.ViewDetail=6]="ViewDetail",a[a.Purchase=7]="Purchase",a[a.Refund=8]="Refund",a[a.AddToWishlist=9]="AddToWishlist",a[a.RemoveFromWishlist=10]="RemoveFromWishlist",a[a.ViewCart=11]="ViewCart",a[a.AddShippingInfo=12]="AddShippingInfo",a[a.AddPaymentInfo=13]="AddPaymentInfo",a[a.PaymentMethodSelected=14]="PaymentMethodSelected",a[a.PaymentAttempted=15]="PaymentAttempted",a[a.PaymentSucceeded=16]="PaymentSucceeded",a[a.PaymentFailed=17]="PaymentFailed",a[a.RefundInitiated=18]="RefundInitiated";})(SDKProductActionType||(SDKProductActionType={}));var LogLevelType={None:"none",Verbose:"verbose",Warning:"warning",Error:"error"};
|
|
213
213
|
|
|
214
|
-
function getDefaultExportFromCjs (x) {
|
|
215
|
-
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
214
|
var dist = {};
|
|
219
215
|
|
|
220
216
|
(function (exports) {
|
|
@@ -555,7 +551,7 @@ if(!isFunction(e))return f.error("search called without a callback function; ski
|
|
|
555
551
|
if(i=function(a){try{e(a);}catch(a){f.error("Error invoking search callback: "+getErrorMessage(a));}},j=Validators.removeFalsyIdentityValues({userIdentities:null!==a&&void 0!==a?a:{}},f).userIdentities,!Object.values(null!==j&&void 0!==j?j:{}).some(function(a){return "string"==typeof a&&0<a.length}))return f.verbose("Identity search called with empty identifiers; skipping request."),i({httpCode:HTTPCodes$4.noHttpCoverage}),[2/*return*/];// No API key -> same: deliver noHttpCoverage rather than hanging.
|
|
556
552
|
if(!b)return f.verbose("search called without a workspace API key; skipping request."),i({httpCode:HTTPCodes$4.noHttpCoverage}),[2/*return*/];v.label=1;case 1:return v.trys.push([1,9,,10]),k=c(),l=__assign(__assign({},k),{known_identities:__assign({},j)}),m={method:"post",headers:{Accept:"application/json","Content-Type":"application/json","x-mp-key":b},body:JSON.stringify(l)},n=g||(window.fetch?new FetchUploader(d):new XHRUploader(d)),f.verbose("Sending search request to "+d),[4/*yield*/,n.upload(m,d)];case 2:if(o=v.sent(),p=void 0,!isFunction(o.json))return [3/*break*/,7];v.label=3;case 3:return v.trys.push([3,5,,6]),[4/*yield*/,o.json()];case 4:return p=v.sent(),[3/*break*/,6];case 5:return v.sent(),f.verbose("search response had no parseable JSON body."),[3/*break*/,6];case 6:return [3/*break*/,8];case 7:if(r=o,null===r||void 0===r?void 0:r.responseText)try{p=JSON.parse(r.responseText);}catch(a){f.verbose("search XHR response was not valid JSON.");}v.label=8;case 8:return o.status===HTTP_OK?f.verbose("search received 200 OK."):o.status===HTTP_NOT_FOUND?f.verbose("search received 404 (no match)."):f.verbose("search received non-success status "+o.status),i({httpCode:o.status,body:p}),[3/*break*/,10];case 9:return s=v.sent(),t=getErrorMessage(s),u="Error sending search request: "+t,f.error(u),null===h||void 0===h?void 0:h.report({message:u,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),i({httpCode:HTTPCodes$4.noHttpCoverage}),[3/*break*/,10];case 10:return [2/*return*/]}})})};
|
|
557
553
|
|
|
558
|
-
var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$3=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout,HTTPCodes$3=Constants.HTTPCodes,Messages$9=Constants.Messages;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
554
|
+
var _a$1=Constants.IdentityMethods,Identify$2=_a$1.Identify,Modify$3=_a$1.Modify,Login$2=_a$1.Login,Logout$2=_a$1.Logout,HTTPCodes$3=Constants.HTTPCodes,Messages$9=Constants.Messages;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
559
555
|
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
560
556
|
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$3||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
561
557
|
// we sort the identities based on their enum.
|
|
@@ -684,7 +680,7 @@ var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go
|
|
|
684
680
|
// https://go.mparticle.com/work/SQDSDKS-4801
|
|
685
681
|
// sanitizes any non number, non string value to 0
|
|
686
682
|
this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.calculateProductActionTotalAmount=function(a){if(!a||null!=a.TotalAmount)return a;var b=0;return Array.isArray(a.ProductList)&&a.ProductList.forEach(function(a){b+=parseNumber(a.Quantity)*parseNumber(a.Price);}),b+=parseNumber(a.ShippingAmount)+parseNumber(a.TaxAmount),a.TotalAmount=b,a},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.ViewCart:return "ViewCart";case Types.ProductActionType.AddShippingInfo:return "AddShippingInfo";case Types.ProductActionType.AddPaymentInfo:return "AddPaymentInfo";case Types.ProductActionType.PaymentMethodSelected:return "PaymentMethodSelected";case Types.ProductActionType.PaymentAttempted:return "PaymentAttempted";case Types.ProductActionType.PaymentSucceeded:return "PaymentSucceeded";case Types.ProductActionType.PaymentFailed:return "PaymentFailed";case Types.ProductActionType.RefundInitiated:return "RefundInitiated";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:b===Types.ProductActionType.ViewCart||b===Types.ProductActionType.AddShippingInfo||b===Types.ProductActionType.AddPaymentInfo||b===Types.ProductActionType.PaymentMethodSelected||b===Types.ProductActionType.PaymentAttempted||b===Types.ProductActionType.PaymentSucceeded||b===Types.ProductActionType.PaymentFailed||b===Types.ProductActionType.RefundInitiated?Types.EventType.Unknown:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801
|
|
687
|
-
return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof
|
|
683
|
+
return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
|
|
688
684
|
return a._Helpers.parseNumber(b)};}
|
|
689
685
|
|
|
690
686
|
var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window
|
|
@@ -696,7 +692,7 @@ function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
|
696
692
|
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access
|
|
697
693
|
return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
|
|
698
694
|
function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model
|
|
699
|
-
persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof
|
|
695
|
+
persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
|
|
700
696
|
(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
|
|
701
697
|
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.getTimeOnSite=function(){var a;return null===(a=b._timeOnSiteTimer)||void 0===a?void 0:a.getTimeInForeground()},this.getTotalTimeOnSite=function(){return d.sessionStartDate?Date.now()-d.sessionStartDate.getTime():void 0},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g=a.workspaceToken,h=a.requiredWebviewBridgeName;// We should reprocess the flags and baseUrls in case they have changed when we request an updated config
|
|
702
698
|
// such as if the SDK is being self-hosted and the flags are different on the server config
|
|
@@ -734,13 +730,22 @@ if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];els
|
|
|
734
730
|
|
|
735
731
|
var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.isVerbose=function(){return this.logLevel===LogLevelType.Verbose},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}();
|
|
736
732
|
|
|
737
|
-
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){
|
|
738
|
-
//
|
|
739
|
-
//
|
|
740
|
-
//
|
|
741
|
-
|
|
742
|
-
//
|
|
743
|
-
|
|
733
|
+
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function getMParticleManager(){return window.mParticle}function _Persistence(a){function b(b,c){return b||c?void(a._Store.isFirstRun=!1):(a._Store.isFirstRun=!0,void(a._Store.mpid=0))}function c(a,b){return a&&b?extend(!1,a,b):a||b}// For migrating from localStorage to cookies -- If an instance switches from
|
|
734
|
+
// localStorage to cookies, then no mParticle cookie exists yet and there is
|
|
735
|
+
// localStorage. Get the localStorage, set them to cookies, then delete the
|
|
736
|
+
// localStorage item.
|
|
737
|
+
function d(b,d,e){var f;return d?(f=c(d,e),b.removeItem(a._Store.storageName)):e&&(f=e),E.storeDataInMemory(f),f}// For migrating from cookie to localStorage -- If an instance is newly
|
|
738
|
+
// switching from cookies to localStorage, then no mParticle localStorage
|
|
739
|
+
// exists yet and there are cookies. Get the cookies, set them to
|
|
740
|
+
// localStorage, then delete the cookies.
|
|
741
|
+
function e(b,d){if(!d)return void E.storeDataInMemory(b);var e=c(b,d);return E.storeDataInMemory(e),E.expireCookies(a._Store.storageName),e}function f(b,c){return a._Store.isLocalStorageAvailable?a._Store.SDKConfig.useCookieStorage?d(window.localStorage,b,c):e(b,c):void E.storeDataInMemory(c)}function g(b){for(var c in b)b.hasOwnProperty(c)&&!SDKv2NonMPIDCookieKeys[c]&&(a._Store.nonCurrentUserMPIDs[c]=b[c]);}function h(){return E.useLocalStorage()&&a._Store.isLocalStorageAvailable?void localStorage.removeItem(a._Store.storageName):void E.expireCookies(a._Store.storageName)}function i(){a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId();}function j(b,c){// For most persistence values, we prioritize localstorage/cookie values over
|
|
742
|
+
// Store. However, we allow device ID to be overriden via a config value and
|
|
743
|
+
// thus the priority of the deviceId value is
|
|
744
|
+
// 1. value passed via config.deviceId
|
|
745
|
+
// 2. previous value in persistence
|
|
746
|
+
// 3. generate new guid
|
|
747
|
+
a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu];}// https://go.mparticle.com/work/SQDSDKS-6045
|
|
748
|
+
function k(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}/* This function determines if a cookie is greater than the configured maxCookieSize.
|
|
744
749
|
- If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.
|
|
745
750
|
- Once removed, check size, and repeat.
|
|
746
751
|
- Never remove the currentUser's MPID from the cookie.
|
|
@@ -751,8 +756,15 @@ var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Consta
|
|
|
751
756
|
a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs
|
|
752
757
|
b. Then remove MPIDs based on order in currentSessionMPIDs array, which
|
|
753
758
|
stores MPIDs based on earliest login.
|
|
754
|
-
*/
|
|
759
|
+
*/function l(a,b){return a.length>b}function m(a,b,c,d){var e;for(var f in a)a.hasOwnProperty(f)&&(e=r(a,b,c),!!l(e,d))&&(SDKv2NonMPIDCookieKeys[f]||f===a.cu||delete a[f]);return e}function n(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(SDKv2NonMPIDCookieKeys[c]||c===a.cu||(b[c]=1));return b}function o(a,b,c,d,e,f){var g;for(var h in b)(g=r(a,d,e),!!l(g,f))&&b.hasOwnProperty(h)&&-1===c.indexOf(h)&&delete a[h];return g}function p(b,c,d){return b[c]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+d+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[c],null,2)),void delete b[c]):void a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+d+". We recommend using a maxCookieSize of 1500.")}function q(a,b,c,d,e){for(var f,g=0;g<b.length&&(f=r(a,c,d),!!l(f,e));g++)p(a,b[g],e);return f}function r(a,b,c){return E.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}function s(a,b,c){for(var d in a)if(b===d&&c===a[d])return !0;return !1}function t(a,b,c){var d;for(var e in a)// any value in persistence that has an MPID key will be an MPID to search through
|
|
760
|
+
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
|
|
761
|
+
a[e].mpid&&s(a[e].ui,b,c)&&(d=e);return d}function u(a,b){var c;for(var d in b.userIdentities)if(a&&Object.keys(a).length){var e=t(a,d,b.userIdentities[d]);e&&(c=e);}return c}function v(b){return Array.isArray(b)?0<b.length:!!a._Helpers.isObject(b)&&0<Object.keys(b).length}function w(a,b){return a[b]&&v(a[b])?void(a[b]=Base64.encode(JSON.stringify(a[b]))):void delete a[b]}function x(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){w(a,b);continue}if("ie"==b){a[b]=a[b]?1:0;continue}a[b]||delete a[b];}}function y(b,c){var d=b[c];return a._Helpers.isObject(d)&&Object.keys(d).length?void(b[c]=Base64.encode(JSON.stringify(d))):void delete b[c]}function z(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&y(a,b);}function A(a){for(var b in a)a.hasOwnProperty(b)&&(SDKv2NonMPIDCookieKeys[b]||z(a[b]));}function B(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){a[b]=JSON.parse(Base64.decode(a[b]));continue}"ie"==b&&(a[b]=!!a[b]);}}function C(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&a[b].length&&(a[b]=JSON.parse(Base64.decode(a[b])));}function D(a){for(var b in a)if(a.hasOwnProperty(b)){if(!SDKv2NonMPIDCookieKeys[b]){C(a[b]);continue}"l"==b&&(a[b]=!!a[b]);}}// TODO: This should actually be decodePersistenceString or
|
|
755
762
|
// we should refactor this to take a string and return an object
|
|
763
|
+
var E=this;// https://go.mparticle.com/work/SQDSDKS-5022
|
|
764
|
+
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
765
|
+
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
766
|
+
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
767
|
+
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
756
768
|
// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
|
|
757
769
|
// For example subdomain.domain.co.uk would try the following combinations:
|
|
758
770
|
// "co.uk" -> fail
|
|
@@ -768,418 +780,142 @@ var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Consta
|
|
|
768
780
|
* time
|
|
769
781
|
*/ // https://go.mparticle.com/work/SQDSDKS-6045
|
|
770
782
|
// Forwarder Batching Code
|
|
771
|
-
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var
|
|
772
|
-
|
|
773
|
-
//
|
|
774
|
-
//
|
|
775
|
-
|
|
776
|
-
{var
|
|
777
|
-
if(!(null!==(
|
|
778
|
-
if(
|
|
779
|
-
var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
|
|
780
|
-
if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
|
|
781
|
-
for(var n,o=0;o<h.length&&(g=d(b,c,e),g.length>f);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through
|
|
782
|
-
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
|
|
783
|
-
if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<a.cookie.indexOf("mptest=cookie"))return a.cookie="mptest=;domain=."+d+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",d;return ""},this.saveUserCookieSyncDatesToPersistence=function(a,b){if(b){var c=f.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),f.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=f.getPersistence();d&&(d.cu=b,d.gs.csm=c,f.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
784
|
-
if(!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional())){var d,e=f.encodePersistence(JSON.stringify(b)),g=new Date,h=a._Store.storageName,i=new Date(g.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString(),j=f.getCookieDomain();if(d=""===j?"":";domain="+j,a._Store.SDKConfig.useCookieStorage){var k=f.reduceAndEncodePersistence(b,i,d,a._Store.SDKConfig.maxCookieSize);window.document.cookie=encodeURIComponent(h)+"="+k;}else if(a._Store.isLocalStorageAvailable)try{localStorage.setItem(a._Store.storageName,e);}catch(b){a.Logger.error("Error saving persistence to localStorage.");}}},this.getPersistence=function(){var a=this.useLocalStorage()?this.getLocalStorage():this.getCookie();return a},this.getFirstSeenTime=function(a){if(!a)return null;var b=f.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=f.getPersistence();c&&(!c[a]&&(c[a]={}),!c[a].fst&&(c[a].fst=b,f.savePersistence(c)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
783
|
+
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var c=E.getLocalStorage(),d=E.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045
|
|
784
|
+
b(c,d),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0);// https://go.mparticle.com/work/SQDSDKS-6046
|
|
785
|
+
var e=f(c,d);g(e),E.update();}catch(b){// If cookies or local storage is corrupt, we want to remove it
|
|
786
|
+
// so that in the future, initializeStorage will work
|
|
787
|
+
h(),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&E.setCookie(),E.setLocalStorage());},this.storeDataInMemory=function(b,c){try{if(!b)return void i();j(b,c);}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b=getMParticleManager();if(null===b||void 0===b?void 0:b._forceNoLocalStorage)return !1;try{a.setItem("mparticle","test");var c="test"===a.getItem("mparticle");return a.removeItem("mparticle"),!!(c&&a)}catch(a){return !1}},this.setLocalStorage=function(){var b;if(a._Store.isLocalStorageAvailable&&(null===(b=a._CookieConsentManager)||void 0===b||!b.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true
|
|
788
|
+
{var c=a._Store.storageName,d=E.getLocalStorage()||{},e=a.Identity.getCurrentUser(),f=e?e.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){d.gs=d.gs||{},d.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(d.gs.csm=a._Store.currentSessionMPIDs),d.gs.ie=a._Store.isEnabled,f&&(d.cu=f),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(d=extend({},d,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),d=k(d);try{window.localStorage.setItem(encodeURIComponent(c),E.encodePersistence(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b=a._Store.storageName,c=E.decodePersistence(window.localStorage.getItem(b));if(!c)return null;var d=JSON.parse(c),e={};for(var f in d)d.hasOwnProperty(f)&&(e[f]=d[f]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=E.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,f,g,h=a._Store.storageName,j=h?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;c<d;c++){try{e=b[c].split("="),f=e.shift(),g=e.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+f+". Skipping.");}if(h&&h===f){j=a._Helpers.converted(g);break}h||(j[f]=a._Helpers.converted(g));}return j?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(E.decodePersistence(j))):null},this.setCookie=function(){var b;// Block mprtcl-v4 cookies when noFunctional is true
|
|
789
|
+
if(!(null!==(b=a._CookieConsentManager)&&void 0!==b)||!b.getNoFunctional()){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,f,g,h=new Date,i=a._Store.storageName,j=E.getCookie()||{},l=new Date(h.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toUTCString();e=E.getCookieDomain(),f=""===e?"":";domain="+e,j.gs=j.gs||{},a._Store.sessionId&&(j.gs.csm=a._Store.currentSessionMPIDs),c&&(j.cu=c),j.l=a._Store.isLoggedIn?1:0,j=k(j),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(j=extend({},j,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),g=E.reduceAndEncodePersistence(j,l,f,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(i)+"="+g;}},this.reduceAndEncodePersistence=function(a,b,c,d){var e=a.gs.csm?a.gs.csm:[];if(!e.length)return m(a,b,c,d);var f=n(a);return Object.keys(f).length&&o(a,f,e,b,c,d),q(a,e,b,c,d)},this.findPrevCookiesBasedOnUI=function(b){var c=a._Persistence.getPersistence();if(b){var d=u(c,b);d&&E.storeDataInMemory(c,d);}},this.encodePersistence=function(a){var b=JSON.parse(a);return x(b.gs),A(b),createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(!b)return;var c=JSON.parse(revertCookieString(b));return a._Helpers.isObject(c)&&Object.keys(c).length&&(B(c.gs),D(c)),JSON.stringify(c)}catch(b){a.Logger.error("Problem with decoding cookie");}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=E.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<a.cookie.indexOf("mptest=cookie"))return a.cookie="mptest=;domain=."+d+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",d;return ""},this.saveUserCookieSyncDatesToPersistence=function(a,b){if(b){var c=E.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),E.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=E.getPersistence();d&&(d.cu=b,d.gs.csm=c,E.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
790
|
+
if(null===(c=a._CookieConsentManager)||void 0===c||!c.getNoFunctional()){var d,e=E.encodePersistence(JSON.stringify(b)),f=new Date,g=a._Store.storageName,h=new Date(f.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toUTCString(),i=E.getCookieDomain();if(d=""===i?"":";domain="+i,a._Store.SDKConfig.useCookieStorage){var j=E.reduceAndEncodePersistence(b,h,d,a._Store.SDKConfig.maxCookieSize);window.document.cookie=encodeURIComponent(g)+"="+j;}else if(a._Store.isLocalStorageAvailable)try{localStorage.setItem(a._Store.storageName,e);}catch(b){a.Logger.error("Error saving persistence to localStorage.");}}},this.getPersistence=function(){var a=this.useLocalStorage()?this.getLocalStorage():this.getCookie();return a},this.getFirstSeenTime=function(a){if(!a)return null;var b=E.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=E.getPersistence();c&&(!c[a]&&(c[a]={}),!c[a].fst&&(c[a].fst=b,E.savePersistence(c)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
785
791
|
},this.getLastSeenTime=function(b){if(!b)return null;if(b===a.Identity.getCurrentUser().getMPID())//if the mpid is the current user, its last seen time is the current time
|
|
786
|
-
return new Date().getTime();var c=
|
|
787
|
-
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,
|
|
792
|
+
return new Date().getTime();var c=E.getPersistence();return c&&c[b]&&c[b].lst?c[b].lst:null},this.setLastSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=E.getPersistence();c&&c[a]&&(c[a].lst=b,E.savePersistence(c));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
793
|
+
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,E.update();},this.resetPersistence=function(){localStorage.clear(),E.expireCookies(StorageNames.cookieName),E.expireCookies(StorageNames.cookieNameV2),E.expireCookies(StorageNames.cookieNameV3),E.expireCookies(StorageNames.cookieNameV4),E.expireCookies(a._Store.storageName);var b=getMParticleManager();if(null===b||void 0===b?void 0:b._isTestEnv){localStorage.removeItem(a._Helpers.createMainStorageName("abcdef")),E.expireCookies(a._Helpers.createMainStorageName("abcdef"));}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]};}
|
|
794
|
+
|
|
795
|
+
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";// All APV state hangs off one window key, and it is the public debugging
|
|
796
|
+
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
797
|
+
// tracking is live.
|
|
798
|
+
//
|
|
799
|
+
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
800
|
+
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
801
|
+
// but `window` persists for the lifetime of the tab.
|
|
802
|
+
//
|
|
803
|
+
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
804
|
+
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
805
|
+
// survives the reset.
|
|
806
|
+
var WIN_APV_KEY="__mpApv__";// The query params an auto page view may carry. An allowlist, not a denylist:
|
|
807
|
+
// partner URLs routinely hold order ids, email addresses and session tokens, and
|
|
808
|
+
// none of those should reach the event stream because someone forgot to exclude
|
|
809
|
+
// them. Anything absent from this list is dropped.
|
|
810
|
+
//
|
|
811
|
+
// SECURITY: `code`, `state` and `nonce` are the OAuth 2.0 / OIDC authorization
|
|
812
|
+
// code and the CSRF/replay tokens. They are credentials until redeemed, and
|
|
813
|
+
// attaching them here persists them in the event store and forwards them to
|
|
814
|
+
// every configured kit. They are on the list by explicit product decision —
|
|
815
|
+
// deleting that line is the whole of the fix if that decision is revisited.
|
|
816
|
+
var ALLOWED_QUERY_PARAMS=[// Campaign attribution
|
|
817
|
+
"utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id",// Ad-network click ids
|
|
818
|
+
"gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid",// OAuth / OIDC — see the SECURITY note above
|
|
819
|
+
"client_id","redirect_uri","response_type","scope","state","code","nonce",// Pagination and search
|
|
820
|
+
"page","limit","offset","cursor","per_page","q","search",// Referral
|
|
821
|
+
"ref","referrer"];// ---------------------------------------------------------------------------
|
|
822
|
+
// Pure helpers. No `this`, no globals, no side effects — callable and assertable
|
|
823
|
+
// on their own, which is where the interesting rules live.
|
|
824
|
+
// ---------------------------------------------------------------------------
|
|
825
|
+
// Pulls the allowlisted query params off a URL. Delegates to the SDK's own
|
|
826
|
+
// parser, which lowercases keys (so `?UTM_Source=` and `?utm_source=` land on one
|
|
827
|
+
// attribute), drops empty values, and carries the fallback for browsers without
|
|
828
|
+
// URLSearchParams. Tolerates an empty href, so SSR yields no params rather than
|
|
829
|
+
// throwing.
|
|
830
|
+
var allowedQueryParams=function(a){return queryStringParser(a,ALLOWED_QUERY_PARAMS)};// The captured params, in allowlist order. Ordering comes from the constant
|
|
831
|
+
// rather than a sort: it is deterministic without needing a comparator, and it
|
|
832
|
+
// does not depend on the object's insertion order, so reordering the query string
|
|
833
|
+
// cannot produce a different key.
|
|
834
|
+
var capturedNames=function(a){return ALLOWED_QUERY_PARAMS.filter(function(b){return b in a})};// The dedup key: pathname plus the allowlisted params in a fixed order, so that
|
|
835
|
+
// reordering the query string is not a new page. Params outside the allowlist
|
|
836
|
+
// never make it into `page.params` and so cannot key a view — nor can the hash.
|
|
837
|
+
//
|
|
838
|
+
// Values are re-encoded because queryStringParser hands them back DECODED. A
|
|
839
|
+
// value holding the pair delimiters would otherwise serialize exactly like two
|
|
840
|
+
// separate params — `{q: 'a&search=b'}` and `{q: 'a', search: 'b'}` both becoming
|
|
841
|
+
// `q=a&search=b` — and dedup would treat a real navigation between them as the
|
|
842
|
+
// same page and drop the view. `q`, `search` and `redirect_uri` carry `&` and `=`
|
|
843
|
+
// routinely, so this is reachable rather than theoretical.
|
|
844
|
+
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
|
|
845
|
+
// (`?page=2` is a distinct pagination view), while a hash-only change, or a
|
|
846
|
+
// change confined to params we do not capture, is the same page.
|
|
847
|
+
var isNewPage=function(a,b){return b!==a};var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
848
|
+
// path and query params captured when the navigation was accepted rather than the
|
|
849
|
+
// live location.
|
|
850
|
+
var buildPageViewEvent=function(a){var b=a.params,c=a.hostname,d=a.title,e=a.path;return {messageType:MessageType$1.PageView,name:"PageView",// Params spread first, then the core fields by name, so a core field always
|
|
851
|
+
// wins. No allowlist entry collides with hostname/title/path today; naming
|
|
852
|
+
// them here is what keeps a later addition from silently overwriting one.
|
|
853
|
+
data:__assign(__assign({},b),{hostname:c,title:d,path:e}),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
854
|
+
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
855
|
+
// neither the tracker nor mp-instance touches `window` directly and
|
|
856
|
+
// `typeof window` is checked in exactly one place.
|
|
857
|
+
// ---------------------------------------------------------------------------
|
|
858
|
+
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
|
|
859
|
+
// writers below create it.
|
|
860
|
+
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
|
|
861
|
+
// history methods it patched), then swaps in fresh state. The state object is the
|
|
862
|
+
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
863
|
+
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};// Log-safe description of a page: the path, plus the NAMES of the captured
|
|
864
|
+
// params. Values are deliberately omitted — verbose logging goes to the console,
|
|
865
|
+
// and session-replay tooling ships console output off-domain, which is not a
|
|
866
|
+
// place for an OAuth code or a consumer's search terms.
|
|
867
|
+
// Only reachable before init() assigns lastPage, which is ahead of any navigation
|
|
868
|
+
// handler being able to run, so this returns nothing rather than a sentinel.
|
|
869
|
+
// ---------------------------------------------------------------------------
|
|
870
|
+
// History patching
|
|
871
|
+
// ---------------------------------------------------------------------------
|
|
872
|
+
// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
873
|
+
// returns the single function that undoes it — or null when nothing was
|
|
874
|
+
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
875
|
+
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
876
|
+
// references out of the tracker entirely: there is no half-patched state for a
|
|
877
|
+
// caller to inspect, and no way to restore the wrong pair.
|
|
878
|
+
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
|
|
879
|
+
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
880
|
+
// leave anything that is no longer ours in place.
|
|
881
|
+
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};// ---------------------------------------------------------------------------
|
|
882
|
+
// Tracker
|
|
883
|
+
// ---------------------------------------------------------------------------
|
|
884
|
+
var PageViewTracker=/** @class */function(){function a(a){this.lastPage=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.popStateListener=null,this.mpInstance=a;}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
885
|
+
// navigations. Flips to false on teardown, including the teardown a
|
|
886
|
+
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
887
|
+
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
888
|
+
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
|
|
889
|
+
// a previous module load, or this same tracker on a repeat
|
|
890
|
+
// mParticle.init(). Their pending navigations are transferred rather than
|
|
891
|
+
// dropped — a route change may have queued a deferred fire that has not
|
|
892
|
+
// flushed yet, and dropping it loses a page view entirely.
|
|
893
|
+
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=patchHistory(function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),this.popStateListener=function(){return a.safeHandleNavigation("popstate")},window.addEventListener("popstate",this.popStateListener),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.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),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
|
|
894
|
+
// method that is still ours, so one a third party patched over stays
|
|
895
|
+
// installed and keeps firing at a dead tracker. Bail before touching
|
|
896
|
+
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
897
|
+
// rather than at each wrapper also covers the popstate path.
|
|
898
|
+
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}));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}();
|
|
788
899
|
|
|
789
|
-
var Messages$3=Constants.Messages;function Events(a){var b=this
|
|
900
|
+
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
|
|
901
|
+
// come from PageViewTracker instead, so both emitters attach the same
|
|
902
|
+
// allowlisted query params — and this is the one that matters for campaign
|
|
903
|
+
// attribution, since utm_*/gclid live on the entry URL.
|
|
904
|
+
this.logEvent=function(b,c){if(a.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent+": "+b.name),a._Helpers.canLog()){var d=a._ServerModel.createEventObject(b);a._APIClient.sendEventToServer(d,c);}else a.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);},this.startTracking=function(b){function c(b,c){if(b)try{c?b(c):b();}catch(b){a.Logger.error("Error invoking the callback passed to startTrackingLocation."),a.Logger.error(b);}}if(!a._Store.isTracking)"geolocation"in navigator&&(a._Store.watchPositionId=navigator.geolocation.watchPosition(function e(d){// prevents callback from being fired multiple times
|
|
790
905
|
a._Store.currentPosition={lat:d.coords.latitude,lng:d.coords.longitude},c(b,d),b=null,a._Store.isTracking=!0;},function d(){// prevents callback from being fired multiple times
|
|
791
|
-
c(b),b=null,a._Store.isTracking=!1;}));else {var d={coords:{latitude:a._Store.currentPosition.lat,longitude:a._Store.currentPosition.lng}};c(b,d);}},this.stopTracking=function(){a._Store.isTracking&&(navigator.geolocation.clearWatch(a._Store.watchPositionId),a._Store.currentPosition=null,a._Store.isTracking=!1);},this.logOptOut=function(){a.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut);var b=a._ServerModel.createEventObject({messageType:Types.MessageType.OptOut,eventType:Types.EventType.Other});a._APIClient.sendEventToServer(b);},this.logAST=function(){b.logEvent({messageType:Types.MessageType.AppStateTransition});},this.logPageView=function(){b.logEvent({messageType:Types.MessageType.PageView,name:"PageView",data:{hostname:window.location.hostname,title:window.document.title},eventType:Types.EventType.Unknown});},this.logCheckoutEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout),g.EventCategory=Types.CommerceEventType.ProductCheckout,g.ProductAction={ProductActionType:Types.ProductActionType.Checkout,CheckoutStep:c,CheckoutOptions:d,ProductList:[]},b.logCommerceEvent(g,e));},this.logProductActionEvent=function(c,d,e,f,g,h){var i=a._Ecommerce.createCommerceEventObject(f,h),j=Array.isArray(d)?d:[d];j.forEach(function(b){b.TotalAmount&&(b.TotalAmount=a._Ecommerce.sanitizeAmount(b.TotalAmount,"TotalAmount")),b.Position&&(b.Position=a._Ecommerce.sanitizeAmount(b.Position,"Position")),b.Price&&(b.Price=a._Ecommerce.sanitizeAmount(b.Price,"Price")),b.Quantity&&(b.Quantity=a._Ecommerce.sanitizeAmount(b.Quantity,"Quantity"));}),i&&(i.EventCategory=a._Ecommerce.convertProductActionToEventType(c),i.EventName+=a._Ecommerce.getProductActionEventName(c),i.ProductAction={ProductActionType:c,ProductList:j},Types.ProductActionType.isRoktCommerceType(c)&&(i.CustomFlags=i.CustomFlags||{},i.CustomFlags["Rokt.CommerceEventType"]=Types.ProductActionType.getExpansionName(c)),a._Helpers.isObject(g)&&a._Ecommerce.convertTransactionAttributesToProductAction(g,i.ProductAction),b.logCommerceEvent(i,e,h));},this.logPurchaseEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase),g.EventCategory=Types.CommerceEventType.ProductPurchase,g.ProductAction={ProductActionType:Types.ProductActionType.Purchase},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logRefundEvent=function(c,d,e,f){if(!c)return void a.Logger.error(Messages$3.ErrorMessages.TransactionRequired);var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund),g.EventCategory=Types.CommerceEventType.ProductRefund,g.ProductAction={ProductActionType:Types.ProductActionType.Refund},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logPromotionEvent=function(c,d,e,f,g){var h=a._Ecommerce.createCommerceEventObject(f);h&&(h.EventName+=a._Ecommerce.getPromotionActionEventName(c),h.EventCategory=a._Ecommerce.convertPromotionActionToEventType(c),h.PromotionAction={PromotionActionType:c,PromotionList:Array.isArray(d)?d:[d]},b.logCommerceEvent(h,e,g));},this.logImpressionEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(e);g&&(g.EventName+="Impression",g.EventCategory=Types.CommerceEventType.ProductImpression,!Array.isArray(c)&&(c=[c]),g.ProductImpressions=[],c.forEach(function(a){g.ProductImpressions.push({ProductImpressionList:a.Name,ProductList:Array.isArray(a.Product)?a.Product:[a.Product]});}),b.logCommerceEvent(g,d,f));},this.logCommerceEvent=function(b,c,d){// If a developer typos the ProductActionType, the event category will be
|
|
906
|
+
c(b),b=null,a._Store.isTracking=!1;}));else {var d={coords:{latitude:a._Store.currentPosition.lat,longitude:a._Store.currentPosition.lng}};c(b,d);}},this.stopTracking=function(){a._Store.isTracking&&(navigator.geolocation.clearWatch(a._Store.watchPositionId),a._Store.currentPosition=null,a._Store.isTracking=!1);},this.logOptOut=function(){a.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut);var b=a._ServerModel.createEventObject({messageType:Types.MessageType.OptOut,eventType:Types.EventType.Other});a._APIClient.sendEventToServer(b);},this.logAST=function(){b.logEvent({messageType:Types.MessageType.AppStateTransition});},this.logPageView=function(){b.logEvent({messageType:Types.MessageType.PageView,name:"PageView",data:__assign(__assign({},allowedQueryParams(getHref())),{hostname:window.location.hostname,title:window.document.title}),eventType:Types.EventType.Unknown});},this.logCheckoutEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout),g.EventCategory=Types.CommerceEventType.ProductCheckout,g.ProductAction={ProductActionType:Types.ProductActionType.Checkout,CheckoutStep:c,CheckoutOptions:d,ProductList:[]},b.logCommerceEvent(g,e));},this.logProductActionEvent=function(c,d,e,f,g,h){var i=a._Ecommerce.createCommerceEventObject(f,h),j=Array.isArray(d)?d:[d];j.forEach(function(b){b.TotalAmount&&(b.TotalAmount=a._Ecommerce.sanitizeAmount(b.TotalAmount,"TotalAmount")),b.Position&&(b.Position=a._Ecommerce.sanitizeAmount(b.Position,"Position")),b.Price&&(b.Price=a._Ecommerce.sanitizeAmount(b.Price,"Price")),b.Quantity&&(b.Quantity=a._Ecommerce.sanitizeAmount(b.Quantity,"Quantity"));}),i&&(i.EventCategory=a._Ecommerce.convertProductActionToEventType(c),i.EventName+=a._Ecommerce.getProductActionEventName(c),i.ProductAction={ProductActionType:c,ProductList:j},Types.ProductActionType.isRoktCommerceType(c)&&(i.CustomFlags=i.CustomFlags||{},i.CustomFlags["Rokt.CommerceEventType"]=Types.ProductActionType.getExpansionName(c)),a._Helpers.isObject(g)&&a._Ecommerce.convertTransactionAttributesToProductAction(g,i.ProductAction),b.logCommerceEvent(i,e,h));},this.logPurchaseEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase),g.EventCategory=Types.CommerceEventType.ProductPurchase,g.ProductAction={ProductActionType:Types.ProductActionType.Purchase},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logRefundEvent=function(c,d,e,f){if(!c)return void a.Logger.error(Messages$3.ErrorMessages.TransactionRequired);var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund),g.EventCategory=Types.CommerceEventType.ProductRefund,g.ProductAction={ProductActionType:Types.ProductActionType.Refund},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logPromotionEvent=function(c,d,e,f,g){var h=a._Ecommerce.createCommerceEventObject(f);h&&(h.EventName+=a._Ecommerce.getPromotionActionEventName(c),h.EventCategory=a._Ecommerce.convertPromotionActionToEventType(c),h.PromotionAction={PromotionActionType:c,PromotionList:Array.isArray(d)?d:[d]},b.logCommerceEvent(h,e,g));},this.logImpressionEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(e);g&&(g.EventName+="Impression",g.EventCategory=Types.CommerceEventType.ProductImpression,!Array.isArray(c)&&(c=[c]),g.ProductImpressions=[],c.forEach(function(a){g.ProductImpressions.push({ProductImpressionList:a.Name,ProductList:Array.isArray(a.Product)?a.Product:[a.Product]});}),b.logCommerceEvent(g,d,f));},this.logCommerceEvent=function(b,c,d){// If a developer typos the ProductActionType, the event category will be
|
|
792
907
|
// null, resulting in kit forwarding errors on the server.
|
|
793
908
|
// The check for `ProductAction` is required to denote that these are
|
|
794
909
|
// ProductAction events, and not impression or promotions
|
|
795
910
|
if(a.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent),b.ProductAction&&null===b.EventCategory)return void a.Logger.error("Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code.");var e=a._Helpers.sanitizeAttributes(c,b.EventName);a._Helpers.canLog()?(a._Store.webviewBridgeEnabled&&(b.ShoppingCart={}),e&&(b.EventAttributes=e),b.ProductAction&&a._Ecommerce.calculateProductActionTotalAmount(b.ProductAction),a._APIClient.sendEventToServer(b,d),a._Persistence.update()):a.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);},this.addEventHandler=function(c,d,f,g,h){var j,k,e=[],l=function handler(c){var d=function timeoutHandler(){j.href?window.location.href=j.href:j.submit&&j.submit();};a.Logger.verbose("DOM event triggered, handling event"),b.logEvent({messageType:Types.MessageType.PageEvent,name:"function"==typeof f?f(j):f,data:"function"==typeof g?g(j):g,eventType:h||Types.EventType.Other}),(j.href&&"_blank"!==j.target||j.submit)&&(c.preventDefault?c.preventDefault():c.returnValue=!1,setTimeout(d,a._Store.SDKConfig.timeout));};if(!d)return void a.Logger.error("Can't bind event, selector is required");// Handle a css selector string or a dom element
|
|
796
911
|
if("string"==typeof d?e=document.querySelectorAll(d):d.nodeType&&(e=[d]),e.length)for(a.Logger.verbose("Found "+e.length+" element"+(1<e.length?"s":"")+", attaching event handlers"),k=0;k<e.length;k++)j=e[k],j.addEventListener?j.addEventListener(c,l,!1):j.attachEvent?j.attachEvent("on"+c,l):j["on"+c]=l;else a.Logger.verbose("No elements found");};}
|
|
797
912
|
|
|
798
|
-
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
799
|
-
try {
|
|
800
|
-
var info = gen[key](arg);
|
|
801
|
-
var value = info.value;
|
|
802
|
-
} catch (error) {
|
|
803
|
-
reject(error);
|
|
804
|
-
return;
|
|
805
|
-
}
|
|
806
|
-
if (info.done) {
|
|
807
|
-
resolve(value);
|
|
808
|
-
} else {
|
|
809
|
-
Promise.resolve(value).then(_next, _throw);
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
function _asyncToGenerator(fn) {
|
|
813
|
-
return function () {
|
|
814
|
-
var self = this,
|
|
815
|
-
args = arguments;
|
|
816
|
-
return new Promise(function (resolve, reject) {
|
|
817
|
-
var gen = fn.apply(self, args);
|
|
818
|
-
function _next(value) {
|
|
819
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
820
|
-
}
|
|
821
|
-
function _throw(err) {
|
|
822
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
823
|
-
}
|
|
824
|
-
_next(undefined);
|
|
825
|
-
});
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
var regeneratorRuntime$1 = {exports: {}};
|
|
830
|
-
|
|
831
|
-
var _typeof = {exports: {}};
|
|
832
|
-
|
|
833
|
-
_typeof.exports;
|
|
834
|
-
|
|
835
|
-
(function (module) {
|
|
836
|
-
function _typeof(o) {
|
|
837
|
-
"@babel/helpers - typeof";
|
|
838
|
-
|
|
839
|
-
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
840
|
-
return typeof o;
|
|
841
|
-
} : function (o) {
|
|
842
|
-
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
843
|
-
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
|
|
844
|
-
}
|
|
845
|
-
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
|
846
|
-
} (_typeof));
|
|
847
|
-
|
|
848
|
-
var _typeofExports = _typeof.exports;
|
|
849
|
-
|
|
850
|
-
regeneratorRuntime$1.exports;
|
|
851
|
-
|
|
852
|
-
(function (module) {
|
|
853
|
-
var _typeof = _typeofExports["default"];
|
|
854
|
-
function _regeneratorRuntime() {
|
|
855
|
-
module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
|
|
856
|
-
return e;
|
|
857
|
-
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
|
858
|
-
var t,
|
|
859
|
-
e = {},
|
|
860
|
-
r = Object.prototype,
|
|
861
|
-
n = r.hasOwnProperty,
|
|
862
|
-
o = Object.defineProperty || function (t, e, r) {
|
|
863
|
-
t[e] = r.value;
|
|
864
|
-
},
|
|
865
|
-
i = "function" == typeof Symbol ? Symbol : {},
|
|
866
|
-
a = i.iterator || "@@iterator",
|
|
867
|
-
c = i.asyncIterator || "@@asyncIterator",
|
|
868
|
-
u = i.toStringTag || "@@toStringTag";
|
|
869
|
-
function define(t, e, r) {
|
|
870
|
-
return Object.defineProperty(t, e, {
|
|
871
|
-
value: r,
|
|
872
|
-
enumerable: !0,
|
|
873
|
-
configurable: !0,
|
|
874
|
-
writable: !0
|
|
875
|
-
}), t[e];
|
|
876
|
-
}
|
|
877
|
-
try {
|
|
878
|
-
define({}, "");
|
|
879
|
-
} catch (t) {
|
|
880
|
-
define = function define(t, e, r) {
|
|
881
|
-
return t[e] = r;
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
function wrap(t, e, r, n) {
|
|
885
|
-
var i = e && e.prototype instanceof Generator ? e : Generator,
|
|
886
|
-
a = Object.create(i.prototype),
|
|
887
|
-
c = new Context(n || []);
|
|
888
|
-
return o(a, "_invoke", {
|
|
889
|
-
value: makeInvokeMethod(t, r, c)
|
|
890
|
-
}), a;
|
|
891
|
-
}
|
|
892
|
-
function tryCatch(t, e, r) {
|
|
893
|
-
try {
|
|
894
|
-
return {
|
|
895
|
-
type: "normal",
|
|
896
|
-
arg: t.call(e, r)
|
|
897
|
-
};
|
|
898
|
-
} catch (t) {
|
|
899
|
-
return {
|
|
900
|
-
type: "throw",
|
|
901
|
-
arg: t
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
e.wrap = wrap;
|
|
906
|
-
var h = "suspendedStart",
|
|
907
|
-
l = "suspendedYield",
|
|
908
|
-
f = "executing",
|
|
909
|
-
s = "completed",
|
|
910
|
-
y = {};
|
|
911
|
-
function Generator() {}
|
|
912
|
-
function GeneratorFunction() {}
|
|
913
|
-
function GeneratorFunctionPrototype() {}
|
|
914
|
-
var p = {};
|
|
915
|
-
define(p, a, function () {
|
|
916
|
-
return this;
|
|
917
|
-
});
|
|
918
|
-
var d = Object.getPrototypeOf,
|
|
919
|
-
v = d && d(d(values([])));
|
|
920
|
-
v && v !== r && n.call(v, a) && (p = v);
|
|
921
|
-
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
|
|
922
|
-
function defineIteratorMethods(t) {
|
|
923
|
-
["next", "throw", "return"].forEach(function (e) {
|
|
924
|
-
define(t, e, function (t) {
|
|
925
|
-
return this._invoke(e, t);
|
|
926
|
-
});
|
|
927
|
-
});
|
|
928
|
-
}
|
|
929
|
-
function AsyncIterator(t, e) {
|
|
930
|
-
function invoke(r, o, i, a) {
|
|
931
|
-
var c = tryCatch(t[r], t, o);
|
|
932
|
-
if ("throw" !== c.type) {
|
|
933
|
-
var u = c.arg,
|
|
934
|
-
h = u.value;
|
|
935
|
-
return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
|
|
936
|
-
invoke("next", t, i, a);
|
|
937
|
-
}, function (t) {
|
|
938
|
-
invoke("throw", t, i, a);
|
|
939
|
-
}) : e.resolve(h).then(function (t) {
|
|
940
|
-
u.value = t, i(u);
|
|
941
|
-
}, function (t) {
|
|
942
|
-
return invoke("throw", t, i, a);
|
|
943
|
-
});
|
|
944
|
-
}
|
|
945
|
-
a(c.arg);
|
|
946
|
-
}
|
|
947
|
-
var r;
|
|
948
|
-
o(this, "_invoke", {
|
|
949
|
-
value: function value(t, n) {
|
|
950
|
-
function callInvokeWithMethodAndArg() {
|
|
951
|
-
return new e(function (e, r) {
|
|
952
|
-
invoke(t, n, e, r);
|
|
953
|
-
});
|
|
954
|
-
}
|
|
955
|
-
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
|
|
956
|
-
}
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
function makeInvokeMethod(e, r, n) {
|
|
960
|
-
var o = h;
|
|
961
|
-
return function (i, a) {
|
|
962
|
-
if (o === f) throw new Error("Generator is already running");
|
|
963
|
-
if (o === s) {
|
|
964
|
-
if ("throw" === i) throw a;
|
|
965
|
-
return {
|
|
966
|
-
value: t,
|
|
967
|
-
done: !0
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
for (n.method = i, n.arg = a;;) {
|
|
971
|
-
var c = n.delegate;
|
|
972
|
-
if (c) {
|
|
973
|
-
var u = maybeInvokeDelegate(c, n);
|
|
974
|
-
if (u) {
|
|
975
|
-
if (u === y) continue;
|
|
976
|
-
return u;
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
|
|
980
|
-
if (o === h) throw o = s, n.arg;
|
|
981
|
-
n.dispatchException(n.arg);
|
|
982
|
-
} else "return" === n.method && n.abrupt("return", n.arg);
|
|
983
|
-
o = f;
|
|
984
|
-
var p = tryCatch(e, r, n);
|
|
985
|
-
if ("normal" === p.type) {
|
|
986
|
-
if (o = n.done ? s : l, p.arg === y) continue;
|
|
987
|
-
return {
|
|
988
|
-
value: p.arg,
|
|
989
|
-
done: n.done
|
|
990
|
-
};
|
|
991
|
-
}
|
|
992
|
-
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
|
|
993
|
-
}
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
function maybeInvokeDelegate(e, r) {
|
|
997
|
-
var n = r.method,
|
|
998
|
-
o = e.iterator[n];
|
|
999
|
-
if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
|
|
1000
|
-
var i = tryCatch(o, e.iterator, r.arg);
|
|
1001
|
-
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
|
|
1002
|
-
var a = i.arg;
|
|
1003
|
-
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
|
|
1004
|
-
}
|
|
1005
|
-
function pushTryEntry(t) {
|
|
1006
|
-
var e = {
|
|
1007
|
-
tryLoc: t[0]
|
|
1008
|
-
};
|
|
1009
|
-
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
|
|
1010
|
-
}
|
|
1011
|
-
function resetTryEntry(t) {
|
|
1012
|
-
var e = t.completion || {};
|
|
1013
|
-
e.type = "normal", delete e.arg, t.completion = e;
|
|
1014
|
-
}
|
|
1015
|
-
function Context(t) {
|
|
1016
|
-
this.tryEntries = [{
|
|
1017
|
-
tryLoc: "root"
|
|
1018
|
-
}], t.forEach(pushTryEntry, this), this.reset(!0);
|
|
1019
|
-
}
|
|
1020
|
-
function values(e) {
|
|
1021
|
-
if (e || "" === e) {
|
|
1022
|
-
var r = e[a];
|
|
1023
|
-
if (r) return r.call(e);
|
|
1024
|
-
if ("function" == typeof e.next) return e;
|
|
1025
|
-
if (!isNaN(e.length)) {
|
|
1026
|
-
var o = -1,
|
|
1027
|
-
i = function next() {
|
|
1028
|
-
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
|
|
1029
|
-
return next.value = t, next.done = !0, next;
|
|
1030
|
-
};
|
|
1031
|
-
return i.next = i;
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
throw new TypeError(_typeof(e) + " is not iterable");
|
|
1035
|
-
}
|
|
1036
|
-
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
|
|
1037
|
-
value: GeneratorFunctionPrototype,
|
|
1038
|
-
configurable: !0
|
|
1039
|
-
}), o(GeneratorFunctionPrototype, "constructor", {
|
|
1040
|
-
value: GeneratorFunction,
|
|
1041
|
-
configurable: !0
|
|
1042
|
-
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
|
|
1043
|
-
var e = "function" == typeof t && t.constructor;
|
|
1044
|
-
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
|
|
1045
|
-
}, e.mark = function (t) {
|
|
1046
|
-
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
|
|
1047
|
-
}, e.awrap = function (t) {
|
|
1048
|
-
return {
|
|
1049
|
-
__await: t
|
|
1050
|
-
};
|
|
1051
|
-
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
|
|
1052
|
-
return this;
|
|
1053
|
-
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
|
|
1054
|
-
void 0 === i && (i = Promise);
|
|
1055
|
-
var a = new AsyncIterator(wrap(t, r, n, o), i);
|
|
1056
|
-
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
|
|
1057
|
-
return t.done ? t.value : a.next();
|
|
1058
|
-
});
|
|
1059
|
-
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
|
|
1060
|
-
return this;
|
|
1061
|
-
}), define(g, "toString", function () {
|
|
1062
|
-
return "[object Generator]";
|
|
1063
|
-
}), e.keys = function (t) {
|
|
1064
|
-
var e = Object(t),
|
|
1065
|
-
r = [];
|
|
1066
|
-
for (var n in e) r.push(n);
|
|
1067
|
-
return r.reverse(), function next() {
|
|
1068
|
-
for (; r.length;) {
|
|
1069
|
-
var t = r.pop();
|
|
1070
|
-
if (t in e) return next.value = t, next.done = !1, next;
|
|
1071
|
-
}
|
|
1072
|
-
return next.done = !0, next;
|
|
1073
|
-
};
|
|
1074
|
-
}, e.values = values, Context.prototype = {
|
|
1075
|
-
constructor: Context,
|
|
1076
|
-
reset: function reset(e) {
|
|
1077
|
-
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
|
|
1078
|
-
},
|
|
1079
|
-
stop: function stop() {
|
|
1080
|
-
this.done = !0;
|
|
1081
|
-
var t = this.tryEntries[0].completion;
|
|
1082
|
-
if ("throw" === t.type) throw t.arg;
|
|
1083
|
-
return this.rval;
|
|
1084
|
-
},
|
|
1085
|
-
dispatchException: function dispatchException(e) {
|
|
1086
|
-
if (this.done) throw e;
|
|
1087
|
-
var r = this;
|
|
1088
|
-
function handle(n, o) {
|
|
1089
|
-
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
|
|
1090
|
-
}
|
|
1091
|
-
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
|
|
1092
|
-
var i = this.tryEntries[o],
|
|
1093
|
-
a = i.completion;
|
|
1094
|
-
if ("root" === i.tryLoc) return handle("end");
|
|
1095
|
-
if (i.tryLoc <= this.prev) {
|
|
1096
|
-
var c = n.call(i, "catchLoc"),
|
|
1097
|
-
u = n.call(i, "finallyLoc");
|
|
1098
|
-
if (c && u) {
|
|
1099
|
-
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
|
1100
|
-
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
|
1101
|
-
} else if (c) {
|
|
1102
|
-
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
|
1103
|
-
} else {
|
|
1104
|
-
if (!u) throw new Error("try statement without catch or finally");
|
|
1105
|
-
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
},
|
|
1110
|
-
abrupt: function abrupt(t, e) {
|
|
1111
|
-
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
|
|
1112
|
-
var o = this.tryEntries[r];
|
|
1113
|
-
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
|
|
1114
|
-
var i = o;
|
|
1115
|
-
break;
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
|
|
1119
|
-
var a = i ? i.completion : {};
|
|
1120
|
-
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
|
|
1121
|
-
},
|
|
1122
|
-
complete: function complete(t, e) {
|
|
1123
|
-
if ("throw" === t.type) throw t.arg;
|
|
1124
|
-
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
|
|
1125
|
-
},
|
|
1126
|
-
finish: function finish(t) {
|
|
1127
|
-
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
|
1128
|
-
var r = this.tryEntries[e];
|
|
1129
|
-
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
|
|
1130
|
-
}
|
|
1131
|
-
},
|
|
1132
|
-
"catch": function _catch(t) {
|
|
1133
|
-
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
|
1134
|
-
var r = this.tryEntries[e];
|
|
1135
|
-
if (r.tryLoc === t) {
|
|
1136
|
-
var n = r.completion;
|
|
1137
|
-
if ("throw" === n.type) {
|
|
1138
|
-
var o = n.arg;
|
|
1139
|
-
resetTryEntry(r);
|
|
1140
|
-
}
|
|
1141
|
-
return o;
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
throw new Error("illegal catch attempt");
|
|
1145
|
-
},
|
|
1146
|
-
delegateYield: function delegateYield(e, r, n) {
|
|
1147
|
-
return this.delegate = {
|
|
1148
|
-
iterator: values(e),
|
|
1149
|
-
resultName: r,
|
|
1150
|
-
nextLoc: n
|
|
1151
|
-
}, "next" === this.method && (this.arg = t), y;
|
|
1152
|
-
}
|
|
1153
|
-
}, e;
|
|
1154
|
-
}
|
|
1155
|
-
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
|
1156
|
-
} (regeneratorRuntime$1));
|
|
1157
|
-
|
|
1158
|
-
var regeneratorRuntimeExports = regeneratorRuntime$1.exports;
|
|
1159
|
-
|
|
1160
|
-
// TODO(Babel 8): Remove this file.
|
|
1161
|
-
|
|
1162
|
-
var runtime = regeneratorRuntimeExports();
|
|
1163
|
-
var regenerator = runtime;
|
|
1164
|
-
|
|
1165
|
-
// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
|
|
1166
|
-
try {
|
|
1167
|
-
regeneratorRuntime = runtime;
|
|
1168
|
-
} catch (accidentalStrictMode) {
|
|
1169
|
-
if (typeof globalThis === "object") {
|
|
1170
|
-
globalThis.regeneratorRuntime = runtime;
|
|
1171
|
-
} else {
|
|
1172
|
-
Function("r", "regeneratorRuntime = r")(runtime);
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
|
|
1177
|
-
|
|
1178
913
|
function isAttributeKeyAllowed(a,b){return !(null!==a&&void 0!==a)||!a.isAttributeKeyBlocked(b)}function isIdentityAllowed(a,b){return !(null!==a&&void 0!==a)||!a.isIdentityBlocked(b)}function copyUserAttributeValue(a){return Array.isArray(a)?a.slice():a}function buildUserAttributesCopy(a,b){var c={};if(!a)return c;for(var d in a)a.hasOwnProperty(d)&&isAttributeKeyAllowed(b,d)&&(c[d]=copyUserAttributeValue(a[d]));return c}function buildUserAttributeLists(a,b){var c={};for(var d in a)a.hasOwnProperty(d)&&Array.isArray(a[d])&&isAttributeKeyAllowed(b,d)&&(c[d]=a[d].slice());return c}function buildFilteredUserIdentities(a,b,c){var d={},e=a;for(var f in e)if(e.hasOwnProperty(f)){var g=Types.IdentityType.getIdentityName(c(f));isIdentityAllowed(b,g)&&(d[g]=e[f]);}return d}function filteredMparticleUser(a,b,c,d){function e(){var e=buildUserAttributesCopy(c._Store.getUserAttributes(a),d);return c._Helpers.filterUserAttributes(e,b.userAttributeFilters)}return {getUserIdentities:function getUserIdentities(){var e=buildFilteredUserIdentities(c._Store.getUserIdentities(a),d,c._Helpers.parseNumber);return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b=buildUserAttributeLists(e(),d);return c._Helpers.filterUserAttributes(b,a.userAttributeFilters)},getAllUserAttributes:e}}
|
|
1179
914
|
|
|
1180
915
|
var FORWARDING_RULE_MESSAGE_TYPES=[Types.MessageType.PageEvent,Types.MessageType.PageView,Types.MessageType.Commerce];function inFilteredList(a,b){return !!(a&&a.length)&&inArray(a,b)}function isBlockedByForwardingRule(a,b,c){if(!FORWARDING_RULE_MESSAGE_TYPES.includes(a)||!c.filteringEventAttributeValue||!c.filteringEventAttributeValue.eventAttributeName||!c.filteringEventAttributeValue.eventAttributeValue)return !1;var d=null;if(b)for(var e in b)if(b.hasOwnProperty(e)){var f=KitFilterHelper.hashAttributeConditionalForwarding(e);if(f===c.filteringEventAttributeValue.eventAttributeName){d={name:f,value:KitFilterHelper.hashAttributeConditionalForwarding(b[e])};break}}var g=null!==d&&d.value===c.filteringEventAttributeValue.eventAttributeValue,h=!0===c.filteringEventAttributeValue.includeOnMatch?g:!g;return !h}function isBlockedByEventFilter(a,b,c,d){if(a===Types.MessageType.PageEvent&&(inFilteredList(d.eventNameFilters,b)||inFilteredList(d.eventTypeFilters,c)))return !0;return !!(a===Types.MessageType.Commerce&&inFilteredList(d.eventTypeFilters,c))||!!(a===Types.MessageType.PageView&&inFilteredList(d.screenNameFilters,b))}function filterEventAttributes(a,b,c,d,e){if(!d)return d;var f;if(a===Types.MessageType.PageEvent?f=e.attributeFilters:a===Types.MessageType.PageView&&(f=e.screenAttributeFilters),!f)return d;var g={};for(var h in d)if(d.hasOwnProperty(h)){var i=KitFilterHelper.hashEventAttributeKey(b,c,h);inArray(f,i)||(g[h]=d[h]);}return g}function filterUserIdentities(a,b){return a&&a.length?a.filter(function(a){return !inArray(b,KitFilterHelper.hashUserIdentity(a.Type))}):a||[]}
|
|
1181
916
|
|
|
1182
|
-
var
|
|
917
|
+
var _a;var _b=Constants.IdentityMethods,Modify$2=_b.Modify,Identify$1=_b.Identify,Login$1=_b.Login,Logout$1=_b.Logout,identityCompleteKitMethods=(_a={},_a[Identify$1]="onIdentifyComplete",_a[Login$1]="onLoginComplete",_a[Logout$1]="onLogoutComplete",_a[Modify$2]="onModifyComplete",_a);// Maps an identity method to the kit callback that reports its completion.
|
|
918
|
+
function userAttributesMatchFilter(a,b){for(var c in a)if(a.hasOwnProperty(c)){var d=KitFilterHelper.hashAttributeConditionalForwarding(c),e=KitFilterHelper.hashAttributeConditionalForwarding(a[c]);if(d===b.userAttributeName&&e===b.userAttributeValue)return !0}return !1}function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036
|
|
1183
919
|
// Processing forwarders is a 2 step process:
|
|
1184
920
|
// 1. Configure the kit
|
|
1185
921
|
// 2. Initialize the kit
|
|
@@ -1199,9 +935,10 @@ var _Constants$IdentityMe=Constants.IdentityMethods,Modify$2=_Constants$Identity
|
|
|
1199
935
|
// there being a separate process for MP configured kits and
|
|
1200
936
|
// sideloaded kits, this will need to be refactored.
|
|
1201
937
|
// kits can be included via mParticle UI, or via sideloaded kit config API
|
|
1202
|
-
this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=KitFilterHelper.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;
|
|
1203
|
-
return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){
|
|
1204
|
-
|
|
938
|
+
this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=KitFilterHelper.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;if(!c)return !1;var d=c.getAllUserAttributes();try{var e=d&&a._Helpers.isObject(d)&&0<Object.keys(d).length,f=!!e&&userAttributesMatchFilter(d,b);return b.includeOnMatch===f}catch(a){// in any error scenario, err on side of returning true and forwarding event
|
|
939
|
+
return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){if(!a._Store.webviewBridgeEnabled&&a._Store.activeForwarders){// Not for...of: the downleveled loop is miscompiled in cjs/esm builds.
|
|
940
|
+
var c=KitFilterHelper.hashEventName(b.EventName,b.EventCategory),d=KitFilterHelper.hashEventType(b.EventCategory),e=function(e){if(!isBlockedByForwardingRule(b.EventDataType,b.EventAttributes,e)){// Clone the event object, as we could be sending different attributes to each forwarder
|
|
941
|
+
var f=extend(!0,{},b);if(!isBlockedByEventFilter(b.EventDataType,c,d,e)&&(f.EventAttributes=filterEventAttributes(b.EventDataType,b.EventCategory,b.EventName,f.EventAttributes,e),f.UserIdentities=filterUserIdentities(f.UserIdentities,e.userIdentityFilters),f.UserAttributes=KitFilterHelper.filterUserAttributes(f.UserAttributes,e.userAttributeFilters),!!e.process)){a.Logger.verbose("Sending message to forwarder: "+e.name);var g=e.process(f);g&&a.Logger.verbose(g);}}};a._Store.activeForwarders.forEach(function(a){e(a);});}},this.handleForwarderUserAttributes=function(c,d,f){b&&b.isAttributeKeyBlocked(d)||!a._Store.activeForwarders.length||a._Store.activeForwarders.forEach(function(b){var g=b[c];if(g&&!KitFilterHelper.isFilteredUserAttribute(d,b.userAttributeFilters))try{var h;c===e.setUserAttribute?h=b.setUserAttribute(d,f):c===e.removeUserAttribute&&(h=b.removeUserAttribute(d)),h&&a.Logger.verbose(h);}catch(b){a.Logger.error(b);}});},this.setForwarderUserIdentities=function(b){a._Store.activeForwarders.forEach(function(c){var d=a._Helpers.filterUserIdentities(b,c.userIdentityFilters);c.setUserIdentity&&d.forEach(function(b){var d=c.setUserIdentity(b.Identity,b.Type);d&&a.Logger.verbose(d);});});},this.setForwarderOnUserIdentified=function(c){a._Store.activeForwarders.forEach(function(d){var e=filteredMparticleUser(c.getMPID(),d,a,b);if(d.onUserIdentified){var f=d.onUserIdentified(e);f&&a.Logger.verbose(f);}});},this.setForwarderOnIdentityComplete=function(c,d){var e=identityCompleteKitMethods[d];e&&a._Store.activeForwarders.forEach(function(d){var f=d[e];if(f){var g=filteredMparticleUser(c.getMPID(),d,a,b),h=f.call(d,g,g.getUserIdentities());h&&a.Logger.verbose(h);}});},this.getForwarderStatsQueue=function(){return a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue},this.setForwarderStatsQueue=function(b){a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=b;},this.processForwarders=function(b,c){b?(this.processUIEnabledKits(b),this.processSideloadedKits(b),d.initForwarders(a._Store.SDKConfig.identifyRequest.userIdentities,c)):a.Logger.warning("No config was passed. Cannot process forwarders");},this.processUIEnabledKits=function(b){var c=this.returnKitConstructors();try{Array.isArray(b.kitConfigs)&&b.kitConfigs.length&&b.kitConfigs.forEach(function(a){d.configureUIEnabledKit(a,c);});}catch(b){a.Logger.error("MP Kits not configured propertly. Kits may not be initialized. "+b);}},this.returnKitConstructors=function(){var b={};// If there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted
|
|
1205
942
|
return isEmpty(a._Store.SDKConfig.kits)?!isEmpty(a._preInit.forwarderConstructors)&&a._preInit.forwarderConstructors.forEach(function(a){// A suffix is added to a kitConstructor and kit config if there are multiple different
|
|
1206
943
|
// versions of a client kit. This matches the suffix in the DB. As an example
|
|
1207
944
|
// the GA4 kit has a client kit and a server side kit which has a client side
|
|
@@ -1215,7 +952,7 @@ var g=void 0;if(e.suffix&&(g="".concat(e.name,"-").concat(e.suffix)),(f===g||f==
|
|
|
1215
952
|
for(var f in e.forEach(function(a){try{a.kitInstance.register(c);var b=a.kitInstance.name;// Then add the kit filters to each registered kit.
|
|
1216
953
|
c.kits[b].filters=a.filterDictionary;}catch(b){console.error("Error registering sideloaded kit "+a.kitInstance.name);}}),c.kits){var g=c.kits[f];d.configureSideloadedKit(g);}// If Sideloaded Kits are successfully registered,
|
|
1217
954
|
// record this in the Store.
|
|
1218
|
-
if(!isEmpty(c.kits)){var h=Object.keys(c.kits);a._Store.sideloadedKitsCount=h.length;}}}catch(b){a.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. "+b);}},this.configureSideloadedKit=function(b){a._Store.configuredForwarders.push(this.returnConfiguredKit(b,b.filters));},this.returnConfiguredKit=function(a){
|
|
955
|
+
if(!isEmpty(c.kits)){var h=Object.keys(c.kits);a._Store.sideloadedKitsCount=h.length;}}}catch(b){a.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. "+b);}},this.configureSideloadedKit=function(b){a._Store.configuredForwarders.push(this.returnConfiguredKit(b,b.filters));},this.returnConfiguredKit=function(a,b){void 0===b&&(b={});var c=new a.constructor;return c.id=b.moduleId,c.isSandbox=b.isDebug||b.isSandbox,c.hasSandbox="true"===b.hasDebugString,c.isVisible=b.isVisible||!0,c.settings=b.settings||{},c.eventNameFilters=b.eventNameFilters||[],c.eventTypeFilters=b.eventTypeFilters||[],c.attributeFilters=b.attributeFilters||[],c.screenNameFilters=b.screenNameFilters||[],c.screenAttributeFilters=b.screenAttributeFilters||[],c.userIdentityFilters=b.userIdentityFilters||[],c.userAttributeFilters=b.userAttributeFilters||[],c.filteringEventAttributeValue=b.filteringEventAttributeValue||{},c.filteringUserAttributeValue=b.filteringUserAttributeValue||{},c.eventSubscriptionId=b.eventSubscriptionId||null,c.filteringConsentRuleValues=b.filteringConsentRuleValues||{},c.excludeAnonymousUser=b.excludeAnonymousUser||!1,c},this.configurePixel=function(b){(b.isDebug===a._Store.SDKConfig.isDevelopmentMode||b.isProduction!==a._Store.SDKConfig.isDevelopmentMode)&&a._Store.pixelConfigurations.push(b);},this.processPixelConfigs=function(b){try{isEmpty(b.pixelConfigs)||b.pixelConfigs.forEach(function(a){d.configurePixel(a);});}catch(b){a.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. "+b);}},this.sendSingleForwardingStatsToServer=function(b){return __awaiter(c,void 0,void 0,function(){var c,d,e,f;return __generator(this,function(g){switch(g.label){case 0:return c={method:"post",body:JSON.stringify(b),headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"}},[4/*yield*/,this.forwarderStatsUploader.upload(c)];case 1:return d=g.sent(),e=202===d.status?"Successfully sent forwarding stats to mParticle Servers":"Issue with forwarding stats to mParticle Servers, received HTTP Code of "+d.statusText,null===(f=null===a||void 0===a?void 0:a.Logger)||void 0===f?void 0:f.verbose(e),[2/*return*/]}})})};}
|
|
1219
956
|
|
|
1220
957
|
// TODO: This file is no longer the server model because the web SDK payload
|
|
1221
958
|
var MessageType=Types.MessageType,ApplicationTransitionType=Types.ApplicationTransitionType;// TODO: Make this a pure function that returns a new object
|
|
@@ -1234,37 +971,6 @@ Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store
|
|
|
1234
971
|
|
|
1235
972
|
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);};}
|
|
1236
973
|
|
|
1237
|
-
function _toPrimitive(input, hint) {
|
|
1238
|
-
if (_typeof$1(input) !== "object" || input === null) return input;
|
|
1239
|
-
var prim = input[Symbol.toPrimitive];
|
|
1240
|
-
if (prim !== undefined) {
|
|
1241
|
-
var res = prim.call(input, hint || "default");
|
|
1242
|
-
if (_typeof$1(res) !== "object") return res;
|
|
1243
|
-
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
1244
|
-
}
|
|
1245
|
-
return (hint === "string" ? String : Number)(input);
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
function _toPropertyKey(arg) {
|
|
1249
|
-
var key = _toPrimitive(arg, "string");
|
|
1250
|
-
return _typeof$1(key) === "symbol" ? key : String(key);
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
function _defineProperty(obj, key, value) {
|
|
1254
|
-
key = _toPropertyKey(key);
|
|
1255
|
-
if (key in obj) {
|
|
1256
|
-
Object.defineProperty(obj, key, {
|
|
1257
|
-
value: value,
|
|
1258
|
-
enumerable: true,
|
|
1259
|
-
configurable: true,
|
|
1260
|
-
writable: true
|
|
1261
|
-
});
|
|
1262
|
-
} else {
|
|
1263
|
-
obj[key] = value;
|
|
1264
|
-
}
|
|
1265
|
-
return obj;
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
974
|
var AudienceManager=/** @class */function(){function a(a,b,c){this.url="",this.logger=c,this.url="https://".concat(a).concat(b,"/audience"),this.userAudienceAPI=window.fetch?new FetchUploader(this.url):new XHRUploader(this.url);}return a.prototype.sendGetUserAudienceRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c,d,e,f,g,h;return __generator(this,function(i){switch(i.label){case 0:this.logger.verbose("Fetching user audiences from server"),c={method:"GET",headers:{Accept:"*/*"}},d="".concat(this.url,"?mpid=").concat(a),i.label=1;case 1:return i.trys.push([1,6,,7]),[4/*yield*/,this.userAudienceAPI.upload(c,d)];case 2:return (e=i.sent(),!(200<=e.status&&300>e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate.
|
|
1269
975
|
throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}();
|
|
1270
976
|
|
|
@@ -1287,7 +993,7 @@ for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;h<i.length;h++)// Keep t
|
|
|
1287
993
|
e=i[h],g=f,f=f[e];// Apply the function with its proper context
|
|
1288
994
|
f.apply(g,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}};
|
|
1289
995
|
|
|
1290
|
-
|
|
996
|
+
var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,FeatureFlags$1=Constants.FeatureFlags,IdentityMethods$1=Constants.IdentityMethods,ErrorMessages=Messages$2.ErrorMessages,CacheIdentity=FeatureFlags$1.CacheIdentity,Identify=IdentityMethods$1.Identify,Modify$1=IdentityMethods$1.Modify,Login=IdentityMethods$1.Login,Logout=IdentityMethods$1.Logout;function Identity(a){var b=a._Helpers,c=b.getFeatureFlag,d=b.extend,e=this;// https://go.mparticle.com/work/SQDSDKS-6353
|
|
1291
997
|
/**
|
|
1292
998
|
* Invoke these methods on the mParticle.Identity object.
|
|
1293
999
|
* Example: mParticle.Identity.getCurrentUser().
|
|
@@ -1306,54 +1012,54 @@ function ownKeys(s,e){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var
|
|
|
1306
1012
|
// send a user identity change request on identify, login, logout, modify when any values change.
|
|
1307
1013
|
// compare what identities exist vs what is previously was for the specific user if they were in memory before.
|
|
1308
1014
|
// if it's the first time the user is logging in, send a user identity change request with
|
|
1309
|
-
this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(
|
|
1310
|
-
var
|
|
1311
|
-
if(!
|
|
1312
|
-
combineUserIdentities:function combineUserIdentities(
|
|
1313
|
-
!1!==
|
|
1015
|
+
this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(b,c,d){a.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent+": "+d);// First, remove any falsy identity values and warn about them
|
|
1016
|
+
var e=a._Helpers.Validators.removeFalsyIdentityValues(b,a.Logger),f=(null===e||void 0===e?void 0:e.userIdentities)?__assign(__assign({},e),{userIdentities:normalizeUserIdentityKeys(e.userIdentities)}):e,g=a._Helpers.Validators.validateIdentities(f,d);// Normalize convenience aliases (email_sha256 → other, mobile_sha256 → other2)
|
|
1017
|
+
if(!g.valid)return a.Logger.error("ERROR: "+g.error),{valid:!1,error:g.error};if(c&&!a._Helpers.Validators.isFunction(c)){var h="The optional callback must be a function. You tried entering a(n) "+_typeof(c);return a.Logger.error(h),{valid:!1,error:h}}return {valid:!0,cleanedIdentities:f}},createIdentityRequest:function createIdentityRequest(b,c,d,e,f,g,h){var i={client_sdk:{platform:c,sdk_vendor:d,sdk_version:e},context:g,environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:a._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),previous_mpid:h||null,known_identities:createKnownIdentities(b,f)};return i},createModifyIdentityRequest:function createModifyIdentityRequest(b,c,d,e,f,g){return {client_sdk:{platform:d,sdk_vendor:e,sdk_version:f},context:g,environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:a._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),identity_changes:this.createIdentityChanges(b,c)}},createIdentityChanges:function createIdentityChanges(a,b){var c=[];if(b&&isObject(b)&&a&&isObject(a))for(var d in b)c.push({old_value:a[d]||null,new_value:b[d],identity_type:d});return c},// takes 2 UI objects keyed by name, combines them, returns them keyed by type
|
|
1018
|
+
combineUserIdentities:function combineUserIdentities(a,b){var c={},e=d({},a,b);for(var f in e){var g=Types.IdentityType.getIdentityType(f);// this check removes anything that is not whitelisted as an identity type
|
|
1019
|
+
!1!==g&&0<=g&&(c[Types.IdentityType.getIdentityType(f)]=e[f]);}return c},createAliasNetworkRequest:function createAliasNetworkRequest(b){return {request_id:a._Helpers.generateUniqueId(),request_type:"alias",environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:a._Store.devToken,data:{destination_mpid:b.destinationMpid,source_mpid:b.sourceMpid,start_unixtime_ms:b.startTime,end_unixtime_ms:b.endTime,scope:b.scope,device_application_stamp:a._Store.deviceId}}},convertAliasToNative:function convertAliasToNative(a){return {DestinationMpid:a.destinationMpid,SourceMpid:a.sourceMpid,StartUnixtimeMs:a.startTime,EndUnixtimeMs:a.endTime,Scope:a.scope}},convertToNative:function convertToNative(a){var b=[];if(null===a||void 0===a?void 0:a.userIdentities){for(var c in a.userIdentities)a.userIdentities.hasOwnProperty(c)&&b.push({Type:Types.IdentityType.getIdentityType(c),Identity:a.userIdentities[c]});return {UserIdentities:b}}}},this.IdentityAPI={HTTPCodes:HTTPCodes$2,/**
|
|
1314
1020
|
* Initiate a logout request to the mParticle server
|
|
1315
1021
|
* @method identify
|
|
1316
1022
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
1317
1023
|
* @param {Function} [callback] A callback function that is called when the identify request completes
|
|
1318
|
-
*/identify:function identify(
|
|
1319
|
-
var
|
|
1024
|
+
*/identify:function identify(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1025
|
+
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Identify);if(f&&(d=f.getMPID()),g.valid){var h=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);if(a._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var i=tryCacheIdentity(h.known_identities,e.idCache,e.parseIdentityResponse,d,c,b,Identify);if(i)return}a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Identify request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(h,Identify,c,b,e.parseIdentityResponse,d,h.known_identities):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1320
1026
|
* Initiate a logout request to the mParticle server
|
|
1321
1027
|
* @method logout
|
|
1322
1028
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
1323
1029
|
* @param {Function} [callback] A callback function that is called when the logout request completes
|
|
1324
|
-
*/logout:function logout(
|
|
1325
|
-
var
|
|
1030
|
+
*/logout:function logout(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1031
|
+
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Logout);if(f&&(d=f.getMPID()),g.valid){var h,i=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Logout request sent to native sdk")):(a._IdentityAPIClient.sendIdentityRequest(i,Logout,c,b,e.parseIdentityResponse,d),h=a._ServerModel.createEventObject({messageType:Types.MessageType.Profile}),h.ProfileMessageType=Types.ProfileMessageType.Logout,a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(a){var b=a;b.logOut&&b.logOut(h);})):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1326
1032
|
* Initiate a login request to the mParticle server
|
|
1327
1033
|
* @method login
|
|
1328
1034
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
1329
1035
|
* @param {Function} [callback] A callback function that is called when the login request completes
|
|
1330
|
-
*/login:function login(
|
|
1331
|
-
var
|
|
1036
|
+
*/login:function login(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1037
|
+
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Login);if(f&&(d=f.getMPID()),g.valid){var h=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);if(a._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var i=tryCacheIdentity(h.known_identities,e.idCache,e.parseIdentityResponse,d,c,b,Login);if(i)return}a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Login request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(h,Login,c,b,e.parseIdentityResponse,d,h.known_identities):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1332
1038
|
* Initiate a modify request to the mParticle server
|
|
1333
1039
|
* @method modify
|
|
1334
1040
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
1335
1041
|
* @param {Function} [callback] A callback function that is called when the modify request completes
|
|
1336
|
-
*/modify:function modify(
|
|
1337
|
-
var
|
|
1042
|
+
*/modify:function modify(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1043
|
+
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Modify$1);if(f&&(d=f.getMPID()),g.valid){var h=(null===b||void 0===b?void 0:b.userIdentities)?g.cleanedIdentities.userIdentities:{},i=a._Identity.IdentityRequest.createModifyIdentityRequest(f?f.getUserIdentities().userIdentities:{},h,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.context);a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Modify request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(i,Modify$1,c,b,e.parseIdentityResponse,d):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1338
1044
|
* Returns a user object with methods to interact with the current user
|
|
1339
1045
|
* @method getCurrentUser
|
|
1340
1046
|
* @return {Object} the current user object
|
|
1341
|
-
*/getCurrentUser:function getCurrentUser(){var
|
|
1047
|
+
*/getCurrentUser:function getCurrentUser(){var b;return a._Store?(b=a._Store.mpid,b?(b=a._Store.mpid.slice(),e.mParticleUser(b,a._Store.isLoggedIn)):a._Store.webviewBridgeEnabled?e.mParticleUser():null):null},/**
|
|
1342
1048
|
* Returns a the user object associated with the mpid parameter or 'null' if no such
|
|
1343
1049
|
* user exists
|
|
1344
1050
|
* @method getUser
|
|
1345
1051
|
* @param {String} mpid of the desired user
|
|
1346
1052
|
* @return {Object} the user for mpid
|
|
1347
|
-
*/getUser:function getUser(
|
|
1053
|
+
*/getUser:function getUser(b){var c=a._Persistence.getPersistence();return c?c[b]&&!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(b)?e.mParticleUser(b):null:null},/**
|
|
1348
1054
|
* Returns all users, including the current user and all previous users that are stored on the device.
|
|
1349
1055
|
* @method getUsers
|
|
1350
1056
|
* @return {Array} array of users
|
|
1351
|
-
*/getUsers:function getUsers(){var
|
|
1057
|
+
*/getUsers:function getUsers(){var b=a._Persistence.getPersistence(),c=[];if(b)for(var d in b)Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(d)||c.push(e.mParticleUser(d));return c.sort(function(c,a){var b=c.getLastSeenTime()||0,d=a.getLastSeenTime()||0;return b>d?-1:1}),c},/**
|
|
1352
1058
|
* Initiate an alias request to the mParticle server
|
|
1353
1059
|
* @method aliasUsers
|
|
1354
1060
|
* @param {Object} aliasRequest object representing an AliasRequest
|
|
1355
1061
|
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
|
|
1356
|
-
*/aliasUsers:function aliasUsers(
|
|
1062
|
+
*/aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/**
|
|
1357
1063
|
* Search the IDSync Workspace endpoint for a known identity.
|
|
1358
1064
|
*
|
|
1359
1065
|
* POSTs to mParticle's `/v1/search` endpoint and invokes `callback`
|
|
@@ -1369,124 +1075,124 @@ var s,i=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIden
|
|
|
1369
1075
|
* @param {String} workspaceApiKey Workspace API key (sent as x-mp-key).
|
|
1370
1076
|
* @param {Object} knownIdentities A `UserIdentities` map.
|
|
1371
1077
|
* @param {Function} callback Invoked with the `IIdentitySearchResult`.
|
|
1372
|
-
*/search:function search(
|
|
1078
|
+
*/search:function search(b,c,d){executeSearchRequest(a,b,c,d);},/**
|
|
1373
1079
|
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
|
|
1374
1080
|
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
|
|
1375
1081
|
|
|
1376
1082
|
In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only
|
|
1377
|
-
be the case if they have not been the current user since this functionality was added, the
|
|
1083
|
+
be the case if they have not been the current user since this functionality was added, the
|
|
1378
1084
|
startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly,
|
|
1379
1085
|
if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time
|
|
1380
1086
|
|
|
1381
1087
|
There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days.
|
|
1382
|
-
If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime.
|
|
1383
|
-
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
1384
|
-
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
1385
|
-
validation that the startTime must be less than the endTime
|
|
1386
|
-
*/createAliasRequest:function createAliasRequest(
|
|
1387
|
-
return
|
|
1088
|
+
If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime.
|
|
1089
|
+
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
1090
|
+
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
1091
|
+
validation that the startTime must be less than the endTime
|
|
1092
|
+
*/createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime()<e)&&(e=a.getFirstSeenTime());});var f=new Date().getTime()-1e3*(60*(60*(24*a._Store.SDKConfig.aliasMaxWindow))),g=b.getLastSeenTime()||new Date().getTime();//if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed
|
|
1093
|
+
return e<f&&(e=f,g<e&&a.Logger.warning("Source User has not been seen in the last "+a._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail")),{destinationMpid:c.getMPID(),sourceMpid:b.getMPID(),startTime:e,endTime:g,scope:d||"device"}}catch(b){return a.Logger.error("There was a problem with creating an alias request: "+b),null}}},this.mParticleUser=function(b,c){return {/**
|
|
1388
1094
|
* Get user identities for current user
|
|
1389
1095
|
* @method getUserIdentities
|
|
1390
1096
|
* @return {Object} an object with userIdentities as its key
|
|
1391
|
-
*/getUserIdentities:function getUserIdentities(){var
|
|
1097
|
+
*/getUserIdentities:function getUserIdentities(){var c={},d=a._Store.getUserIdentities(b);for(var e in d)d.hasOwnProperty(e)&&(c[Types.IdentityType.getIdentityName(a._Helpers.parseNumber(e))]=d[e]);return {userIdentities:c}},/**
|
|
1392
1098
|
* Get the MPID of the current user
|
|
1393
1099
|
* @method getMPID
|
|
1394
1100
|
* @return {String} the current user MPID as a string
|
|
1395
|
-
*/getMPID:function getMPID(){return
|
|
1101
|
+
*/getMPID:function getMPID(){return b},/**
|
|
1396
1102
|
* Sets a user tag
|
|
1397
1103
|
* @method setUserTag
|
|
1398
1104
|
* @param {String} tagName
|
|
1399
|
-
*/setUserTag:function setUserTag(
|
|
1105
|
+
*/setUserTag:function setUserTag(b){return a._Helpers.Validators.isValidKeyValue(b)?void this.setUserAttribute(b,null):void a.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1400
1106
|
* Removes a user tag
|
|
1401
1107
|
* @method removeUserTag
|
|
1402
1108
|
* @param {String} tagName
|
|
1403
|
-
*/removeUserTag:function removeUserTag(
|
|
1109
|
+
*/removeUserTag:function removeUserTag(b){return a._Helpers.Validators.isValidKeyValue(b)?void this.removeUserAttribute(b):void a.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1404
1110
|
* Sets a user attribute
|
|
1405
1111
|
* @method setUserAttribute
|
|
1406
1112
|
* @param {String} key
|
|
1407
1113
|
* @param {String} value
|
|
1408
1114
|
*/ // https://go.mparticle.com/work/SQDSDKS-4576
|
|
1409
1115
|
// https://go.mparticle.com/work/SQDSDKS-6373
|
|
1410
|
-
setUserAttribute:function setUserAttribute(
|
|
1116
|
+
setUserAttribute:function setUserAttribute(c,d){if(a._SessionManager.resetSessionTimer(),a._Helpers.canLog()){if(!a._Helpers.Validators.isValidAttributeValue(d))return void a.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:c,value:d}));else {var f=this.getAllUserAttributes(),g=void 0,h=void 0,i=a._Helpers.findKeyInObject(f,c);i?(h=!1,g=f[i],delete f[i]):h=!0,f[c]=d,a._Store.setUserAttributes(b,f),e.sendUserAttributeChangeEvent(c,d,g,h,!1,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities(),a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("setUserAttribute",c,d);}}},/**
|
|
1411
1117
|
* Set multiple user attributes
|
|
1412
1118
|
* @method setUserAttributes
|
|
1413
1119
|
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
1414
1120
|
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1415
|
-
setUserAttributes:function setUserAttributes(
|
|
1121
|
+
setUserAttributes:function setUserAttributes(b){if(a._SessionManager.resetSessionTimer(),!isObject(b))a.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(b));else if(a._Helpers.canLog())for(var c in b)b.hasOwnProperty(c)&&this.setUserAttribute(c,b[c]);},/**
|
|
1416
1122
|
* Removes a specific user attribute
|
|
1417
1123
|
* @method removeUserAttribute
|
|
1418
1124
|
* @param {String} key
|
|
1419
|
-
*/removeUserAttribute:function removeUserAttribute(
|
|
1125
|
+
*/removeUserAttribute:function removeUserAttribute(c){var d,f;if(a._SessionManager.resetSessionTimer(),!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:c,value:null}));else {d=a._Persistence.getPersistence(),f=this.getAllUserAttributes();var g=a._Helpers.findKeyInObject(f,c);g&&(c=g);var h=f[c]?f[c].toString():null;delete f[c],d&&d[b]&&(d[b].ua=f,a._Persistence.savePersistence(d)),e.sendUserAttributeChangeEvent(c,null,h,!1,!0,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities(),a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("removeUserAttribute",c,null);}},/**
|
|
1420
1126
|
* Sets a list of user attributes
|
|
1421
1127
|
* @method setUserAttributeList
|
|
1422
1128
|
* @param {String} key
|
|
1423
1129
|
* @param {Array} value an array of values
|
|
1424
1130
|
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1425
|
-
setUserAttributeList:function setUserAttributeList(
|
|
1131
|
+
setUserAttributeList:function setUserAttributeList(c,d){if(a._SessionManager.resetSessionTimer(),!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(!Array.isArray(d))return void a.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+_typeof(d));var f=d.slice();if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:c,value:f}));else {var g=this.getAllUserAttributes(),h=void 0,j=void 0,k=void 0,l=a._Helpers.findKeyInObject(g,c);// If the new attributeList length is different than the previous, then there is a change event.
|
|
1426
1132
|
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
1427
1133
|
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
1428
|
-
if(
|
|
1134
|
+
if(l?(j=!1,h=g[l],delete g[l]):j=!0,g[c]=f,a._Store.setUserAttributes(b,g),!h||!Array.isArray(h))k=!0;else if(d.length!==h.length)k=!0;else for(var m=0;m<d.length;m++)if(h[m]!==d[m]){k=!0;break}k&&e.sendUserAttributeChangeEvent(c,d,h,j,!1,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities(),a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("setUserAttribute",c,f);}},/**
|
|
1429
1135
|
* Removes all user attributes
|
|
1430
1136
|
* @method removeAllUserAttributes
|
|
1431
|
-
*/removeAllUserAttributes:function removeAllUserAttributes(){var
|
|
1137
|
+
*/removeAllUserAttributes:function removeAllUserAttributes(){var b;if(a._SessionManager.resetSessionTimer(),a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(b=this.getAllUserAttributes(),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities(),a._APIClient.prepareForwardingStats),b)for(var c in b)b.hasOwnProperty(c)&&a._Forwarders.handleForwarderUserAttributes("removeUserAttribute",c,null),this.removeUserAttribute(c);},/**
|
|
1432
1138
|
* Returns all user attribute keys that have values that are arrays
|
|
1433
1139
|
* @method getUserAttributesLists
|
|
1434
1140
|
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
1435
|
-
*/getUserAttributesLists:function getUserAttributesLists(){var
|
|
1141
|
+
*/getUserAttributesLists:function getUserAttributesLists(){var a,b={};for(var c in a=this.getAllUserAttributes(),a)a.hasOwnProperty(c)&&Array.isArray(a[c])&&(b[c]=a[c].slice());return b},/**
|
|
1436
1142
|
* Returns all user attributes
|
|
1437
1143
|
* @method getAllUserAttributes
|
|
1438
1144
|
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
|
|
1439
|
-
*/getAllUserAttributes:function getAllUserAttributes(){var
|
|
1145
|
+
*/getAllUserAttributes:function getAllUserAttributes(){var c=a._Store.getUserAttributes,d={},e=c(b);if(e)for(var f in e)if(e.hasOwnProperty(f)){var g=e[f];d[f]=Array.isArray(g)?g.slice():g;}return d},/**
|
|
1440
1146
|
* Returns the cart object for the current user
|
|
1441
1147
|
* @method getCart
|
|
1442
1148
|
* @return a cart object
|
|
1443
|
-
*/getCart:function getCart(){return logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart()",warningMessage:"Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"},
|
|
1149
|
+
*/getCart:function getCart(){return logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart()",warningMessage:"Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"},a.Logger,a._ErrorReportingDispatcher),e.mParticleUserCart()},/**
|
|
1444
1150
|
* Returns the Consent State stored locally for this user.
|
|
1445
1151
|
* @method getConsentState
|
|
1446
1152
|
* @return a ConsentState object
|
|
1447
|
-
*/getConsentState:function getConsentState(){return
|
|
1153
|
+
*/getConsentState:function getConsentState(){return a._Store.getConsentState(b)},/**
|
|
1448
1154
|
* Sets the Consent State stored locally for this user.
|
|
1449
1155
|
* @method setConsentState
|
|
1450
1156
|
* @param {Object} consent state
|
|
1451
|
-
*/setConsentState:function setConsentState(
|
|
1157
|
+
*/setConsentState:function setConsentState(c){a._Store.setConsentState(b,c),a._Forwarders.initForwarders(this.getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),a._CookieSyncManager.attemptCookieSync(this.getMPID());},isLoggedIn:function isLoggedIn(){return c},getLastSeenTime:function getLastSeenTime(){return a._Persistence.getLastSeenTime(b)},getFirstSeenTime:function getFirstSeenTime(){return a._Persistence.getFirstSeenTime(b)},/**
|
|
1452
1158
|
* Get user audiences
|
|
1453
1159
|
* @method getuserAudiences
|
|
1454
1160
|
* @param {Function} [callback] A callback function that is invoked when the user audience request completes
|
|
1455
1161
|
*/ // https://go.mparticle.com/work/SQDSDKS-6436
|
|
1456
|
-
getUserAudiences:function getUserAudiences(
|
|
1457
|
-
return
|
|
1162
|
+
getUserAudiences:function getUserAudiences(c){// user audience API is feature flagged
|
|
1163
|
+
return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===e.audienceManager&&(e.audienceManager=new AudienceManager(a._Store.SDKConfig.userAudienceUrl,a._Store.devToken,a.Logger)),e.audienceManager.sendGetUserAudienceRequest(b,c)):void a.Logger.error(ErrorMessages.AudienceAPINotEnabled)}}},this.mParticleUserCart=function(){return {/**
|
|
1458
1164
|
* Adds a cart product to the user cart
|
|
1459
1165
|
* @method add
|
|
1460
1166
|
* @deprecated
|
|
1461
|
-
*/add:function add(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().add()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},
|
|
1167
|
+
*/add:function add(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().add()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},a.Logger,a._ErrorReportingDispatcher);},/**
|
|
1462
1168
|
* Removes a cart product from the current user cart
|
|
1463
1169
|
* @method remove
|
|
1464
1170
|
* @deprecated
|
|
1465
|
-
*/remove:function remove(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().remove()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},
|
|
1171
|
+
*/remove:function remove(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().remove()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},a.Logger,a._ErrorReportingDispatcher);},/**
|
|
1466
1172
|
* Clears the user's cart
|
|
1467
1173
|
* @method clear
|
|
1468
1174
|
* @deprecated
|
|
1469
|
-
*/clear:function clear(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().clear()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},
|
|
1175
|
+
*/clear:function clear(){logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().clear()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},a.Logger,a._ErrorReportingDispatcher);},/**
|
|
1470
1176
|
* Returns all cart products
|
|
1471
1177
|
* @method getCartProducts
|
|
1472
1178
|
* @return {Array} array of cart products
|
|
1473
1179
|
* @deprecated
|
|
1474
|
-
*/getCartProducts:function getCartProducts(){return logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().getCartProducts()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},
|
|
1180
|
+
*/getCartProducts:function getCartProducts(){return logDeprecatedMethodUsage({methodName:"Identity.getCurrentUser().getCart().getCartProducts()",warningMessage:generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")},a.Logger,a._ErrorReportingDispatcher),[]}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n,o,p,q=a.Identity.getUser(d),r=q?q.getMPID():null,s=q?q.getUserIdentities().userIdentities:{},t={};a._Store.identityCallInFlight=!1;try{if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),o=null!==(k=b.responseText)&&void 0!==k?k:null,a._Store.isLoggedIn=(null===o||void 0===o?void 0:o.is_logged_in)||!1,hasMPIDChanged(q,o)&&(a._Store.mpid=o.mpid,q&&a._Persistence.setLastSeenTime(d),n=!a._Persistence.getFirstSeenTime(o.mpid),a._Persistence.setFirstSeenTime(o.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(o.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(t=a._Identity.IdentityRequest.combineUserIdentities(s,g.userIdentities),a._Store.setUserIdentities(d,t)):(h===Identify&&q&&o.mpid===r&&a._Persistence.setFirstSeenTime(o.mpid),a._Store.addMpidToSessionHistory(o.mpid,d),a._CookieSyncManager.attemptCookieSync(o.mpid,n),a._Persistence.swapCurrentUser(d,o.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(t=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(o.mpid,t),a._Persistence.update(),a._Store.syncPersistenceData(),a._Persistence.findPrevCookiesBasedOnUI(g),a._Store.context=o.context||a._Store.context),p=a.Identity.getCurrentUser(),tryOnUserAlias(q,p,g,a.Logger,a._ErrorReportingDispatcher);var w=a._Persistence.getPersistence();p&&(a._Persistence.storeDataInMemory(w,p.getMPID()),e.reinitForwardersOnUserChange(q,p),e.setForwarderCallbacks(p,h));var x=IdentityType.getNewIdentitiesByName(t),y=h===Modify$1?s:v;// Sync $NoTargeting before sendUserIdentityChangeEvent
|
|
1475
1181
|
// because UIC events call sendEventToServer which triggers
|
|
1476
1182
|
// processQueuedEvents, draining the event queue. The
|
|
1477
1183
|
// attribute must be in the store before that happens so
|
|
1478
1184
|
// appendUserInfo picks it up.
|
|
1479
|
-
null===(
|
|
1480
|
-
|
|
1185
|
+
null===(l=a._CookieConsentManager)||void 0===l?void 0:l.syncNoTargetingAttribute(p),e.sendUserIdentityChangeEvent(x,h,o.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,o||null,p);}else o&&!isEmpty(o.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
|
|
1186
|
+
a.Logger.error("Received HTTP response code of "+b.status+" - "+o.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(m=a._APIClient)||void 0===m?void 0:m.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,o||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue,a.Logger);},this.sendUserIdentityChangeEvent=function(b,c,d,f){var g;if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1481
1187
|
{// https://go.mparticle.com/work/SQDSDKS-6354
|
|
1482
|
-
var
|
|
1483
|
-
if(i
|
|
1188
|
+
var h=this.IdentityAPI.getUser(d);for(var i in b)// Verifies a change actually happened
|
|
1189
|
+
if(f[i]!==b[i]){// If a new identity type was introduced when the identity changes
|
|
1484
1190
|
// we need to notify the server so that the user profile is updated in
|
|
1485
1191
|
// the mParticle UI.
|
|
1486
|
-
null===(
|
|
1487
|
-
return a
|
|
1488
|
-
null===(
|
|
1489
|
-
function tryOnUserAlias(
|
|
1192
|
+
var j=!f[i],k=e.createUserIdentityChange(i,b[i],f[i],j,h);null===(g=a._APIClient)||void 0===g?void 0:g.sendEventToServer(k);}}},this.createUserIdentityChange=function(b,c,d,e,f){var g;// https://go.mparticle.com/work/SQDSDKS-6439
|
|
1193
|
+
return g=a._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:b,Identity:c,CreatedThisBatch:e},Old:{IdentityType:b,Identity:d,CreatedThisBatch:!1}},userInMemory:f}),g},this.sendUserAttributeChangeEvent=function(b,c,d,f,g,h){var i,j=e.createUserAttributeChange(b,c,d,f,g,h);j&&(null===(i=a._APIClient)||void 0===i?void 0:i.sendEventToServer(j));},this.createUserAttributeChange=function(b,c,d,e,f,g){"undefined"==typeof d&&(d=null);var h;return c!==d&&(h=a._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:b,New:c,Old:d,Deleted:f,IsNewAttribute:e}},g)),h},this.reinitForwardersOnUserChange=function(b,c){var d;hasMPIDAndUserLoginChanged(b,c)&&(null===(d=a._Forwarders)||void 0===d?void 0:d.initForwarders(c.getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats));},this.setForwarderCallbacks=function(b,c){var d,e,f;// https://go.mparticle.com/work/SQDSDKS-6036
|
|
1194
|
+
null===(d=a._Forwarders)||void 0===d?void 0:d.setForwarderUserIdentities(b.getUserIdentities().userIdentities),null===(e=a._Forwarders)||void 0===e?void 0:e.setForwarderOnIdentityComplete(b,c),null===(f=a._Forwarders)||void 0===f?void 0:f.setForwarderOnUserIdentified(b);};}// https://go.mparticle.com/work/SQDSDKS-6359
|
|
1195
|
+
function tryOnUserAlias(a,b,c,d,e){if(c&&c.onUserAlias&&isFunction(c.onUserAlias))try{logDeprecatedMethodUsage({methodName:"onUserAlias",warningMessage:generateDeprecationMessage("onUserAlias")},d,e),c.onUserAlias(a,b);}catch(a){d.error("There was an error with your onUserAlias function - "+a);}}
|
|
1490
1196
|
|
|
1491
1197
|
var CCPAPurpose=Constants.CCPAPurpose;function Consent(a){var b=this;// this function is called when consent is required to
|
|
1492
1198
|
// determine if a cookie sync should happen, or a
|
|
@@ -1568,7 +1274,7 @@ if(v=null===(u=null===(t=null===(s=null===(r=null===(q=null===(p=null===(o=null=
|
|
|
1568
1274
|
then remove it from event.UserAttributes as it is blocked
|
|
1569
1275
|
*/var c=this.dataPlanMatchLookups.user_attributes;if(this.mpInstance._Helpers.isObject(c))for(var d,e=0,f=Object.keys(b.UserAttributes);e<f.length;e++)d=f[e],c[d]||delete b.UserAttributes[d];}return b},a.prototype.isAttributeKeyBlocked=function(a){/* used when an attribute is added to the user */if(!this.blockUserAttributes)return !1;var b=this.dataPlanMatchLookups.user_attributes;// When additionalProperties is set to true, matchedAttributes
|
|
1570
1276
|
// will be a boolean, otherwise it will return an object
|
|
1571
|
-
return !("boolean"==typeof b&&b)&&"object"===_typeof
|
|
1277
|
+
return !("boolean"==typeof b&&b)&&"object"===_typeof(b)&&!0!==b[a];// When "Block unplanned user attributes" is enabled and "Allow unplanned user
|
|
1572
1278
|
// attributes" is also enabled in the UI, allowing unplanned user attributes will be prioritized
|
|
1573
1279
|
},a.prototype.isIdentityBlocked=function(a){/* used when an attribute is added to the user */if(!this.blockUserIdentities)return !1;if(this.blockUserIdentities){var b=this.dataPlanMatchLookups.user_identities;if(!0===b)return !1;if(!b[a])return !0}else return !1;return !1},a.prototype.transformUserIdentities=function(a){var b,c=this,d=__assign({},a);/*
|
|
1574
1280
|
If the user identity is not found in matchedIdentities
|
|
@@ -1633,7 +1339,7 @@ var s=(null===f||void 0===f?void 0:f.sandbox)||!1,t=normalizeRoktLauncherOptions
|
|
|
1633
1339
|
// to the Rokt Launcher.
|
|
1634
1340
|
this.launcherOptions=__assign({sandbox:s},t),(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,(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.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 r,s,t,u,v,w,x,y,z,A,B,C,D,E,E,F,G,H,I,J,K,L,M,N=this;return __generator(this,function(){// Queue if kit isn't ready OR if identity is in flight
|
|
1635
1341
|
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(r=a.attributes,s=(null===r||void 0===r?void 0:r.sandbox)||null,t=this.mapPlacementAttributes(r,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(u=obfuscateDevData(r,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(u,null,2)))),this.currentUser=this.identityService.getCurrentUser(),v=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},w=v.email,x=t.email,y=void 0,z=void 0,A=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),A&&(y=v[this.mappedEmailShaIdentityType],z=t.emailsha256||t[this.mappedEmailShaIdentityType]||void 0),B=this.hasIdentityChanged(w,x),C=this.hasIdentityChanged(y,z),D={},B&&(D.email=x,x&&(E="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(E),null===(i=this.errorReporter)||void 0===i?void 0:i.report({message:E,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING}))),C&&(D[this.mappedEmailShaIdentityType]=z,E="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(E),null===(j=this.errorReporter)||void 0===j?void 0:j.report({message:E,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING})),!isEmpty(D))// Fire-and-forget identify — best-effort, does not block selectPlacements
|
|
1636
|
-
try{this.identityService.identify({userIdentities:__assign(__assign({},v),D)},function(a){var b=+(null===a||void 0===a?void 0:a.httpCode);b&&(400<=b||0>b)&&N.logger.error("Background identify failed with HTTP "+b),N.processMessageQueue();});}catch(a){this.logger.error("Background identify threw an error: "+getErrorMessage(a));}return F=__assign(__assign({},v),D),this.setUserAttributes(t),G=null===(l=null===(k=this.store)||void 0===k?void 0:k.getTimeOnSite)||void 0===l?void 0:l.call(k),H=null===(n=null===(m=this.store)||void 0===m?void 0:m.getTotalTimeOnSite)||void 0===n?void 0:n.call(m),I=__assign(__assign(__assign(__assign({},t),null===s?{}:{sandbox:s}),G?{active_time_on_site_ms:G}:{}),H?{total_time_on_site_ms:H}:{}),F.email&&!I.email&&(I.email=F.email),A&&(J=F[this.mappedEmailShaIdentityType],J&&!I.emailsha256&&!I[this.mappedEmailShaIdentityType]&&(I.emailsha256=J)),I[PASSBACK_CONVERSION_TRACKING_ID]||(null===(o=this.integrationCapture)||void 0===o?void 0:o.capture(),K=null===(p=this.integrationCapture)||void 0===p?void 0:p.getClickIdsAsIntegrationAttributes(),L=null===(q=null===K||void 0===K?void 0:K[PARTNER_MODULE_IDS.Rokt])||void 0===q?void 0:q[PASSBACK_CONVERSION_TRACKING_ID],L&&(I[PASSBACK_CONVERSION_TRACKING_ID]=L)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,M=__assign(__assign({},a),{attributes:I}),[2/*return*/,this.kit.selectPlacements(M)]}catch(a){return [2/*return*/,Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))]}return [2/*return*/]})})},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
|
|
1342
|
+
try{this.identityService.identify({userIdentities:__assign(__assign({},v),D)},function(a){var b=+(null===a||void 0===a?void 0:a.httpCode);b&&(400<=b||0>b)&&N.logger.error("Background identify failed with HTTP "+b),N.processMessageQueue();});}catch(a){this.logger.error("Background identify threw an error: "+getErrorMessage(a));}return F=__assign(__assign({},v),D),this.setUserAttributes(t),G=null===(l=null===(k=this.store)||void 0===k?void 0:k.getTimeOnSite)||void 0===l?void 0:l.call(k),H=null===(n=null===(m=this.store)||void 0===m?void 0:m.getTotalTimeOnSite)||void 0===n?void 0:n.call(m),I=__assign(__assign(__assign(__assign({},t),null===s?{}:{sandbox:s}),G?{active_time_on_site_ms:G}:{}),H?{total_time_on_site_ms:H}:{}),F.email&&!I.email&&(I.email=F.email),A&&(J=F[this.mappedEmailShaIdentityType],J&&!I.emailsha256&&!I[this.mappedEmailShaIdentityType]&&(I.emailsha256=J)),I[PASSBACK_CONVERSION_TRACKING_ID]||(null===(o=this.integrationCapture)||void 0===o?void 0:o.capture(),K=null===(p=this.integrationCapture)||void 0===p?void 0:p.getClickIdsAsIntegrationAttributes(),L=null===(q=null===K||void 0===K?void 0:K[PARTNER_MODULE_IDS.Rokt])||void 0===q?void 0:q[PASSBACK_CONVERSION_TRACKING_ID],L&&(I[PASSBACK_CONVERSION_TRACKING_ID]=L)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,M=__assign(__assign({},a),{attributes:I}),[2/*return*/,this.kit.selectPlacements(M)]}catch(a){return [2/*return*/,Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))]}return [2/*return*/]})})},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.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
|
|
1637
1343
|
return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=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;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},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
|
|
1638
1344
|
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
|
|
1639
1345
|
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
|
|
@@ -1657,66 +1363,6 @@ var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=
|
|
|
1657
1363
|
|
|
1658
1364
|
var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){var b=this;this.services.forEach(function(c){var d;try{c.log(a);}catch(a){null===(d=b.logger)||void 0===d?void 0:d.error("Error in LoggingService: "+a);}});},a}();
|
|
1659
1365
|
|
|
1660
|
-
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";// All APV state hangs off one window key, and it is the public debugging
|
|
1661
|
-
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
1662
|
-
// tracking is live.
|
|
1663
|
-
//
|
|
1664
|
-
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
1665
|
-
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
1666
|
-
// but `window` persists for the lifetime of the tab.
|
|
1667
|
-
//
|
|
1668
|
-
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
1669
|
-
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
1670
|
-
// survives the reset.
|
|
1671
|
-
var WIN_APV_KEY="__mpApv__";// ---------------------------------------------------------------------------
|
|
1672
|
-
// Pure helpers. No `this`, no globals, no side effects — callable and assertable
|
|
1673
|
-
// on their own, which is where the interesting rules live.
|
|
1674
|
-
// ---------------------------------------------------------------------------
|
|
1675
|
-
// Dedup keys on pathname only: a query-string- or hash-only change is the same
|
|
1676
|
-
// page and must not fire a view.
|
|
1677
|
-
var isNewPage=function(a,b){return b!==a};var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
1678
|
-
// path captured when the navigation was accepted rather than the live location.
|
|
1679
|
-
var buildPageViewEvent=function(a){return {messageType:MessageType$1.PageView,name:"PageView",data:__assign({},a),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
1680
|
-
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
1681
|
-
// neither the tracker nor mp-instance touches `window` directly and
|
|
1682
|
-
// `typeof window` is checked in exactly one place.
|
|
1683
|
-
// ---------------------------------------------------------------------------
|
|
1684
|
-
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
|
|
1685
|
-
// writers below create it.
|
|
1686
|
-
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
|
|
1687
|
-
// history methods it patched), then swaps in fresh state. The state object is the
|
|
1688
|
-
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
1689
|
-
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);},currentPathname=function(){return window.location.pathname};// ---------------------------------------------------------------------------
|
|
1690
|
-
// History patching
|
|
1691
|
-
// ---------------------------------------------------------------------------
|
|
1692
|
-
// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
1693
|
-
// returns the single function that undoes it — or null when nothing was
|
|
1694
|
-
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
1695
|
-
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
1696
|
-
// references out of the tracker entirely: there is no half-patched state for a
|
|
1697
|
-
// caller to inspect, and no way to restore the wrong pair.
|
|
1698
|
-
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
|
|
1699
|
-
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
1700
|
-
// leave anything that is no longer ours in place.
|
|
1701
|
-
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};// ---------------------------------------------------------------------------
|
|
1702
|
-
// Tracker
|
|
1703
|
-
// ---------------------------------------------------------------------------
|
|
1704
|
-
var PageViewTracker=/** @class */function(){function a(a){this.lastPath=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.popStateListener=null,this.mpInstance=a;}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
1705
|
-
// navigations. Flips to false on teardown, including the teardown a
|
|
1706
|
-
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
1707
|
-
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
1708
|
-
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
|
|
1709
|
-
// a previous module load, or this same tracker on a repeat
|
|
1710
|
-
// mParticle.init(). Their pending navigations are transferred rather than
|
|
1711
|
-
// dropped — a route change may have queued a deferred fire that has not
|
|
1712
|
-
// flushed yet, and dropping it loses a page view entirely.
|
|
1713
|
-
var b=getActiveTracker(),c=this.retire(b);this.active&&b!==this&&(c=c.concat(this.retire(this))),this.active=!0,this.lastPath=currentPathname(),this.log("[init] seeded lastPath: ".concat(this.lastPath)),this.undoHistoryPatch=patchHistory(function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),this.popStateListener=function(){return a.safeHandleNavigation("popstate")},window.addEventListener("popstate",this.popStateListener),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.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),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){return clearTimeout(a.timeoutId)}),a.map(function(a){return a.path})},a.prototype.safeHandleNavigation=function(a){// An orphaned wrapper still calls in: teardown can only restore a history
|
|
1714
|
-
// method that is still ours, so one a third party patched over stays
|
|
1715
|
-
// installed and keeps firing at a dead tracker. Bail before touching
|
|
1716
|
-
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
1717
|
-
// rather than at each wrapper also covers the popstate path.
|
|
1718
|
-
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=currentPathname();return this.log("[detect] navigation signal (source: ".concat(a,", candidatePath: ").concat(b,", lastPath: ").concat(this.lastPath,")")),isNewPage(this.lastPath,b)?void(this.log("[accept] pathname changed, scheduling fire (source: ".concat(a,", from: ").concat(this.lastPath,", to: ").concat(b,")")),this.lastPath=b,this.scheduleFire(b)):void this.log("[dedupe] pathname unchanged, skipping (source: ".concat(a,", path: ").concat(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({path:a,timeoutId:c});},a.prototype.firePageView=function(a){var b=window.document.title,c=buildPageViewEvent({hostname:window.location.hostname,title:b,path:a});this.log("[fire] deferred flush -> _Events.logEvent(PageView) (path: ".concat(a,", title: ").concat(b,")")),this.mpInstance._Events.logEvent(c);},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle APV: ".concat(a));},a}();
|
|
1719
|
-
|
|
1720
1366
|
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;/**
|
|
1721
1367
|
* <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>
|
|
1722
1368
|
* <p>In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.</p>
|
|
@@ -1733,7 +1379,7 @@ this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._Ses
|
|
|
1733
1379
|
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
|
|
1734
1380
|
// to it for it to be run after fetched
|
|
1735
1381
|
if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._ErrorReportingDispatcher.logger=c.Logger,c._LoggingDispatcher.logger=c.Logger,c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),resetPageViewTracking(),c._PageViewTracker=void 0,b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval
|
|
1736
|
-
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof
|
|
1382
|
+
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/**
|
|
1737
1383
|
* Creates a CCPA Opt Out Consent State.
|
|
1738
1384
|
*
|
|
1739
1385
|
* @method createCCPAConsent
|
|
@@ -1881,7 +1527,7 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf
|
|
|
1881
1527
|
*/logRefund:function logRefund(a,c,d,e,f){return logDeprecatedMethodUsage({methodName:"mParticle.logRefund",warningMessage:"mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"},b.Logger,b._ErrorReportingDispatcher),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie
|
|
1882
1528
|
// And logs to in-memory object
|
|
1883
1529
|
// Example: mParticle.setSessionAttribute('location', '33431');
|
|
1884
|
-
if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof
|
|
1530
|
+
if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed
|
|
1885
1531
|
if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any
|
|
1886
1532
|
// other integration delays set to true. It not, process the queued events/.
|
|
1887
1533
|
var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this._registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this._registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment
|