@mparticle/web-sdk 2.65.0 → 2.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mparticle.common.js +119 -78
- package/dist/mparticle.esm.js +119 -78
- package/dist/mparticle.js +383 -128
- package/dist/types/src/identity/search.d.ts +64 -0
- package/dist/types/src/identity-utils.d.ts +17 -1
- package/dist/types/src/identity.interfaces.d.ts +37 -1
- package/dist/types/src/public-types.d.ts +1 -1
- package/dist/types/src/roktManager.d.ts +4 -0
- package/dist/types/src/stub/mparticle.stub.d.ts +1 -0
- package/package.json +1 -1
- package/src/identity/search.ts +233 -0
- package/src/identity-utils.ts +81 -1
- package/src/identity.interfaces.ts +46 -0
- package/src/identity.js +27 -0
- package/src/mparticle-instance-manager.ts +7 -0
- package/src/public-types.ts +4 -0
- package/src/roktManager.ts +35 -0
- package/src/stub/mparticle.stub.js +1 -0
package/dist/mparticle.esm.js
CHANGED
|
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
|
|
|
15
15
|
filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
|
|
16
16
|
isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
|
|
17
17
|
|
|
18
|
-
var version = "2.
|
|
18
|
+
var version = "2.67.0";
|
|
19
19
|
|
|
20
20
|
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",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
|
|
@@ -31,7 +31,7 @@ CaptureIntegrationSpecificIdsV2:"captureIntegrationSpecificIds.V2",AstBackground
|
|
|
31
31
|
// launcherOptions.noTargeting. Server-side systems use this attribute
|
|
32
32
|
// to exclude the user from retargeting audiences.
|
|
33
33
|
var NO_TARGETING_ATTRIBUTE="$NoTargeting";// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
|
|
34
|
-
var HTTP_OK=200;var HTTP_ACCEPTED=202;var HTTP_BAD_REQUEST=400;var HTTP_SERVER_ERROR=500;
|
|
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
36
|
function _typeof$1(o) {
|
|
37
37
|
"@babel/helpers - typeof";
|
|
@@ -138,7 +138,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
|
|
|
138
138
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
139
139
|
};
|
|
140
140
|
|
|
141
|
-
var Messages$
|
|
141
|
+
var Messages$a=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},generateDeprecationMessage=function(a,b,c,d){var e=[a];return b?e.push(Messages$a.DeprecationMessages.MethodHasBeenDeprecated):e.push(Messages$a.DeprecationMessages.MethodMarkedForDeprecationPostfix),c&&(e.push(Messages$a.DeprecationMessages.AlternativeMethodPrefix),e.push(c+".")),d&&e.push("See - "+d),e.join(" ")};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
|
|
142
142
|
?generateRandomValue()// if the placeholder was passed, return
|
|
143
143
|
:// [1e7] -> // 10000000 +
|
|
144
144
|
// -1e3 -> // -1000 +
|
|
@@ -508,9 +508,41 @@ if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.p
|
|
|
508
508
|
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," received")),[2/*return*/,d.slice(f,d.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
509
509
|
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,d.slice(f,d.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}();
|
|
510
510
|
|
|
511
|
-
var
|
|
511
|
+
var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",IDENTITY_MISMATCH:"IDENTITY_MISMATCH",ROKT_KIT_ATTACHED:"ROKT_KIT_ATTACHED"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"};
|
|
512
|
+
|
|
513
|
+
var Modify$4=Constants.IdentityMethods.Modify,Validators={// From ./utils
|
|
514
|
+
// Utility Functions for backwards compatability
|
|
515
|
+
isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,// Validator Functions
|
|
516
|
+
isValidAttributeValue:isValidAttributeValue,// Validator Functions
|
|
517
|
+
// Neither null nor undefined can be a valid Key
|
|
518
|
+
isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},removeFalsyIdentityValues:function removeFalsyIdentityValues(a,b){if(!a||!a.userIdentities)return a;var c={},d=__assign({},a.userIdentities);for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){var f=a.userIdentities[e];// Check if value is falsy (undefined, false, 0, '', etc.) but not null
|
|
519
|
+
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$4&&(isObject(a.userIdentities)&&!Object.keys(a.userIdentities).length||!isObject(a.userIdentities)))return {valid:!1,error:Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var d in a)if(a.hasOwnProperty(d)){if(!c[d])return {valid:!1,error:Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===d&&!Validators.isFunction(a[d]))return {valid:!1,error:Constants.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(a).length)return {valid:!0};// identityApiData.userIdentities can't be undefined
|
|
520
|
+
if(void 0===a.userIdentities)return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
|
|
521
|
+
if(null!==a.userIdentities&&!isObject(a.userIdentities))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};if(isObject(a.userIdentities)&&Object.keys(a.userIdentities).length)for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){if(!1===Types.IdentityType.getIdentityType(e))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof a.userIdentities[e]&&null!==a.userIdentities[e])return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return {valid:!0}}};
|
|
522
|
+
|
|
523
|
+
var HTTPCodes$4=Constants.HTTPCodes;/**
|
|
524
|
+
* Sends a POST to mParticle's IDSync Search endpoint and invokes `callback`
|
|
525
|
+
* with the HTTP status and parsed body.
|
|
526
|
+
*
|
|
527
|
+
* Defensive contract:
|
|
528
|
+
* - No identifier with a non-empty string value -> callback with
|
|
529
|
+
* `{ httpCode: noHttpCoverage }`, no network call.
|
|
530
|
+
* - Missing `apiKey` -> callback with `{ httpCode: noHttpCoverage }`,
|
|
531
|
+
* no network call.
|
|
532
|
+
* - Network/JSON-parse errors are caught and surfaced via the callback,
|
|
533
|
+
* never thrown. Network errors are also reported through the optional
|
|
534
|
+
* `errorReporter` so any registered IErrorReportingService can observe
|
|
535
|
+
* them (matches the pattern used by identifyRequest in identityApiClient).
|
|
536
|
+
*/var sendSearchRequest=function(a,b,c,d,e,f,g,h){return __awaiter(void 0,void 0,void 0,function(){var i,j,k,l,m,n,o,p,r,s,t,u;return __generator(this,function(v){switch(v.label){case 0:// Validate the callback up front. If it isn't a function we have nowhere
|
|
537
|
+
// to deliver a result to, so log and bail out without invoking anything.
|
|
538
|
+
if(!isFunction(e))return f.error("search called without a callback function; skipping request."),[2/*return*/];// No usable identifier -> deliver httpCode: noHttpCoverage so callers
|
|
539
|
+
// waiting on the callback (e.g. to clear a loading state) don't hang.
|
|
540
|
+
if(i=function(a){try{e(a);}catch(a){f.error("Error invoking search callback: "+((null===a||void 0===a?void 0:a.message)||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.
|
|
541
|
+
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=(null===s||void 0===s?void 0:s.message)||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*/]}})})};
|
|
542
|
+
|
|
543
|
+
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
|
|
512
544
|
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
513
|
-
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$
|
|
545
|
+
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
|
|
514
546
|
// we sort the identities based on their enum.
|
|
515
547
|
// we create an array, set the user identity at the index of the user identity type
|
|
516
548
|
var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type
|
|
@@ -537,7 +569,20 @@ if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};var
|
|
|
537
569
|
*
|
|
538
570
|
* @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities)
|
|
539
571
|
* @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise
|
|
540
|
-
*/var hasExplicitIdentifier=function(a){var b,c,d,e=null===(c=null===(b=null===a||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.identifyRequest)||void 0===c?void 0:c.userIdentities;return !!(e&&isObject(e)&&!isEmpty(e)&&Object.values(e).some(Boolean))||!(!(null!==(d=null===a||void 0===a?void 0:a.SDKConfig)&&void 0!==d)||!d.deviceId)}
|
|
572
|
+
*/var hasExplicitIdentifier=function(a){var b,c,d,e=null===(c=null===(b=null===a||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.identifyRequest)||void 0===c?void 0:c.userIdentities;return !!(e&&isObject(e)&&!isEmpty(e)&&Object.values(e).some(Boolean))||!(!(null!==(d=null===a||void 0===a?void 0:a.SDKConfig)&&void 0!==d)||!d.deviceId)};/**
|
|
573
|
+
* Builds the /v1/identify-style envelope (client_sdk, environment,
|
|
574
|
+
* request_id, request_timestamp_ms) used to correlate IDSync requests
|
|
575
|
+
* across endpoints. `known_identities` is omitted so the caller can
|
|
576
|
+
* fold in the search-specific identifiers alongside the envelope.
|
|
577
|
+
*/var buildIdentitySearchEnvelope=function(a){return {client_sdk:{platform:Constants.platform,sdk_vendor:Constants.sdkVendor,sdk_version:Constants.sdkVersion},environment:a,request_id:generateUniqueId(),request_timestamp_ms:Date.now()}};/**
|
|
578
|
+
* Wires the SDK instance into `sendSearchRequest`: gates on `canLog`,
|
|
579
|
+
* builds the `/v1/search` URL and request envelope, and dispatches.
|
|
580
|
+
* Lives here so the SDK glue (URL building, opt-out gate, dispatcher
|
|
581
|
+
* plumbing) is type-checked instead of being expressed in plain JS.
|
|
582
|
+
*/var executeSearchRequest=function(a,b,c,d){var e=a._Helpers,f=a._Store,g=a.Logger,h=a._ErrorReportingDispatcher,i=f.SDKConfig,j=i.identityUrl,k=i.isDevelopmentMode;if(!e.canLog()){if(g.verbose(Messages$9.InformationMessages.AbandonLogEvent),isFunction(d))try{d({httpCode:HTTPCodes$3.loggingDisabledOrMissingAPIKey});}catch(a){g.error("Error invoking search callback: "+((null===a||void 0===a?void 0:a.message)||a+""));}return}// The Search endpoint is colocated with /v1/identify under
|
|
583
|
+
// identityUrl, so we reuse the same service URL builder. We do
|
|
584
|
+
// NOT append the apiKey to the URL — auth is done via x-mp-key.
|
|
585
|
+
var l=e.createServiceUrl(j),m=k?"development":"production";sendSearchRequest(c,b,function(){return buildIdentitySearchEnvelope(m)},l+"search?cb=1",d,g,void 0,h);};
|
|
541
586
|
|
|
542
587
|
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){// https://go.mparticle.com/work/SQDSDKS-6317
|
|
543
588
|
var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
@@ -551,16 +596,6 @@ var d=function(c,d){var e,f=(null===(e=a._CookieConsentManager)||void 0===e?void
|
|
|
551
596
|
if(!g||a._Store.requireDelay||!a._Store.configurationLoaded)return a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c);this.processQueuedEvents(),isEmpty(c)||(f.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition+""&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&!c.AlreadySentToForwarders&&a._Forwarders.sendEventToForwarders(c)));}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
552
597
|
},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.initializeForwarderStatsUploader=function(){var b=a._Store.SDKConfig.v1SecureServiceUrl,c=a._Store.devToken,d="https://".concat(b).concat(c,"/Forwarding"),e=window.fetch?new FetchUploader(d):new XHRUploader(d);return e},this.prepareForwardingStats=function(b,c){var d,e=a._Forwarders.getForwarderStatsQueue();if(b&&b.isVisible){d={mid:b.id,esid:b.eventSubscriptionId,n:c.EventName,attrs:c.EventAttributes,sdk:c.SDKVersion,dt:c.EventDataType,et:c.EventCategory,dbg:c.Debug,ct:c.Timestamp,eec:c.ExpandedEventCount,dp:c.DataPlan};var f=a._Forwarders,g=f.sendSingleForwardingStatsToServer,h=f.setForwarderStatsQueue;a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(e.push(d),h(e)):g(d);}};}
|
|
553
598
|
|
|
554
|
-
var Modify$3=Constants.IdentityMethods.Modify,Validators={// From ./utils
|
|
555
|
-
// Utility Functions for backwards compatability
|
|
556
|
-
isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,// Validator Functions
|
|
557
|
-
isValidAttributeValue:isValidAttributeValue,// Validator Functions
|
|
558
|
-
// Neither null nor undefined can be a valid Key
|
|
559
|
-
isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},removeFalsyIdentityValues:function removeFalsyIdentityValues(a,b){if(!a||!a.userIdentities)return a;var c={},d=__assign({},a.userIdentities);for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){var f=a.userIdentities[e];// Check if value is falsy (undefined, false, 0, '', etc.) but not null
|
|
560
|
-
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$3&&(isObject(a.userIdentities)&&!Object.keys(a.userIdentities).length||!isObject(a.userIdentities)))return {valid:!1,error:Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var d in a)if(a.hasOwnProperty(d)){if(!c[d])return {valid:!1,error:Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===d&&!Validators.isFunction(a[d]))return {valid:!1,error:Constants.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(a).length)return {valid:!0};// identityApiData.userIdentities can't be undefined
|
|
561
|
-
if(void 0===a.userIdentities)return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
|
|
562
|
-
if(null!==a.userIdentities&&!isObject(a.userIdentities))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};if(isObject(a.userIdentities)&&Object.keys(a.userIdentities).length)for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){if(!1===Types.IdentityType.getIdentityType(e))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof a.userIdentities[e]&&null!==a.userIdentities[e])return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return {valid:!0}}};
|
|
563
|
-
|
|
564
599
|
var KitFilterHelper=/** @class */function(){function a(){}a.hashEventType=function(a){return generateHash(a)},a.hashEventName=function(a,b){return generateHash(b+a)},a.hashEventAttributeKey=function(a,b,c){return generateHash(a+b+c)},a.hashUserAttribute=function(a){return generateHash(a)},a.hashUserIdentity=function(a){return a},a.hashConsentPurpose=function(a,b){return generateHash(a+b)},a.hashAttributeConditionalForwarding=function(a){return generateHash(a).toString()},a.hashConsentPurposeConditionalForwarding=function(a,b){return this.hashConsentPurpose(a,b).toString()};var b;return b=a,a.filterUserAttributes=function(a,c){return filterDictionaryWithHash(a,c,function(a){return b.hashUserAttribute(a)})},a.filterUserIdentities=function(a,c){return filterDictionaryWithHash(a,c,function(a){return b.hashUserIdentity(IdentityType.getIdentityType(a))})},a.isFilteredUserAttribute=function(a,c){var d=b.hashUserAttribute(a);return c&&inArray(c,d)},a}();
|
|
565
600
|
|
|
566
601
|
var StorageNames$1=Constants.StorageNames;function Helpers(a){var b=this;// TODO: Refactor SDK to directly use these methods
|
|
@@ -1176,7 +1211,7 @@ for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;h<i.length;h++)// Keep t
|
|
|
1176
1211
|
e=i[h],g=f,f=f[e];// Apply the function with its proper context
|
|
1177
1212
|
f.apply(g,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}};
|
|
1178
1213
|
|
|
1179
|
-
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(
|
|
1214
|
+
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(t){var r=t._Helpers,s=r.getFeatureFlag,i=r.extend,n=this;// https://go.mparticle.com/work/SQDSDKS-6353
|
|
1180
1215
|
/**
|
|
1181
1216
|
* Invoke these methods on the mParticle.Identity object.
|
|
1182
1217
|
* Example: mParticle.Identity.getCurrentUser().
|
|
@@ -1195,53 +1230,69 @@ var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,FeatureFlags$1
|
|
|
1195
1230
|
// send a user identity change request on identify, login, logout, modify when any values change.
|
|
1196
1231
|
// compare what identities exist vs what is previously was for the specific user if they were in memory before.
|
|
1197
1232
|
// if it's the first time the user is logging in, send a user identity change request with
|
|
1198
|
-
this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(
|
|
1199
|
-
var
|
|
1200
|
-
combineUserIdentities:function combineUserIdentities(
|
|
1201
|
-
!1!==
|
|
1233
|
+
this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(e,r,s){t.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent+": "+s);// First, remove any falsy identity values and warn about them
|
|
1234
|
+
var i=t._Helpers.Validators.removeFalsyIdentityValues(e,t.Logger),n=t._Helpers.Validators.validateIdentities(i,s);if(!n.valid)return t.Logger.error("ERROR: "+n.error),{valid:!1,error:n.error};if(r&&!t._Helpers.Validators.isFunction(r)){var d="The optional callback must be a function. You tried entering a(n) "+_typeof$1(r);return t.Logger.error(d),{valid:!1,error:d}}return {valid:!0,cleanedIdentities:i}},createIdentityRequest:function createIdentityRequest(e,r,s,i,n,d,a){var o={client_sdk:{platform:r,sdk_vendor:s,sdk_version:i},context:d,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),previous_mpid:a||null,known_identities:createKnownIdentities(e,n)};return o},createModifyIdentityRequest:function createModifyIdentityRequest(e,r,s,i,n,d){return {client_sdk:{platform:s,sdk_vendor:i,sdk_version:n},context:d,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),identity_changes:this.createIdentityChanges(e,r)}},createIdentityChanges:function createIdentityChanges(e,t){var r,s=[];if(t&&isObject(t)&&e&&isObject(e))for(r in t)s.push({old_value:e[r]||null,new_value:t[r],identity_type:r});return s},// takes 2 UI objects keyed by name, combines them, returns them keyed by type
|
|
1235
|
+
combineUserIdentities:function combineUserIdentities(e,t){var r={},s=i({},e,t);for(var n in s){var d=Types.IdentityType.getIdentityType(n);// this check removes anything that is not whitelisted as an identity type
|
|
1236
|
+
!1!==d&&0<=d&&(r[Types.IdentityType.getIdentityType(n)]=s[n]);}return r},createAliasNetworkRequest:function createAliasNetworkRequest(e){return {request_id:t._Helpers.generateUniqueId(),request_type:"alias",environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:t._Store.devToken,data:{destination_mpid:e.destinationMpid,source_mpid:e.sourceMpid,start_unixtime_ms:e.startTime,end_unixtime_ms:e.endTime,scope:e.scope,device_application_stamp:t._Store.deviceId}}},convertAliasToNative:function convertAliasToNative(e){return {DestinationMpid:e.destinationMpid,SourceMpid:e.sourceMpid,StartUnixtimeMs:e.startTime,EndUnixtimeMs:e.endTime,Scope:e.scope}},convertToNative:function convertToNative(e){var t=[];if(e&&e.userIdentities){for(var r in e.userIdentities)e.userIdentities.hasOwnProperty(r)&&t.push({Type:Types.IdentityType.getIdentityType(r),Identity:e.userIdentities[r]});return {UserIdentities:t}}}},this.IdentityAPI={HTTPCodes:HTTPCodes$2,/**
|
|
1202
1237
|
* Initiate a logout request to the mParticle server
|
|
1203
1238
|
* @method identify
|
|
1204
1239
|
* @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)
|
|
1205
1240
|
* @param {Function} [callback] A callback function that is called when the identify request completes
|
|
1206
|
-
*/identify:function identify(
|
|
1207
|
-
var
|
|
1241
|
+
*/identify:function identify(e,r){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1242
|
+
var s,i=t.Identity.getCurrentUser(),d=t._Identity.IdentityRequest.preProcessIdentityRequest(e,r,Identify);if(i&&(s=i.getMPID()),d.valid){var a=t._Identity.IdentityRequest.createIdentityRequest(d.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,s);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var o=tryCacheIdentity(a.known_identities,n.idCache,n.parseIdentityResponse,s,r,e,Identify);if(o)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(r,HTTPCodes$2.nativeIdentityRequest,"Identify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(a,Identify,r,e,n.parseIdentityResponse,s,a.known_identities):(t._Helpers.invokeCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(r,HTTPCodes$2.validationIssue,d.error),t.Logger.verbose(d);},/**
|
|
1208
1243
|
* Initiate a logout request to the mParticle server
|
|
1209
1244
|
* @method logout
|
|
1210
1245
|
* @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)
|
|
1211
1246
|
* @param {Function} [callback] A callback function that is called when the logout request completes
|
|
1212
|
-
*/logout:function logout(
|
|
1213
|
-
var
|
|
1247
|
+
*/logout:function logout(e,r){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1248
|
+
var s,i=t.Identity.getCurrentUser(),d=t._Identity.IdentityRequest.preProcessIdentityRequest(e,r,Logout);if(i&&(s=i.getMPID()),d.valid){var a,o=t._Identity.IdentityRequest.createIdentityRequest(d.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,s);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(r,HTTPCodes$2.nativeIdentityRequest,"Logout request sent to native sdk")):(t._IdentityAPIClient.sendIdentityRequest(o,Logout,r,e,n.parseIdentityResponse,s),a=t._ServerModel.createEventObject({messageType:Types.MessageType.Profile}),a.ProfileMessageType=Types.ProfileMessageType.Logout,t._Store.activeForwarders.length&&t._Store.activeForwarders.forEach(function(e){e.logOut&&e.logOut(a);})):(t._Helpers.invokeCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(r,HTTPCodes$2.validationIssue,d.error),t.Logger.verbose(d);},/**
|
|
1214
1249
|
* Initiate a login request to the mParticle server
|
|
1215
1250
|
* @method login
|
|
1216
1251
|
* @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)
|
|
1217
1252
|
* @param {Function} [callback] A callback function that is called when the login request completes
|
|
1218
|
-
*/login:function login(
|
|
1219
|
-
var
|
|
1253
|
+
*/login:function login(e,r){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1254
|
+
var s,i=t.Identity.getCurrentUser(),d=t._Identity.IdentityRequest.preProcessIdentityRequest(e,r,Login);if(i&&(s=i.getMPID()),d.valid){var a=t._Identity.IdentityRequest.createIdentityRequest(d.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,s);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var o=tryCacheIdentity(a.known_identities,n.idCache,n.parseIdentityResponse,s,r,e,Login);if(o)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(r,HTTPCodes$2.nativeIdentityRequest,"Login request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(a,Login,r,e,n.parseIdentityResponse,s,a.known_identities):(t._Helpers.invokeCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(r,HTTPCodes$2.validationIssue,d.error),t.Logger.verbose(d);},/**
|
|
1220
1255
|
* Initiate a modify request to the mParticle server
|
|
1221
1256
|
* @method modify
|
|
1222
1257
|
* @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)
|
|
1223
1258
|
* @param {Function} [callback] A callback function that is called when the modify request completes
|
|
1224
|
-
*/modify:function modify(
|
|
1225
|
-
var
|
|
1259
|
+
*/modify:function modify(e,r){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1260
|
+
var s,i=t.Identity.getCurrentUser(),d=t._Identity.IdentityRequest.preProcessIdentityRequest(e,r,Modify$1);if(i&&(s=i.getMPID()),d.valid){var a=e&&e.userIdentities?d.cleanedIdentities.userIdentities:{},o=t._Identity.IdentityRequest.createModifyIdentityRequest(i?i.getUserIdentities().userIdentities:{},a,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.context);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(r,HTTPCodes$2.nativeIdentityRequest,"Modify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(o,Modify$1,r,e,n.parseIdentityResponse,s,o.known_identities):(t._Helpers.invokeCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(r,HTTPCodes$2.validationIssue,d.error),t.Logger.verbose(d);},/**
|
|
1226
1261
|
* Returns a user object with methods to interact with the current user
|
|
1227
1262
|
* @method getCurrentUser
|
|
1228
1263
|
* @return {Object} the current user object
|
|
1229
|
-
*/getCurrentUser:function getCurrentUser(){var
|
|
1264
|
+
*/getCurrentUser:function getCurrentUser(){var e;return t._Store?(e=t._Store.mpid,e?(e=t._Store.mpid.slice(),n.mParticleUser(e,t._Store.isLoggedIn)):t._Store.webviewBridgeEnabled?n.mParticleUser():null):null},/**
|
|
1230
1265
|
* Returns a the user object associated with the mpid parameter or 'null' if no such
|
|
1231
1266
|
* user exists
|
|
1232
1267
|
* @method getUser
|
|
1233
1268
|
* @param {String} mpid of the desired user
|
|
1234
1269
|
* @return {Object} the user for mpid
|
|
1235
|
-
*/getUser:function getUser(
|
|
1270
|
+
*/getUser:function getUser(e){var r=t._Persistence.getPersistence();return r?r[e]&&!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(e)?n.mParticleUser(e):null:null},/**
|
|
1236
1271
|
* Returns all users, including the current user and all previous users that are stored on the device.
|
|
1237
1272
|
* @method getUsers
|
|
1238
1273
|
* @return {Array} array of users
|
|
1239
|
-
*/getUsers:function getUsers(){var
|
|
1274
|
+
*/getUsers:function getUsers(){var e=t._Persistence.getPersistence(),r=[];if(e)for(var s in e)Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(s)||r.push(n.mParticleUser(s));return r.sort(function(e,t){var r=e.getLastSeenTime()||0,s=t.getLastSeenTime()||0;return r>s?-1:1}),r},/**
|
|
1240
1275
|
* Initiate an alias request to the mParticle server
|
|
1241
1276
|
* @method aliasUsers
|
|
1242
1277
|
* @param {Object} aliasRequest object representing an AliasRequest
|
|
1243
1278
|
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
|
|
1244
|
-
*/aliasUsers:function aliasUsers(
|
|
1279
|
+
*/aliasUsers:function aliasUsers(e,r){var s;if(e.destinationMpid&&e.sourceMpid||(s=Messages$2.ValidationMessages.AliasMissingMpid),e.destinationMpid===e.sourceMpid&&(s=Messages$2.ValidationMessages.AliasNonUniqueMpid),e.startTime&&e.endTime||(s=Messages$2.ValidationMessages.AliasMissingTime),e.startTime>e.endTime&&(s=Messages$2.ValidationMessages.AliasStartBeforeEndTime),s)return t.Logger.warning(s),void t._Helpers.invokeAliasCallback(r,HTTPCodes$2.validationIssue,s);if(!t._Helpers.canLog())t._Helpers.invokeAliasCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),t.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(t._Identity.IdentityRequest.convertAliasToNative(e))),t._Helpers.invokeAliasCallback(r,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {t.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+e.sourceMpid+" -> "+e.destinationMpid);var i=t._Identity.IdentityRequest.createAliasNetworkRequest(e);t._IdentityAPIClient.sendAliasRequest(i,r);}},/**
|
|
1280
|
+
* Search the IDSync Workspace endpoint for a known identity.
|
|
1281
|
+
*
|
|
1282
|
+
* POSTs to mParticle's `/v1/search` endpoint and invokes `callback`
|
|
1283
|
+
* with `{ httpCode, body? }`.
|
|
1284
|
+
*
|
|
1285
|
+
* The `workspaceApiKey` is a workspace-specific API key supplied by
|
|
1286
|
+
* the caller (passed in from a kit's settings). It is intentionally
|
|
1287
|
+
* NOT read from the SDK's own workspace token, so that workspace
|
|
1288
|
+
* searches can be authorised independently of the host SDK's
|
|
1289
|
+
* workspace.
|
|
1290
|
+
*
|
|
1291
|
+
* @method search
|
|
1292
|
+
* @param {String} workspaceApiKey Workspace API key (sent as x-mp-key).
|
|
1293
|
+
* @param {Object} knownIdentities A `UserIdentities` map.
|
|
1294
|
+
* @param {Function} callback Invoked with the `IIdentitySearchResult`.
|
|
1295
|
+
*/search:function search(e,r,s){executeSearchRequest(t,e,r,s);},/**
|
|
1245
1296
|
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
|
|
1246
1297
|
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
|
|
1247
1298
|
|
|
@@ -1255,110 +1306,110 @@ var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIden
|
|
|
1255
1306
|
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
1256
1307
|
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
1257
1308
|
validation that the startTime must be less than the endTime
|
|
1258
|
-
*/createAliasRequest:function createAliasRequest(
|
|
1259
|
-
return
|
|
1309
|
+
*/createAliasRequest:function createAliasRequest(e,r,s){try{if(!r||!e)return t.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var i=e.getFirstSeenTime();i||t.Identity.getUsers().forEach(function(e){e.getFirstSeenTime()&&(!i||e.getFirstSeenTime()<i)&&(i=e.getFirstSeenTime());});var n=new Date().getTime()-1e3*(60*(60*(24*t._Store.SDKConfig.aliasMaxWindow))),d=e.getLastSeenTime()||new Date().getTime();//if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed
|
|
1310
|
+
return i<n&&(i=n,d<i&&t.Logger.warning("Source User has not been seen in the last "+t._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail")),{destinationMpid:r.getMPID(),sourceMpid:e.getMPID(),startTime:i,endTime:d,scope:s||"device"}}catch(r){return t.Logger.error("There was a problem with creating an alias request: "+r),null}}},this.mParticleUser=function(e,r){var s=this;return {/**
|
|
1260
1311
|
* Get user identities for current user
|
|
1261
1312
|
* @method getUserIdentities
|
|
1262
1313
|
* @return {Object} an object with userIdentities as its key
|
|
1263
|
-
*/getUserIdentities:function getUserIdentities(){var
|
|
1314
|
+
*/getUserIdentities:function getUserIdentities(){var r={},s=t._Store.getUserIdentities(e);for(var i in s)s.hasOwnProperty(i)&&(r[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(i))]=s[i]);return {userIdentities:r}},/**
|
|
1264
1315
|
* Get the MPID of the current user
|
|
1265
1316
|
* @method getMPID
|
|
1266
1317
|
* @return {String} the current user MPID as a string
|
|
1267
|
-
*/getMPID:function getMPID(){return
|
|
1318
|
+
*/getMPID:function getMPID(){return e},/**
|
|
1268
1319
|
* Sets a user tag
|
|
1269
1320
|
* @method setUserTag
|
|
1270
1321
|
* @param {String} tagName
|
|
1271
|
-
*/setUserTag:function setUserTag(
|
|
1322
|
+
*/setUserTag:function setUserTag(e){return t._Helpers.Validators.isValidKeyValue(e)?void this.setUserAttribute(e,null):void t.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1272
1323
|
* Removes a user tag
|
|
1273
1324
|
* @method removeUserTag
|
|
1274
1325
|
* @param {String} tagName
|
|
1275
|
-
*/removeUserTag:function removeUserTag(
|
|
1326
|
+
*/removeUserTag:function removeUserTag(e){return t._Helpers.Validators.isValidKeyValue(e)?void this.removeUserAttribute(e):void t.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1276
1327
|
* Sets a user attribute
|
|
1277
1328
|
* @method setUserAttribute
|
|
1278
1329
|
* @param {String} key
|
|
1279
1330
|
* @param {String} value
|
|
1280
1331
|
*/ // https://go.mparticle.com/work/SQDSDKS-4576
|
|
1281
1332
|
// https://go.mparticle.com/work/SQDSDKS-6373
|
|
1282
|
-
setUserAttribute:function setUserAttribute(
|
|
1333
|
+
setUserAttribute:function setUserAttribute(r,i){if(t._SessionManager.resetSessionTimer(),t._Helpers.canLog()){if(!t._Helpers.Validators.isValidAttributeValue(i))return void t.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:r,value:i}));else {var n,d,a=this.getAllUserAttributes(),o=t._Helpers.findKeyInObject(a,r);o?(d=!1,n=a[o],delete a[o]):d=!0,a[r]=i,t._Store.setUserAttributes(e,a),s.sendUserAttributeChangeEvent(r,i,n,d,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,i);}}},/**
|
|
1283
1334
|
* Set multiple user attributes
|
|
1284
1335
|
* @method setUserAttributes
|
|
1285
1336
|
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
1286
1337
|
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1287
|
-
setUserAttributes:function setUserAttributes(
|
|
1338
|
+
setUserAttributes:function setUserAttributes(e){if(t._SessionManager.resetSessionTimer(),!isObject(e))t.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof$1(e));else if(t._Helpers.canLog())for(var r in e)e.hasOwnProperty(r)&&this.setUserAttribute(r,e[r]);},/**
|
|
1288
1339
|
* Removes a specific user attribute
|
|
1289
1340
|
* @method removeUserAttribute
|
|
1290
1341
|
* @param {String} key
|
|
1291
|
-
*/removeUserAttribute:function removeUserAttribute(
|
|
1342
|
+
*/removeUserAttribute:function removeUserAttribute(r){var i,n;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:r,value:null}));else {i=t._Persistence.getPersistence(),n=this.getAllUserAttributes();var d=t._Helpers.findKeyInObject(n,r);d&&(r=d);var a=n[r]?n[r].toString():null;delete n[r],i&&i[e]&&(i[e].ua=n,t._Persistence.savePersistence(i,e)),s.sendUserAttributeChangeEvent(r,null,a,!1,!0,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null);}},/**
|
|
1292
1343
|
* Sets a list of user attributes
|
|
1293
1344
|
* @method setUserAttributeList
|
|
1294
1345
|
* @param {String} key
|
|
1295
1346
|
* @param {Array} value an array of values
|
|
1296
1347
|
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1297
|
-
setUserAttributeList:function setUserAttributeList(
|
|
1348
|
+
setUserAttributeList:function setUserAttributeList(r,n){if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(!Array.isArray(n))return void t.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+("undefined"==typeof value?"undefined":_typeof$1(value)));var d=n.slice();if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:r,value:d}));else {var a,o,g,l=this.getAllUserAttributes(),u=t._Helpers.findKeyInObject(l,r);// If the new attributeList length is different than the previous, then there is a change event.
|
|
1298
1349
|
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
1299
1350
|
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
1300
|
-
if(
|
|
1351
|
+
if(u?(o=!1,a=l[u],delete l[u]):o=!0,l[r]=d,t._Store.setUserAttributes(e,l),!a||!Array.isArray(a))g=!0;else if(n.length!==a.length)g=!0;else for(var p=0;p<n.length;p++)if(a[p]!==n[p]){g=!0;break}g&&s.sendUserAttributeChangeEvent(r,n,a,o,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,d);}},/**
|
|
1301
1352
|
* Removes all user attributes
|
|
1302
1353
|
* @method removeAllUserAttributes
|
|
1303
|
-
*/removeAllUserAttributes:function removeAllUserAttributes(){var
|
|
1354
|
+
*/removeAllUserAttributes:function removeAllUserAttributes(){var e;if(t._SessionManager.resetSessionTimer(),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(e=this.getAllUserAttributes(),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),e)for(var r in e)e.hasOwnProperty(r)&&t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null),this.removeUserAttribute(r);},/**
|
|
1304
1355
|
* Returns all user attribute keys that have values that are arrays
|
|
1305
1356
|
* @method getUserAttributesLists
|
|
1306
1357
|
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
1307
|
-
*/getUserAttributesLists:function getUserAttributesLists(){var
|
|
1358
|
+
*/getUserAttributesLists:function getUserAttributesLists(){var e,t={};for(var r in e=this.getAllUserAttributes(),e)e.hasOwnProperty(r)&&Array.isArray(e[r])&&(t[r]=e[r].slice());return t},/**
|
|
1308
1359
|
* Returns all user attributes
|
|
1309
1360
|
* @method getAllUserAttributes
|
|
1310
1361
|
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
|
|
1311
|
-
*/getAllUserAttributes:function getAllUserAttributes(){var
|
|
1362
|
+
*/getAllUserAttributes:function getAllUserAttributes(){var r=t._Store.getUserAttributes,s={},i=r(e);if(i)for(var n in i)i.hasOwnProperty(n)&&(s[n]=Array.isArray(i[n])?i[n].slice():i[n]);return s},/**
|
|
1312
1363
|
* Returns the cart object for the current user
|
|
1313
1364
|
* @method getCart
|
|
1314
1365
|
* @return a cart object
|
|
1315
|
-
*/getCart:function getCart(){return
|
|
1366
|
+
*/getCart:function getCart(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"),s.mParticleUserCart()},/**
|
|
1316
1367
|
* Returns the Consent State stored locally for this user.
|
|
1317
1368
|
* @method getConsentState
|
|
1318
1369
|
* @return a ConsentState object
|
|
1319
|
-
*/getConsentState:function getConsentState(){return
|
|
1370
|
+
*/getConsentState:function getConsentState(){return t._Store.getConsentState(e)},/**
|
|
1320
1371
|
* Sets the Consent State stored locally for this user.
|
|
1321
1372
|
* @method setConsentState
|
|
1322
1373
|
* @param {Object} consent state
|
|
1323
|
-
*/setConsentState:function setConsentState(
|
|
1374
|
+
*/setConsentState:function setConsentState(r){t._Store.setConsentState(e,r),t._Forwarders.initForwarders(this.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._CookieSyncManager.attemptCookieSync(this.getMPID());},isLoggedIn:function isLoggedIn(){return r},getLastSeenTime:function getLastSeenTime(){return t._Persistence.getLastSeenTime(e)},getFirstSeenTime:function getFirstSeenTime(){return t._Persistence.getFirstSeenTime(e)},/**
|
|
1324
1375
|
* Get user audiences
|
|
1325
1376
|
* @method getuserAudiences
|
|
1326
1377
|
* @param {Function} [callback] A callback function that is invoked when the user audience request completes
|
|
1327
1378
|
*/ // https://go.mparticle.com/work/SQDSDKS-6436
|
|
1328
|
-
getUserAudiences:function getUserAudiences(
|
|
1329
|
-
return
|
|
1379
|
+
getUserAudiences:function getUserAudiences(r){// user audience API is feature flagged
|
|
1380
|
+
return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audienceManager&&(s.audienceManager=new AudienceManager(t._Store.SDKConfig.userAudienceUrl,t._Store.devToken,t.Logger,e)),s.audienceManager.sendGetUserAudienceRequest(e,r)):void t.Logger.error(ErrorMessages.AudienceAPINotEnabled)}}},this.mParticleUserCart=function(){return {/**
|
|
1330
1381
|
* Adds a cart product to the user cart
|
|
1331
1382
|
* @method add
|
|
1332
1383
|
* @deprecated
|
|
1333
|
-
*/add:function add(){
|
|
1384
|
+
*/add:function add(){t.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/**
|
|
1334
1385
|
* Removes a cart product from the current user cart
|
|
1335
1386
|
* @method remove
|
|
1336
1387
|
* @deprecated
|
|
1337
|
-
*/remove:function remove(){
|
|
1388
|
+
*/remove:function remove(){t.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/**
|
|
1338
1389
|
* Clears the user's cart
|
|
1339
1390
|
* @method clear
|
|
1340
1391
|
* @deprecated
|
|
1341
|
-
*/clear:function clear(){
|
|
1392
|
+
*/clear:function clear(){t.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/**
|
|
1342
1393
|
* Returns all cart products
|
|
1343
1394
|
* @method getCartProducts
|
|
1344
1395
|
* @return {Array} array of cart products
|
|
1345
1396
|
* @deprecated
|
|
1346
|
-
*/getCartProducts:function getCartProducts(){return
|
|
1397
|
+
*/getCartProducts:function getCartProducts(){return t.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")),[]}}},this.parseIdentityResponse=function(r,i,d,a,o,g,l){var u,p,y,I=t.Identity.getUser(i),c=I?I.getMPID():null,_=I?I.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,b,S;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(b=p)||void 0===b?void 0:b.is_logged_in)||!1,hasMPIDChanged(I,p)&&(t._Store.mpid=p.mpid,I&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){var A;s(CacheIdentity)&&cacheOrClearIdCache(o,g,n.idCache,r,l);var U=n.IdentityAPI.getUser(p.mpid),k=U?U.getUserIdentities().userIdentities:{};o===Modify$1?(v=t._Identity.IdentityRequest.combineUserIdentities(_,a.userIdentities),t._Store.setUserIdentities(i,v)):(o===Identify&&I&&p.mpid===c&&t._Persistence.setFirstSeenTime(p.mpid),t._Store.addMpidToSessionHistory(p.mpid,i),t._CookieSyncManager.attemptCookieSync(p.mpid,u),t._Persistence.swapCurrentUser(i,p.mpid,t._Store.currentSessionMPIDs),a&&!isEmpty(a.userIdentities)&&(v=n.IdentityRequest.combineUserIdentities(k,a.userIdentities)),t._Store.setUserIdentities(p.mpid,v),t._Persistence.update(),t._Store.syncPersistenceData(),t._Persistence.findPrevCookiesBasedOnUI(a),t._Store.context=p.context||t._Store.context),y=t.Identity.getCurrentUser(),tryOnUserAlias(I,y,a,t.Logger);var C=t._Persistence.getPersistence();y&&(t._Persistence.storeDataInMemory(C,y.getMPID()),n.reinitForwardersOnUserChange(I,y),n.setForwarderCallbacks(y,o));var P=IdentityType.getNewIdentitiesByName(v),w=o===Modify$1?_:k;// Sync $NoTargeting before sendUserIdentityChangeEvent
|
|
1347
1398
|
// because UIC events call sendEventToServer which triggers
|
|
1348
1399
|
// processQueuedEvents, draining the event queue. The
|
|
1349
1400
|
// attribute must be in the store before that happens so
|
|
1350
1401
|
// appendUserInfo picks it up.
|
|
1351
|
-
null===(
|
|
1352
|
-
|
|
1402
|
+
null===(A=t._CookieConsentManager)||void 0===A||A.syncNoTargetingAttribute(y),n.sendUserIdentityChangeEvent(P,o,p.mpid,w);}if(d){var f=0===r.status?HTTPCodes$2.noHttpCoverage:r.status;t._Helpers.invokeCallback(d,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
|
|
1403
|
+
t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(S=t._APIClient)||void 0===S||S.processQueuedEvents();}catch(s){d&&t._Helpers.invokeCallback(d,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}t._Store.isInitialized=!0,t._RoktManager.onIdentityComplete(),t._preInit.readyQueue=processReadyQueue(t._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1353
1404
|
{// https://go.mparticle.com/work/SQDSDKS-6354
|
|
1354
|
-
var
|
|
1355
|
-
if(
|
|
1405
|
+
var d=this.IdentityAPI.getUser(s);for(var a in e)// Verifies a change actually happened
|
|
1406
|
+
if(i[a]!==e[a]){var o,g=!i[a],l=n.createUserIdentityChange(a,e[a],i[a],g,d);// If a new identity type was introduced when the identity changes
|
|
1356
1407
|
// we need to notify the server so that the user profile is updated in
|
|
1357
1408
|
// the mParticle UI.
|
|
1358
|
-
null===(
|
|
1359
|
-
return
|
|
1360
|
-
null===(
|
|
1361
|
-
function tryOnUserAlias(
|
|
1409
|
+
null===(o=t._APIClient)||void 0===o||o.sendEventToServer(l);}}},this.createUserIdentityChange=function(e,r,s,i,n){var d;// https://go.mparticle.com/work/SQDSDKS-6439
|
|
1410
|
+
return d=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:r,CreatedThisBatch:i},Old:{IdentityType:e,Identity:s,CreatedThisBatch:!1}},userInMemory:n}),d},this.sendUserAttributeChangeEvent=function(e,r,s,i,d,a){var o=n.createUserAttributeChange(e,r,s,i,d,a);if(o){var g;null===(g=t._APIClient)||void 0===g||g.sendEventToServer(o);}},this.createUserAttributeChange=function(e,r,s,i,n,d){"undefined"==typeof s&&(s=null);var a;return r!==s&&(a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:r,Old:s,Deleted:n,IsNewAttribute:i}},d)),a},this.reinitForwardersOnUserChange=function(e,r){if(hasMPIDAndUserLoginChanged(e,r)){var s;null===(s=t._Forwarders)||void 0===s||s.initForwarders(r.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats);}},this.setForwarderCallbacks=function(e,r){var s,i,n;// https://go.mparticle.com/work/SQDSDKS-6036
|
|
1411
|
+
null===(s=t._Forwarders)||void 0===s||s.setForwarderUserIdentities(e.getUserIdentities().userIdentities),null===(i=t._Forwarders)||void 0===i||i.setForwarderOnIdentityComplete(e,r),null===(n=t._Forwarders)||void 0===n||n.setForwarderOnUserIdentified(e);};}// https://go.mparticle.com/work/SQDSDKS-6359
|
|
1412
|
+
function tryOnUserAlias(e,t,r,s){if(r&&r.onUserAlias&&isFunction(r.onUserAlias))try{s.warning(generateDeprecationMessage("onUserAlias")),r.onUserAlias(e,t);}catch(t){s.error("There was an error with your onUserAlias function - "+t);}}
|
|
1362
1413
|
|
|
1363
1414
|
var CCPAPurpose=Constants.CCPAPurpose;function Consent(a){var b=this;// this function is called when consent is required to
|
|
1364
1415
|
// determine if a cookie sync should happen, or a
|
|
@@ -1453,8 +1504,6 @@ return !("boolean"==typeof b&&b)&&"object"===_typeof$1(b)&&!0!==b[a];// When "Bl
|
|
|
1453
1504
|
var buildUrl=function(a,b,c,d){var e=d?"1":"0",f=["env=".concat(e)],g=c||{},h=g.planId,i=g.planVersion;return h&&f.push("plan_id=".concat(h)),i&&f.push("plan_version=".concat(i)),"".concat(a+b+"/config","?").concat(f.join("&"))};function ConfigAPIClient(a,b,c){var d=this,e="https://"+c._Store.SDKConfig.configUrl,f=b.isDevelopmentMode,g=b.dataPlan,h=buildUrl(e,a,g,f),i=window.fetch?new FetchUploader(h):new XHRUploader(h);this.getSDKConfiguration=function(){return __awaiter(d,void 0,void 0,function(){var a,d,e,f,h,j,k;return __generator(this,function(l){switch(l.label){case 0:d={method:"get",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"},body:null},l.label=1;case 1:return l.trys.push([1,6,,7]),[4/*yield*/,i.upload(d)];case 2:return (e=l.sent(),200!==e.status)?[3/*break*/,5]:(null===(h=null===c||void 0===c?void 0:c.Logger)||void 0===h?void 0:h.verbose("Successfully received configuration from server"),e.json?[4/*yield*/,e.json()]:[3/*break*/,4]);case 3:return a=l.sent(),[2/*return*/,a];case 4:return f=e,a=JSON.parse(f.responseText),[2/*return*/,a];case 5:return null===(j=null===c||void 0===c?void 0:c.Logger)||void 0===j?void 0:j.verbose("Issue with receiving configuration from server, received HTTP Code of "+e.statusText),[3/*break*/,7];case 6:return l.sent(),null===(k=null===c||void 0===c?void 0:c.Logger)||void 0===k?void 0:k.error("Error getting forwarder configuration from mParticle servers."),[3/*break*/,7];case 7:// Returns the original config object if we cannot retrieve the remote config
|
|
1454
1505
|
return [2/*return*/,b]}})})};}
|
|
1455
1506
|
|
|
1456
|
-
var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",IDENTITY_MISMATCH:"IDENTITY_MISMATCH",ROKT_KIT_ATTACHED:"ROKT_KIT_ATTACHED"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"};
|
|
1457
|
-
|
|
1458
1507
|
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,A,m,E,m,A,F;return __generator(this,function(G){switch(G.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,p=a._ErrorReportingDispatcher,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,G.label=1;case 1:return G.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=G.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=G.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),G.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):o.isVerbose()&&(B=v.responseText,C=a._Store.SDKConfig.isDevelopmentMode,D=B,!C&&(null===B||void 0===B?void 0:B.matched_identities)&&(D=__assign(__assign({},B),{matched_identities:obfuscateData(B.matched_identities)})),w="Received Identity Response from server: "+JSON.stringify(D)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,o.error("Error sending identity request to servers - "+A),n(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,w&&o.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return E=G.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),A=E.message||E.toString(),F="Error sending identity request to servers - "+A,o.error(F),null===p||void 0===p?void 0:p.report({message:F,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
|
|
1459
1508
|
|
|
1460
1509
|
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
|
|
@@ -1497,15 +1546,7 @@ var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c
|
|
|
1497
1546
|
// }
|
|
1498
1547
|
for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}();
|
|
1499
1548
|
|
|
1500
|
-
|
|
1501
|
-
// The Rokt Manager should load before the Web Kit and stubs out many of the
|
|
1502
|
-
// Rokt Web SDK functions with an internal message queue in case a Rokt function
|
|
1503
|
-
// is requested before the Rokt Web Kit or SDK is finished loaded.
|
|
1504
|
-
// Once the Rokt Kit is attached to the Rokt Manager, we can consider the
|
|
1505
|
-
// Rokt Manager in a "ready" state and it can begin sending data to the kit.
|
|
1506
|
-
//
|
|
1507
|
-
// https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
|
|
1508
|
-
var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1;}/**
|
|
1549
|
+
var ON_SHOPPABLE_ADS_READY_METHOD="onShoppableAdsReady",RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1,this.isShoppableAdsLoaded=!1;}/**
|
|
1509
1550
|
* Sets a callback to be invoked when RoktManager becomes ready
|
|
1510
1551
|
*/return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g,h,i){var j,k,l=a||{},m=l.userAttributeFilters,n=l.settings,o=n||{},p=o.placementAttributesMapping,q=o.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(j=null===q||void 0===q?void 0:q.toLowerCase())&&void 0!==j?j:null,this.identityService=c,this.store=d,this.logger=e,this.errorReporter=h,this.loggingService=i,this.captureTiming=g,null===(k=this.captureTiming)||void 0===k?void 0:k.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:m,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(p);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
|
|
1511
1552
|
// It is set here and passed in to the createLauncher method in the Rokt Kit
|
|
@@ -1515,12 +1556,12 @@ var r=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set he
|
|
|
1515
1556
|
// to the Rokt Launcher.
|
|
1516
1557
|
this.launcherOptions=__assign({sandbox:r},null===f||void 0===f?void 0:f.launcherOptions),(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,e,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)),null===(d=this.loggingService)||void 0===d?void 0:d.log({message:"RoktManager: Kit attached, Rokt is ready",code:ErrorCodes.ROKT_KIT_ATTACHED}),this.processMessageQueue();try{null===(e=this.onReadyCallback)||void 0===e?void 0:e.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;return __awaiter(this,void 0,void 0,function(){var k,l,m,n,o,p,q,r,s,t,u,v,w,x,x,y,z,A,B,C,D=this;return __generator(this,function(){// Queue if kit isn't ready OR if identity is in flight
|
|
1517
1558
|
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(k=a.attributes,l=(null===k||void 0===k?void 0:k.sandbox)||null,m=this.mapPlacementAttributes(k,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(n=obfuscateDevData(k,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(n,null,2)))),this.currentUser=this.identityService.getCurrentUser(),o=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},p=o.email,q=m.email,r=void 0,s=void 0,t=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),t&&(r=o[this.mappedEmailShaIdentityType],s=m.emailsha256||m[this.mappedEmailShaIdentityType]||void 0),u=this.hasIdentityChanged(p,q),v=this.hasIdentityChanged(r,s),w={},u&&(w.email=q,q&&(x="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(x),null===(i=this.errorReporter)||void 0===i?void 0:i.report({message:x,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING}))),v&&(w[this.mappedEmailShaIdentityType]=s,x="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(x),null===(j=this.errorReporter)||void 0===j?void 0:j.report({message:x,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING})),!isEmpty(w))// Fire-and-forget identify — best-effort, does not block selectPlacements
|
|
1518
|
-
try{this.identityService.identify({userIdentities:__assign(__assign({},o),w)},function(a){var b=+(null===a||void 0===a?void 0:a.httpCode);b&&(400<=b||0>b)&&D.logger.error("Background identify failed with HTTP "+b),D.processMessageQueue();});}catch(a){y=a instanceof Error?a.message:JSON.stringify(a),this.logger.error("Background identify threw an error: "+y);}return z=__assign(__assign({},o),w),this.setUserAttributes(m),A=__assign(__assign({},m),null===l?{}:{sandbox:l}),z.email&&!A.email&&(A.email=z.email),t&&(B=z[this.mappedEmailShaIdentityType],B&&!A.emailsha256&&!A[this.mappedEmailShaIdentityType]&&(A.emailsha256=B)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,C=__assign(__assign({},a),{attributes:A}),[2/*return*/,this.kit.selectPlacements(C)]}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,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,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=o.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=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[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){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},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.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[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
|
|
1559
|
+
try{this.identityService.identify({userIdentities:__assign(__assign({},o),w)},function(a){var b=+(null===a||void 0===a?void 0:a.httpCode);b&&(400<=b||0>b)&&D.logger.error("Background identify failed with HTTP "+b),D.processMessageQueue();});}catch(a){y=a instanceof Error?a.message:JSON.stringify(a),this.logger.error("Background identify threw an error: "+y);}return z=__assign(__assign({},o),w),this.setUserAttributes(m),A=__assign(__assign({},m),null===l?{}:{sandbox:l}),z.email&&!A.email&&(A.email=z.email),t&&(B=z[this.mappedEmailShaIdentityType],B&&!A.emailsha256&&!A[this.mappedEmailShaIdentityType]&&(A.emailsha256=B)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,C=__assign(__assign({},a),{attributes:A}),[2/*return*/,this.kit.selectPlacements(C)]}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,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,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=o.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=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[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){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},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){var b=a instanceof Error?a.message:a+"";this.logger.error("Failed to register onShoppableAdsReady callback: ".concat(b));}},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,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[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
|
|
1519
1560
|
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
|
|
1520
1561
|
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
|
|
1521
1562
|
var h=a.resolve,i=a.reject,j=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),i&&i(c);};try{var k=b[a.methodName](a.payload);// Handle both sync and async methods
|
|
1522
1563
|
Promise.resolve(k).then(function(a){h&&h(a);})["catch"](j);}catch(a){j(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
|
|
1523
|
-
},a}()
|
|
1564
|
+
},a}();// The purpose of this class is to create a link between the Core mParticle SDK and the
|
|
1524
1565
|
|
|
1525
1566
|
/**
|
|
1526
1567
|
* CookieConsentManager handles storage and access of consent flags (noFunctional, noTargeting)
|
|
@@ -1752,6 +1793,6 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot
|
|
|
1752
1793
|
* @param {String} apiKey your mParticle assigned API key
|
|
1753
1794
|
* @param {Object} [config] an options object for additional configuration
|
|
1754
1795
|
* @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples.
|
|
1755
|
-
*/this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this._registerErrorReportingService=function(b){a.getInstance()._registerErrorReportingService(b);},this._registerLoggingService=function(b){a.getInstance()._registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator);
|
|
1796
|
+
*/this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);},search:function search(b,c,d){a.getInstance().Identity.search(b,c,d);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this._registerErrorReportingService=function(b){a.getInstance()._registerErrorReportingService(b);},this._registerLoggingService=function(b){a.getInstance()._registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator);
|
|
1756
1797
|
|
|
1757
1798
|
export { mParticleManager as default };
|