Socket
Socket
Sign inDemoInstall

@mparticle/web-sdk

Package Overview
Dependencies
Maintainers
7
Versions
108
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mparticle/web-sdk - npm Package Compare versions

Comparing version 2.9.12-rc.2 to 2.9.13-rc.1

src/filteredMparticleUser.js

364

CHANGELOG.md
## Releases
--
#### 2.9.13 - 2019-10-09
- Refactor codebase with Prettier
- Bugfix - Resolve Sonarqube code smells
- Modify Rollup builds
#### 2.9.12 - 2019-10-02
* Support event batching and beacon API; provide new Events API v3 endpoint which supports batching
* Implement Typescript and Babel compilation
* Feat - Enable configuration of config endpoint
- Support event batching and beacon API; provide new Events API v3 endpoint which supports batching
- Implement Typescript and Babel compilation
- Feat - Enable configuration of config endpoint
#### 2.9.11 - 2019-09-26
* Feat - Add Base Event functionality to core for future child SDK use
* Update .eslintrc, fix urls in yuidoc comments
- Feat - Add Base Event functionality to core for future child SDK use
- Update .eslintrc, fix urls in yuidoc comments
#### 2.9.10 - 2019-08-21
* Add integration tests for bundlers (webpack, browserify, rollup)
* Bugfix - Make getCartProducts more robust
* Bugfix - Fix immediate logging for self hosting
* Feat - add session start to server DTO
* Bugfix - update modify old_value
- Add integration tests for bundlers (webpack, browserify, rollup)
- Bugfix - Make getCartProducts more robust
- Bugfix - Fix immediate logging for self hosting
- Feat - add session start to server DTO
- Bugfix - update modify old_value
#### 2.9.9 - 2019-08-07
* Bugfix - Check all event attributes when forwarding rules are set
- Bugfix - Check all event attributes when forwarding rules are set
#### 2.9.8 - 2019-08-07
* Migrate to ES6 Modules; Replace Browserify with Rollup
- Migrate to ES6 Modules; Replace Browserify with Rollup
#### 2.9.7 - 2019-07-16
* Bugfix - noHttpCoverage code properly sent to callback
* Bugfix - Configure forwarders prior to identify callback
- Bugfix - noHttpCoverage code properly sent to callback
- Bugfix - Configure forwarders prior to identify callback
#### 2.9.6 - 2019-07-08
* Bugfix - Alias requests respect isDevelopmentMode setting
- Bugfix - Alias requests respect isDevelopmentMode setting
#### 2.9.5 - 2019-07-01
* Bugfix - set isInitialized in both web and webview contexts
* Feature: log error custom attributes
* Update build parameters
- Bugfix - set isInitialized in both web and webview contexts
- Feature: log error custom attributes
- Update build parameters
#### 2.9.4 - 2019-06-25
* Modify files for self hosting
* Add a /config endpoint
* Accept 2nd argument to init for configuration
* Bugfix - Initialize Logger before Store
- Modify files for self hosting
- Add a /config endpoint
- Accept 2nd argument to init for configuration
- Bugfix - Initialize Logger before Store
#### 2.9.3 - 2019-06-20
* Bugfix - retain mParticle.isIOS on script load
- Bugfix - retain mParticle.isIOS on script load
#### 2.9.2 - 2019-06-10
* Bugfix - respect mParticle.isIOS setting
- Bugfix - respect mParticle.isIOS setting
#### 2.9.1 - 2019-06-05
* Make endpoints configurable
- Make endpoints configurable
#### 2.9.0 - 2019-05-28
* Implement User Aliasing
* Bugfixes - Helpers.debug & set isFirstRun to false after app inits for the first time
- Implement User Aliasing
- Bugfixes - Helpers.debug & set isFirstRun to false after app inits for the first time
#### 2.8.12 - 2019-05-08
* Implement firstSeen and lastSeen fields for MParticleUser
* Sort MParticleUser Array returned by getUsers() by lastSeenTime
* Bugfix - Callback validation & correct warning message
* Add getPreviousUser() to Identity callbacks
- Implement firstSeen and lastSeen fields for MParticleUser
- Sort MParticleUser Array returned by getUsers() by lastSeenTime
- Bugfix - Callback validation & correct warning message
- Add getPreviousUser() to Identity callbacks
#### 2.8.11 - 2019-04-24
* Refactor config into a class
* Implement Logger
* Fix consent object validation and remove unneeded null check
- Refactor config into a class
- Implement Logger
- Fix consent object validation and remove unneeded null check
#### 2.8.10 - 2019-04-10
* Prefer modules over public mParticle methods
- Prefer modules over public mParticle methods
#### 2.8.9 - 2019-03-13
* Simplify / remove migrations
- Simplify / remove migrations
#### 2.8.8 - 2019-02-20
* Bugfix - Native SDK - prioritize equality of requiredWebviewBridgeName
- Bugfix - Native SDK - prioritize equality of requiredWebviewBridgeName
#### 2.8.7 - 2019-02-14
* Update native bridge logic
- Update native bridge logic
#### 2.8.6 - 2019-02-14
* Namespace localstorage with workspace token
- Namespace localstorage with workspace token
#### 2.8.5 - 2019-02-13
* Add callback to location tracking method
- Add callback to location tracking method
#### 2.8.4 - 2019-02-04
* Set session attributes when using native bridge
- Set session attributes when using native bridge
#### 2.8.3 - 2019-01-30
* Bugfix - Check for LocalStorage before migrating
- Bugfix - Check for LocalStorage before migrating
#### 2.8.2 - 2019-01-25
* Bugfix - Guard against undefined result from crypto API
* Bugfix - Call identify if cookies exist, but there is no current user
- Bugfix - Guard against undefined result from crypto API
- Bugfix - Call identify if cookies exist, but there is no current user
#### 2.8.1 - 2019-01-23
* Add identityMethod to onUserIdentified function definition
* Bugfix - return 0 instead of null for hashing boolean false
- Add identityMethod to onUserIdentified function definition
- Bugfix - return 0 instead of null for hashing boolean false
#### 2.8.0 - 2018-12-19
* Fix autogen yuidocs comments
* Add get/setIntegrationAttribute APIs
* Add snippet tests
* Add boolean validation for isDevelopmentMode
- Fix autogen yuidocs comments
- Add get/setIntegrationAttribute APIs
- Add snippet tests
- Add boolean validation for isDevelopmentMode
#### 2.7.8 - 2018-10-24
* Initialize forwarders based on logged in status
- Initialize forwarders based on logged in status
#### 2.7.7 - 2018-10-15
* Bugfix - remove cart item uses proper product persistence
* Bugfix - Guard against corrupt local storage/cookies
- Bugfix - remove cart item uses proper product persistence
- Bugfix - Guard against corrupt local storage/cookies
#### 2.7.6 - 2018-10-10
* Bugfix - guard against null cookie
- Bugfix - guard against null cookie
#### 2.7.5 - 2018-09-19
* Add getUser method to identity callback results
* Only call initial identify and callback once
* Bugfix - logLevel
- Add getUser method to identity callback results
- Only call initial identify and callback once
- Bugfix - logLevel
#### 2.7.4 - 2018-09-14
* Bugfix - Remove corrupt localStorage
* Bugfix - Fix encoding LS for special characters
- Bugfix - Remove corrupt localStorage
- Bugfix - Fix encoding LS for special characters
#### 2.7.3 - 2018-08-30
* Bugfix - Always init forwarder when no UA filters are present
- Bugfix - Always init forwarder when no UA filters are present
#### 2.7.2 - 2018-08-22
* Re-initialize forwarders after userAttr changes
* Capitalize all letters in sessionId
- Re-initialize forwarders after userAttr changes
- Capitalize all letters in sessionId
#### 2.7.1 - 2018-08-10
* Bugfix - Create copy of MP.eventQueue to iterate through
- Bugfix - Create copy of MP.eventQueue to iterate through
#### 2.7.0 - 2018-08-08
* Add setUserAttributes to public API
- Add setUserAttributes to public API
#### 2.6.4 - 2018-08-01
* Implement forwarderUploader module, feaure flags, batch forwarder stats
* Bugfix - Change ProductActionTypes to be consistent with mobile/S2S
- Implement forwarderUploader module, feaure flags, batch forwarder stats
- Bugfix - Change ProductActionTypes to be consistent with mobile/S2S
#### 2.6.3 - 2018-07-18
* Implement customFlags per public API method
- Implement customFlags per public API method
#### 2.6.2 - 2018-07-16
* Update growl and hoek for testing dependencies
* Bugfix - sendEventToForwarder fix
- Update growl and hoek for testing dependencies
- Bugfix - sendEventToForwarder fix
#### 2.6.1 - 2018-07-11
* Default forceHttps to true
* Add apiClient module
- Default forceHttps to true
- Add apiClient module
#### 2.6.0 - 2018-06-20
* Implement Consent forwarding rules
- Implement Consent forwarding rules
#### 2.5.1 - 2018-06-11
* Bugfix - Fix filterUserAttributeValues break/continue
- Bugfix - Fix filterUserAttributeValues break/continue
#### 2.5.0 - 2018-06-06
* Expose getUser and getUsers to public Identity API
* Bugfix - send newUser to forwarder on user identified
* Add filtered user object
- Expose getUser and getUsers to public Identity API
- Bugfix - send newUser to forwarder on user identified
- Add filtered user object
#### 2.4.1 - 2018-05-09
* Bugfix - encode event value before sending to iOS
* Update package-lock.json to pass CI tests
- Bugfix - encode event value before sending to iOS
- Update package-lock.json to pass CI tests
#### 2.4.0 - 2018-04-26
* Implement Consent State
* Expose Identitiy HTTP constants to the public
- Implement Consent State
- Expose Identitiy HTTP constants to the public
#### 2.3.3 - 2018-04-19
* Bugfix - filter user attributes to forwarders on init
- Bugfix - filter user attributes to forwarders on init
#### 2.3.2 - 2018-04-04
* Bugfix - filter user attributes to forwarders on init
- Bugfix - filter user attributes to forwarders on init
#### 2.3.1 - 2018-04-02
* Bugfix - Compare strings when filtering event/user attribute values
- Bugfix - Compare strings when filtering event/user attribute values
#### 2.3.0 - 2018-03-28
* Bugfix - Prioritize client entered config over persistence
* Bugfix - Correct capitalization of clearing eCommerce carts
* Add Identify to public API
- Bugfix - Prioritize client entered config over persistence
- Bugfix - Correct capitalization of clearing eCommerce carts
- Add Identify to public API
#### 2.2.6 - 2018-03-07
* Add forceHttps as a config option
* Fix linting
* Migrate all mpids between cookies and LS when useCookieStorage changes
- Add forceHttps as a config option
- Fix linting
- Migrate all mpids between cookies and LS when useCookieStorage changes
#### 2.2.5 - 2018-03-01
* Bugfix - add shouldUseNativeSdk logic to fix null user and null path values
- Bugfix - add shouldUseNativeSdk logic to fix null user and null path values
#### 2.2.4 - 2018-02-28
* Add config option for maxCookieSize
* Refactor useNativeSdk and prevent identify calls when in webview
- Add config option for maxCookieSize
- Refactor useNativeSdk and prevent identify calls when in webview
#### 2.2.3 - 2018-02-23
* Update logic for useNativeSdk and isIOS
- Update logic for useNativeSdk and isIOS
#### 2.2.2 - 2018-02-20
* Pass identityApiData to native SDKs
- Pass identityApiData to native SDKs
#### 2.2.1 - 2018-02-14
* Queue events when mpid is null or 0
* Stub primary methods for pre-loading SDK invocation
* Add eventSubscriptionId to forwarder contract
* Update readme to remove adchemix
- Queue events when mpid is null or 0
- Stub primary methods for pre-loading SDK invocation
- Add eventSubscriptionId to forwarder contract
- Update readme to remove adchemix
#### 2.2.0 - 2018-01-31
* Remove product bags
- Remove product bags
#### 2.1.5 - 2018-01-25
* Update version endpoint for /Forwarding
- Update version endpoint for /Forwarding
#### 2.1.4 - 2018-01-10
* Ensure customerid is always the first identity being set
* Auto generate API docs
* Add migration for base64 encoded products
* Finalize Other IDs
* Bugfix - Adjust logic for session end event
- Ensure customerid is always the first identity being set
- Auto generate API docs
- Add migration for base64 encoded products
- Finalize Other IDs
- Bugfix - Adjust logic for session end event
#### 2.1.3 - 2017-12-20
* Remove logLTVIncrease
* Return an empty array when there are no cart products
* Bugfix - Adjust arguments for applyToForwarders
- Remove logLTVIncrease
- Return an empty array when there are no cart products
- Bugfix - Adjust arguments for applyToForwarders
#### 2.1.2 - 2017-12-14
* Add setForwarderOnUserIdentified, return null currentUser when MPID is null
- Add setForwarderOnUserIdentified, return null currentUser when MPID is null
#### 2.1.1 - 2017-12-13
* Modularize tests for readability and robustness
* Adjust Application State Transition, include initial location
* Bugfix - Add CheckoutOption to ProductAction-related switch statements
* Add parseStringOrNumber function
* Sanitize additional attributes
* Correct order of internal createProducts arguments
* Refactor logPageView
* Require explicit UIWebview binding
- Modularize tests for readability and robustness
- Adjust Application State Transition, include initial location
- Bugfix - Add CheckoutOption to ProductAction-related switch statements
- Add parseStringOrNumber function
- Sanitize additional attributes
- Correct order of internal createProducts arguments
- Refactor logPageView
- Require explicit UIWebview binding
#### 2.1.0 - 2017-11-30
* Migrate persistence to v4
* Add onUserAlias callback
- Migrate persistence to v4
- Add onUserAlias callback
#### 2.0.13 - 2017-11-08
* Add support for filtering user attribute values
* Update persistence after a modify call
- Add support for filtering user attribute values
- Update persistence after a modify call
#### 2.0.12 - 2017-10-23
* Complete modularization of SDK
- Complete modularization of SDK
#### 2.0.11 - 2017-10-19
* Modularize Types, Constants, Helpers, DTO, Identity, Ecommerce
* Reorganize tests
- Modularize Types, Constants, Helpers, DTO, Identity, Ecommerce
- Reorganize tests
#### 2.0.10 - 2017-10-17
* Bugfix - Execute useLocalStorage method
- Bugfix - Execute useLocalStorage method
#### 1.14.1 - 2017-06-22
* Fixes for cookie syncing. Properly cookie sync when MPID changes, and only perform a cookie sync when debug modes for defined pixel and mParticle match
* Store productBags and cartProducts to cookies, with config option to change number of products allowed in each (config.maxProducts = 20 by default)
* Prevent setUserIdentity from accepting booleans
* Clean up code - Add additional validations, convert remaining == to ===
- Fixes for cookie syncing. Properly cookie sync when MPID changes, and only perform a cookie sync when debug modes for defined pixel and mParticle match
- Store productBags and cartProducts to cookies, with config option to change number of products allowed in each (config.maxProducts = 20 by default)
- Prevent setUserIdentity from accepting booleans
- Clean up code - Add additional validations, convert remaining == to ===
#### 1.14.0 - 2017-06-15
* Support for cookie-syncing. Cookie-syncing enables the optional collection of 3rd-party IDs to enable enhanced audience sharing with advertising platforms such as DoubleClick, Adobe, and AppNexus
* Add application state transition to mParticle initialization
- Support for cookie-syncing. Cookie-syncing enables the optional collection of 3rd-party IDs to enable enhanced audience sharing with advertising platforms such as DoubleClick, Adobe, and AppNexus
- Add application state transition to mParticle initialization
#### 1.13.1 - 2017-05-25
* Fix for removing duplicate user identities where ID is missing, allow ID to be `undefined`
* Fix for creating CGID on initial load
- Fix for removing duplicate user identities where ID is missing, allow ID to be `undefined`
- Fix for creating CGID on initial load
#### 1.13.0 - 2017-05-18
* Send sessionLength to server when sessionEnd is called.
- Send sessionLength to server when sessionEnd is called.
#### 1.12.0 - 2017-05-11
* Add deviceId, and deviceId retrieval via `mParticle.getDeviceId()`.
- Add deviceId, and deviceId retrieval via `mParticle.getDeviceId()`.
#### 1.11.0 - 2017-04-27
* Add new session management.
* Fixed a bug where the same sessionId may be associated with events over several days.
- Add new session management.
- Fixed a bug where the same sessionId may be associated with events over several days.
#### 1.10.0 - 2017-04-20
* Added config option for useCookieStorage to allow use of either cookies or localStorage. By default, localStorage is used (useCookieStorage = false). If localStorage not available, reverts to cookie use.
* Fixed a bug where `forwarders` contained a mix of both initialized and uninitialized forwarders. `forwarders` now only contains initialized forwarders.
- Added config option for useCookieStorage to allow use of either cookies or localStorage. By default, localStorage is used (useCookieStorage = false). If localStorage not available, reverts to cookie use.
- Fixed a bug where `forwarders` contained a mix of both initialized and uninitialized forwarders. `forwarders` now only contains initialized forwarders.
#### 1.9.0 - 2017-04-17
* Fixed bug where calling setUserIdentity with a similar type added another identity, rather than replacing the identity.
* Calling setUserIdentity with `id = null` and valid type will remove the user identity of that type.
* Include CommerceEvent custom attributions in expansion; makes a copy of the original commerce event rather than referencing it, which would mutate it.
- Fixed bug where calling setUserIdentity with a similar type added another identity, rather than replacing the identity.
- Calling setUserIdentity with `id = null` and valid type will remove the user identity of that type.
- Include CommerceEvent custom attributions in expansion; makes a copy of the original commerce event rather than referencing it, which would mutate it.
{
"name": "@mparticle/web-sdk",
"version": "2.9.12-rc.2",
"description": "mParticle core SDK for web applications",
"license": "Apache-2.0",
"keywords": [
"mparticle",
"analytics",
"cdp"
],
"files": [
"dist/mparticle.common.js",
"dist/mparticle.esm.js",
"src/"
],
"main": "dist/mparticle.common.js",
"module": "dist/mparticle.esm.js",
"repository": "https://github.com/mParticle/mparticle-web-sdk",
"scripts": {
"build": "ENVIRONMENT=prod rollup --config rollup.config.js",
"build:dev": "ENVIRONMENT=dev rollup --config rollup.config.js",
"build:tests:prod": "ENVIRONMENT=prod rollup --config rollup.test.config.js",
"build:docs": "yuidoc src/",
"build:snippet": "uglifyjs snippet.js -nm -o snippet.min.js",
"build:browserify:cjs": "browserify test/integrations/cjs/browserify/index.js -o test/integrations/cjs/dist/browserify-output.js && npm run test:karma:browserify:cjs",
"build:rollup:cjs": "rollup --config test/integrations/cjs/rollup/rollup.config.js && npm run test:karma:rollup:cjs",
"build:webpack:cjs": "webpack --config test/integrations/cjs/webpack/webpack.config.js && npm run test:karma:webpack:cjs",
"build:rollup:module": "rollup --config test/integrations/module/rollup/rollup.config.js && npm run test:karma:rollup:module",
"build:webpack:module": "webpack --config test/integrations/module/webpack/webpack.config.js && npm run test:karma:webpack:module",
"build:ts": "tsc -p .",
"test": "npm run build && npm run build:tests:prod && DEBUG=false karma start test/karma.config.js",
"test:debug": "DEBUG=true karma start test/karma.config.js",
"test:stub": "npm run build:tests:prod && karma start test/stub/karma.stub.config.js",
"test:integrations": "npm run test:requirejs && npm run test:integrations:cjs && npm run test:integrations:module",
"test:integrations:cjs": "npm run build:browserify:cjs && npm run build:webpack:cjs && npm run build:rollup:cjs",
"test:integrations:module": "npm run build:webpack:module && npm run build:rollup:module",
"test:requirejs": "npm run test:requirejs:before && npm run test:requirejs:after",
"test:requirejs:before": "FILE_ORDER=before_mp karma start test/integrations/requirejs/karma.requirejs.config.js",
"test:requirejs:after": "FILE_ORDER=after_mp karma start test/integrations/requirejs/karma.requirejs.config.js",
"test:karma:webpack:cjs": "BUNDLER=webpack karma start test/integrations/cjs/karma.webpack.config.js",
"test:karma:browserify:cjs": "BUNDLER=browserify karma start test/integrations/cjs/karma.browserify.config.js",
"test:karma:rollup:cjs": "BUNDLER=rollup karma start test/integrations/cjs/karma.rollup.config.js",
"test:karma:webpack:module": "BUNDLER=webpack karma start test/integrations/module/karma.webpack.config.js",
"test:karma:rollup:module": "BUNDLER=rollup karma start test/integrations/module/karma.rollup.config.js",
"watch": "ENVIRONMENT=dev rollup --config rollup.config.js -w",
"watch:tests": "ENVIRONMENT=dev rollup --config rollup.test.config.js -w",
"lint": "eslint src/ test/src/",
"gts:check": "gts check",
"gts:fix": "gts fix"
},
"pre-commit": [
"lint"
],
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/plugin-proposal-class-properties": "^7.5.5",
"@babel/plugin-proposal-object-rest-spread": "^7.5.5",
"@babel/plugin-transform-runtime": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-typescript": "^7.6.0",
"@types/chai": "^4.2.3",
"@types/mocha": "^5.2.7",
"@types/node": "^10.0.3",
"babel-preset-minify": "^0.5.1",
"browser-sync": "^2.26.3",
"browserify": "^16.3.0",
"chai": "^4.2.0",
"eslint": "^6.4.0",
"gts": "^1.1.0",
"karma": "^4.0.1",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-edge-launcher": "^0.4.1",
"karma-firefox-launcher": "^1.0.1",
"karma-ie-launcher": "^1.0.0",
"karma-junit-reporter": "^1.2.0",
"karma-mocha": "^1.3.0",
"karma-safari-launcher": "^1.0.0",
"karma-should": "^1.0.0",
"mocha": "^6.0.2",
"pre-commit": "^1.2.2",
"rollup": "^1.19.4",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-typescript": "^1.0.1",
"shelljs": "^0.7.8",
"should": "^7.1.0",
"sinon": "^7.4.1",
"tslib": "^1.10.0",
"typescript": "^3.6.2",
"uglify-js": "^3.4.9",
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"yuidocjs": "^0.10.2"
},
"dependencies": {
"@babel/runtime": "^7.6.0"
}
"name": "@mparticle/web-sdk",
"version": "2.9.13-rc.1",
"description": "mParticle core SDK for web applications",
"license": "Apache-2.0",
"keywords": [
"mparticle",
"analytics",
"cdp"
],
"files": [
"dist/mparticle.common.js",
"dist/mparticle.esm.js",
"src/"
],
"main": "dist/mparticle.common.js",
"module": "dist/mparticle.esm.js",
"repository": "https://github.com/mParticle/mparticle-web-sdk",
"scripts": {
"build": "ENVIRONMENT=prod BUILDALL=true rollup --config rollup.config.js",
"build:dev": "ENVIRONMENT=dev BUILD=iife rollup --config rollup.config.js",
"build:iife": "ENVIRONMENT=prod BUILD=iife rollup --config rollup.config.js",
"build:npm": "ENVIRONMENT=prod BUILD=cjs rollup --config rollup.config.js",
"build:esm": "ENVIRONMENT=prod BUILD=esm rollup --config rollup.config.js",
"build:stub": "ENVIRONMENT=prod BUILD=stub rollup --config rollup.config.js",
"build:docs": "yuidoc src/",
"build:snippet": "uglifyjs snippet.js -nm -o snippet.min.js",
"build:browserify:cjs": "browserify test/integrations/cjs/browserify/index.js -o test/integrations/cjs/dist/browserify-output.js && npm run test:karma:browserify:cjs",
"build:rollup:cjs": "rollup --config test/integrations/cjs/rollup/rollup.config.js && npm run test:karma:rollup:cjs",
"build:webpack:cjs": "webpack --config test/integrations/cjs/webpack/webpack.config.js && npm run test:karma:webpack:cjs",
"build:rollup:module": "rollup --config test/integrations/module/rollup/rollup.config.js && npm run test:karma:rollup:module",
"build:webpack:module": "webpack --config test/integrations/module/webpack/webpack.config.js && npm run test:karma:webpack:module",
"build:ts": "tsc -p .",
"test": "npm run build && TESTTYPE=main ENVIRONMENT=prod rollup --config rollup.test.config.js && DEBUG=false karma start test/karma.config.js",
"test:debug": "DEBUG=true karma start test/karma.config.js",
"test:stub": "TESTTYPE=stub ENVIRONMENT=prod rollup --config rollup.test.config.js && karma start test/stub/karma.stub.config.js",
"test:integrations": "npm run test:requirejs && npm run test:integrations:cjs && npm run test:integrations:module",
"test:integrations:cjs": "npm run build:browserify:cjs && npm run build:webpack:cjs && npm run build:rollup:cjs",
"test:integrations:module": "npm run build:webpack:module && npm run build:rollup:module",
"test:requirejs": "npm run test:requirejs:before && npm run test:requirejs:after",
"test:requirejs:before": "FILE_ORDER=before_mp karma start test/integrations/requirejs/karma.requirejs.config.js",
"test:requirejs:after": "FILE_ORDER=after_mp karma start test/integrations/requirejs/karma.requirejs.config.js",
"test:karma:webpack:cjs": "BUNDLER=webpack karma start test/integrations/cjs/karma.webpack.config.js",
"test:karma:browserify:cjs": "BUNDLER=browserify karma start test/integrations/cjs/karma.browserify.config.js",
"test:karma:rollup:cjs": "BUNDLER=rollup karma start test/integrations/cjs/karma.rollup.config.js",
"test:karma:webpack:module": "BUNDLER=webpack karma start test/integrations/module/karma.webpack.config.js",
"test:karma:rollup:module": "BUNDLER=rollup karma start test/integrations/module/karma.rollup.config.js",
"watch": "ENVIRONMENT=dev BUILD=iife rollup --config rollup.config.js -w",
"watch:all": "ENVIRONMENT=dev WATCHALL=true rollup --config rollup.config.js -w",
"watch:tests": "ENVIRONMENT=dev rollup --config rollup.test.config.js -w",
"lint": "eslint src/ test/src/",
"gts:check": "gts check",
"gts:fix": "gts fix",
"prettier": "node_modules/.bin/prettier --check \"**/*.js\""
},
"pre-commit": [
"lint"
],
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/plugin-proposal-class-properties": "^7.5.5",
"@babel/plugin-proposal-object-rest-spread": "^7.5.5",
"@babel/plugin-transform-runtime": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-typescript": "^7.6.0",
"@types/chai": "^4.2.3",
"@types/mocha": "^5.2.7",
"@types/node": "^10.0.3",
"babel-preset-minify": "^0.5.1",
"browser-sync": "^2.26.3",
"browserify": "^16.3.0",
"chai": "^4.2.0",
"eslint": "^6.4.0",
"eslint-config-prettier": "6.3.0",
"eslint-plugin-prettier": "3.1.1",
"gts": "^1.1.0",
"karma": "^4.0.1",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-edge-launcher": "^0.4.1",
"karma-firefox-launcher": "^1.0.1",
"karma-ie-launcher": "^1.0.0",
"karma-junit-reporter": "^1.2.0",
"karma-mocha": "^1.3.0",
"karma-safari-launcher": "^1.0.0",
"karma-should": "^1.0.0",
"mocha": "^6.0.2",
"pre-commit": "^1.2.2",
"prettier": "1.18.2",
"rollup": "^1.19.4",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-typescript": "^1.0.1",
"shelljs": "^0.7.8",
"should": "^7.1.0",
"sinon": "^7.4.1",
"tslib": "^1.10.0",
"typescript": "^3.6.2",
"uglify-js": "^3.4.9",
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"yuidocjs": "^0.10.2"
},
"dependencies": {
"@babel/runtime": "^7.6.0"
}
}
<img src="https://static.mparticle.com/sdk/mp_logo_black.svg" width="280"><br>
<!-- <img src="https://img.shields.io/github/release/mparticle/mparticle-web-sdk.svg?color=green"> <img src ="https://img.shields.io/npm/v/@mparticle/web-sdk.svg?color=green"> -->
# mParticle Javascript SDK

@@ -12,5 +10,7 @@

## Documentation
Fully detailed documentation and other information about mParticle web SDK can be found at our doc site [here](https://docs.mparticle.com/developers/sdk/web/getting-started)
## Include and Initialize the SDK
There are 2 ways to initialize the SDK, either via a snippet script in your HTML file, or via npm if you plan to self host. A summary of directions for both are available below, but you should review detailed directions for the [snippet script](https://docs.mparticle.com/developers/sdk/web/getting-started) and our [self hosting](https://docs.mparticle.com/developers/sdk/web/self-hosting) options on our doc site.

@@ -20,3 +20,2 @@

#### 1. Customize the SDK

@@ -31,7 +30,10 @@

identifyRequest: {
userIdentities: { email: 'email@example.com', customerid: '123456' }
userIdentities: {
email: 'email@example.com',
customerid: '123456',
},
},
identityCallback: myIdentityCallback
}
}
identityCallback: myIdentityCallback,
},
};
```

@@ -72,3 +74,6 @@

```javascript
mParticle.logEvent('Play Movie', mParticle.EventType.Navigation, {'movie_length':'127 minutes','rating':'PG'});
mParticle.logEvent('Play Movie', mParticle.EventType.Navigation, {
movie_length: '127 minutes',
rating: 'PG',
});
```

@@ -79,2 +84,3 @@

In your root directory:
```

@@ -103,24 +109,23 @@ npm i @mparticle/web-sdk

## Creating an Integration
If you configure mParticle via a snippet tag, the Javascript SDK is able to automatically include, initialize, and delegate API calls to 3rd-party Javascript SDKs. Otherwise you will install them via npm. For more instructions on installing via npm, view the [documentation](https://docs.mparticle.com/developers/sdk/web/self-hosting).
If you configure mParticle via a snippet tag, the Javascript SDK is able to automatically include, initialize, and delegate API calls to 3rd-party Javascript SDKs. Otherwise you will install them via npm. For more instructions on installing via npm, view the [documentation](https://docs.mparticle.com/developers/sdk/web/self-hosting).
If you would like to add your company as a new Javascript integration, reference the following integrations as examples:
- [Amplitude](https://github.com/mparticle-integrations/mparticle-javascript-integration-amplitude)
- [Appboy](https://github.com/mparticle-integrations/mparticle-javascript-integration-appboy)
- [BingAds](https://github.com/mparticle-integrations/mparticle-javascript-integration-bingads)
- [Device Match](https://github.com/mparticle-integrations/mparticle-javascript-integration-device-match)
- [Facebook](https://github.com/mparticle-integrations/mparticle-javascript-integration-facebook)
- [Google Analytics](https://github.com/mparticle-integrations/mparticle-javascript-integration-google-analytics)
- [Inspectlet](https://github.com/mparticle-integrations/mparticle-javascript-integration-inspectlet)
- [Intercom](https://github.com/mparticle-integrations/mparticle-javascript-integration-intercom)
- [Kahuna](https://github.com/mparticle-integrations/mparticle-javascript-integration-kahuna)
- [Kissmetrics](https://github.com/mparticle-integrations/mparticle-javascript-integration-kissmetrics)
- [Localytics](https://github.com/mparticle-integrations/mparticle-javascript-integration-localytics)
- [Mixpanel](https://github.com/mparticle-integrations/mparticle-javascript-integration-mixpanel)
- [Optimizely](https://github.com/mparticle-integrations/mparticle-javascript-integration-optimizely)
- [SimpleReach](https://github.com/mparticle-integrations/mparticle-javascript-integration-simplereach)
- [Twitter](https://github.com/mparticle-integrations/mparticle-javascript-integration-twitter)
- [Amplitude](https://github.com/mparticle-integrations/mparticle-javascript-integration-amplitude)
- [Appboy](https://github.com/mparticle-integrations/mparticle-javascript-integration-appboy)
- [BingAds](https://github.com/mparticle-integrations/mparticle-javascript-integration-bingads)
- [Device Match](https://github.com/mparticle-integrations/mparticle-javascript-integration-device-match)
- [Facebook](https://github.com/mparticle-integrations/mparticle-javascript-integration-facebook)
- [Google Analytics](https://github.com/mparticle-integrations/mparticle-javascript-integration-google-analytics)
- [Inspectlet](https://github.com/mparticle-integrations/mparticle-javascript-integration-inspectlet)
- [Intercom](https://github.com/mparticle-integrations/mparticle-javascript-integration-intercom)
- [Kahuna](https://github.com/mparticle-integrations/mparticle-javascript-integration-kahuna)
- [Kissmetrics](https://github.com/mparticle-integrations/mparticle-javascript-integration-kissmetrics)
- [Localytics](https://github.com/mparticle-integrations/mparticle-javascript-integration-localytics)
- [Mixpanel](https://github.com/mparticle-integrations/mparticle-javascript-integration-mixpanel)
- [Optimizely](https://github.com/mparticle-integrations/mparticle-javascript-integration-optimizely)
- [SimpleReach](https://github.com/mparticle-integrations/mparticle-javascript-integration-simplereach)
- [Twitter](https://github.com/mparticle-integrations/mparticle-javascript-integration-twitter)

@@ -142,5 +147,7 @@ ## Running the Tests

```
where browserBrand can be another browser such as Edge or IE.
## Development Notes
This package comes with the NPM package [pre-commit](https://www.npmjs.com/package/pre-commit), which will run [ESLint](http://eslint.org/) when you try to commit.

@@ -147,0 +154,0 @@

@@ -15,4 +15,6 @@ import Helpers from './helpers';

function queueEventForBatchUpload(event) {
if (!uploader){
var millis = Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis);
if (!uploader) {
var millis = Helpers.getFeatureFlag(
Constants.FeatureFlags.EventBatchingIntervalMillis
);
uploader = new BatchUploader(mParticle, millis);

@@ -27,4 +29,9 @@ }

}
var eventsV3Percentage = Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3);
if (!eventsV3Percentage || !Helpers.Validators.isNumber(eventsV3Percentage)) {
var eventsV3Percentage = Helpers.getFeatureFlag(
Constants.FeatureFlags.EventsV3
);
if (
!eventsV3Percentage ||
!Helpers.Validators.isNumber(eventsV3Percentage)
) {
return false;

@@ -62,6 +69,9 @@ }

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent, JSON.stringify(event));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.LogEvent,
JSON.stringify(event)
);
return;
}
var mpid,

@@ -72,7 +82,17 @@ currentUser = mParticle.Identity.getCurrentUser();

}
mParticle.Store.requireDelay = Helpers.isDelayedByIntegration(mParticle.preInit.integrationDelays, mParticle.Store.integrationDelayTimeoutStart, Date.now());
mParticle.Store.requireDelay = Helpers.isDelayedByIntegration(
mParticle.preInit.integrationDelays,
mParticle.Store.integrationDelayTimeoutStart,
Date.now()
);
// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
if (!mpid || mParticle.Store.requireDelay || !mParticle.Store.configurationLoaded) {
mParticle.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.');
if (
!mpid ||
mParticle.Store.requireDelay ||
!mParticle.Store.configurationLoaded
) {
mParticle.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.'
);
mParticle.Store.eventQueue.push(event);

@@ -102,7 +122,9 @@ return;

if (xhr.readyState === 4) {
mParticle.Logger.verbose('Received ' + xhr.statusText + ' from server');
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
parseEventResponse(xhr.responseText);
}
};
if (!event) {

@@ -116,10 +138,23 @@ mParticle.Logger.error(Messages.ErrorMessages.EventEmpty);

try {
xhr.open('post', Helpers.createServiceUrl(mParticle.Store.SDKConfig.v2SecureServiceUrl, mParticle.Store.devToken) + '/Events');
xhr.send(JSON.stringify(ServerModel.convertEventToDTO(event, mParticle.Store.isFirstRun)));
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v2SecureServiceUrl,
mParticle.Store.devToken
) + '/Events'
);
xhr.send(
JSON.stringify(
ServerModel.convertEventToDTO(
event,
mParticle.Store.isFirstRun
)
)
);
} catch (e) {
mParticle.Logger.error(
'Error sending event to mParticle servers. ' + e
);
}
catch (e) {
mParticle.Logger.error('Error sending event to mParticle servers. ' + e);
}
}
}

@@ -142,3 +177,5 @@

if (settings && settings.Store) {
mParticle.Logger.verbose('Parsed store from response, updating local settings');
mParticle.Logger.verbose(
'Parsed store from response, updating local settings'
);

@@ -162,4 +199,3 @@ if (!mParticle.Store.serverSettings) {

}
}
else {
} else {
// This is a valid setting

@@ -172,6 +208,7 @@ mParticle.Store.serverSettings[prop] = fullProp;

}
} catch (e) {
mParticle.Logger.error(
'Error parsing JSON response from server: ' + e.name
);
}
catch (e) {
mParticle.Logger.error('Error parsing JSON response from server: ' + e.name);
}
}

@@ -183,3 +220,5 @@

if (xhr.readyState === 4) {
mParticle.Logger.verbose('Received ' + xhr.statusText + ' from server');
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
//only parse error messages from failing requests

@@ -191,3 +230,7 @@ if (xhr.status !== 200 && xhr.status !== 202) {

var errorMessage = response.message;
Helpers.invokeAliasCallback(callback, xhr.status, errorMessage);
Helpers.invokeAliasCallback(
callback,
xhr.status,
errorMessage
);
return;

@@ -205,8 +248,15 @@ }

try {
xhr.open('post', Helpers.createServiceUrl(mParticle.Store.SDKConfig.aliasUrl, mParticle.Store.devToken) + '/Alias');
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.aliasUrl,
mParticle.Store.devToken
) + '/Alias'
);
xhr.send(JSON.stringify(aliasRequest));
}
catch (e) {
} catch (e) {
Helpers.invokeAliasCallback(callback, HTTPCodes.noHttpCoverage, e);
mParticle.Logger.error('Error sending alias request to mParticle servers. ' + e);
mParticle.Logger.error(
'Error sending alias request to mParticle servers. ' + e
);
}

@@ -216,8 +266,24 @@ }

function sendIdentityRequest(identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid) {
var xhr, previousMPID,
function sendIdentityRequest(
identityApiRequest,
method,
callback,
originalIdentityApiData,
parseIdentityResponse,
mpid
) {
var xhr,
previousMPID,
xhrCallback = function() {
if (xhr.readyState === 4) {
mParticle.Logger.verbose('Received ' + xhr.statusText + ' from server');
parseIdentityResponse(xhr, previousMPID, callback, originalIdentityApiData, method);
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
parseIdentityResponse(
xhr,
previousMPID,
callback,
originalIdentityApiData,
method
);
}

@@ -239,9 +305,26 @@ };

if (mParticle.Store.identityCallInFlight) {
Helpers.invokeCallback(callback, HTTPCodes.activeIdentityRequest, 'There is currently an Identity request processing. Please wait for this to return before requesting again');
Helpers.invokeCallback(
callback,
HTTPCodes.activeIdentityRequest,
'There is currently an Identity request processing. Please wait for this to return before requesting again'
);
} else {
previousMPID = mpid || null;
if (method === 'modify') {
xhr.open('post', Helpers.createServiceUrl(mParticle.Store.SDKConfig.identityUrl) + mpid + '/' + method);
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.identityUrl
) +
mpid +
'/' +
method
);
} else {
xhr.open('post', Helpers.createServiceUrl(mParticle.Store.SDKConfig.identityUrl) + method);
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.identityUrl
) + method
);
}

@@ -253,7 +336,11 @@ xhr.setRequestHeader('Content-Type', 'application/json');

}
}
catch (e) {
} catch (e) {
mParticle.Store.identityCallInFlight = false;
Helpers.invokeCallback(callback, HTTPCodes.noHttpCoverage, e);
mParticle.Logger.error('Error sending identity request to servers with status code ' + xhr.status + ' - ' + e);
mParticle.Logger.error(
'Error sending identity request to servers with status code ' +
xhr.status +
' - ' +
e
);
}

@@ -266,6 +353,9 @@ }

try {
url = Helpers.createServiceUrl(mParticle.Store.SDKConfig.v2SecureServiceUrl, mParticle.Store.devToken);
url = Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v2SecureServiceUrl,
mParticle.Store.devToken
);
data = {
uuid: Helpers.generateUniqueId(),
data: forwardingStatsData
data: forwardingStatsData,
};

@@ -277,6 +367,7 @@

}
} catch (e) {
mParticle.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
catch (e) {
mParticle.Logger.error('Error sending forwarding stats to mParticle servers.');
}
}

@@ -290,3 +381,5 @@

if (xhr.status === 202) {
mParticle.Logger.verbose('Successfully sent ' + xhr.statusText + ' from server');
mParticle.Logger.verbose(
'Successfully sent ' + xhr.statusText + ' from server'
);
}

@@ -296,3 +389,6 @@ }

var xhr = Helpers.createXHR(xhrCallback);
url = Helpers.createServiceUrl(mParticle.Store.SDKConfig.v1SecureServiceUrl, mParticle.Store.devToken);
url = Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v1SecureServiceUrl,
mParticle.Store.devToken
);
data = forwardingStatsData;

@@ -304,6 +400,7 @@

}
} catch (e) {
mParticle.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
catch (e) {
mParticle.Logger.error('Error sending forwarding stats to mParticle servers.');
}
}

@@ -315,12 +412,21 @@

var xhrCallback = function() {
if (xhr.readyState === 4) {
if (xhr.readyState === 4) {
// when a 200 returns, merge current config with what comes back from config, prioritizing user inputted config
if (xhr.status === 200) {
config = Helpers.extend({}, config, JSON.parse(xhr.responseText));
config = Helpers.extend(
{},
config,
JSON.parse(xhr.responseText)
);
completeSDKInitialization(apiKey, config);
mParticle.Logger.verbose('Successfully received configuration from server');
mParticle.Logger.verbose(
'Successfully received configuration from server'
);
} else {
// if for some reason a 200 doesn't return, then we initialize with the just the passed through config
completeSDKInitialization(apiKey, config);
mParticle.Logger.verbose('Issue with receiving configuration from server, received HTTP Code of ' + xhr.status);
mParticle.Logger.verbose(
'Issue with receiving configuration from server, received HTTP Code of ' +
xhr.status
);
}

@@ -331,3 +437,7 @@ }

var xhr = Helpers.createXHR(xhrCallback);
url = 'https://' + mParticle.Store.SDKConfig.configUrl + apiKey + '/config?env=';
url =
'https://' +
mParticle.Store.SDKConfig.configUrl +
apiKey +
'/config?env=';
if (config.isDevelopmentMode) {

@@ -343,6 +453,7 @@ url = url + '1';

}
}
catch (e) {
} catch (e) {
completeSDKInitialization(apiKey, config);
mParticle.Logger.error('Error getting forwarder configuration from mParticle servers.');
mParticle.Logger.error(
'Error getting forwarder configuration from mParticle servers.'
);
}

@@ -366,3 +477,3 @@ }

ct: event.Timestamp,
eec: event.ExpandedEventCount
eec: event.ExpandedEventCount,
};

@@ -389,3 +500,3 @@

appendUserInfoToEvents: appendUserInfoToEvents,
shouldEnableBatching: shouldEnableBatching
};
shouldEnableBatching: shouldEnableBatching,
};
import { Batch } from './eventsApiModels';
import Helpers from './helpers';
import { SDKEvent, MParticleUser, MParticleWebSDK, SDKLoggerApi } from './sdkRuntimeModels';
import {
SDKEvent,
MParticleUser,
MParticleWebSDK,
SDKLoggerApi,
} from './sdkRuntimeModels';
import { convertEvents } from './sdkToEventsApiConverter';

@@ -20,6 +25,7 @@

this.uploadIntervalMillis = uploadInterval;
this.batchingEnabled = uploadInterval >= BatchUploader.MINIMUM_INTERVAL_MILLIS;
this.batchingEnabled =
uploadInterval >= BatchUploader.MINIMUM_INTERVAL_MILLIS;
if (this.uploadIntervalMillis < BatchUploader.MINIMUM_INTERVAL_MILLIS) {
this.uploadIntervalMillis = BatchUploader.MINIMUM_INTERVAL_MILLIS;
}
}
this.pendingEvents = [];

@@ -65,4 +71,6 @@ this.pendingUploads = [];

this.pendingEvents.push(event);
this.webSdk.Logger.verbose(`Queuing event: ${JSON.stringify(event)}`);
this.webSdk.Logger.verbose(
`Queuing event: ${JSON.stringify(event)}`
);
this.webSdk.Logger.verbose(
`Queued event count: ${this.pendingEvents.length}`

@@ -101,3 +109,3 @@ );

const mpid = defaultUser.getMPID();
sdkEvent.MPID = mpid
sdkEvent.MPID = mpid;
}

@@ -104,0 +112,0 @@ let events = eventsByUser.get(sdkEvent.MPID);

import Helpers from './helpers';
function createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId) {
if (typeof(consented) !== 'boolean') {
mParticle.Logger.error('Consented boolean is required when constructing a GDPR Consent object.');
function createGDPRConsent(
consented,
timestamp,
consentDocument,
location,
hardwareId
) {
if (typeof consented !== 'boolean') {
mParticle.Logger.error(
'Consented boolean is required when constructing a GDPR Consent object.'
);
return null;
}
if (timestamp && isNaN(timestamp)) {
mParticle.Logger.error('Timestamp must be a valid number when constructing a GDPR Consent object.');
mParticle.Logger.error(
'Timestamp must be a valid number when constructing a GDPR Consent object.'
);
return null;
}
if (consentDocument && typeof(consentDocument) !== 'string') {
mParticle.Logger.error('Document must be a valid string when constructing a GDPR Consent object.');
if (consentDocument && typeof consentDocument !== 'string') {
mParticle.Logger.error(
'Document must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (location && typeof(location) !== 'string') {
mParticle.Logger.error('Location must be a valid string when constructing a GDPR Consent object.');
if (location && typeof location !== 'string') {
mParticle.Logger.error(
'Location must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (hardwareId && typeof(hardwareId) !== 'string') {
mParticle.Logger.error('Hardware ID must be a valid string when constructing a GDPR Consent object.');
if (hardwareId && typeof hardwareId !== 'string') {
mParticle.Logger.error(
'Hardware ID must be a valid string when constructing a GDPR Consent object.'
);
return null;

@@ -29,3 +45,3 @@ }

Location: location,
HardwareId: hardwareId
HardwareId: hardwareId,
};

@@ -41,19 +57,20 @@ }

jsonObject.gdpr = {};
for (var purpose in gdprConsentState){
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof(gdprConsent.Consented) === 'boolean') {
if (typeof gdprConsent.Consented === 'boolean') {
jsonObject.gdpr[purpose].c = gdprConsent.Consented;
}
if (typeof(gdprConsent.Timestamp) === 'number') {
if (typeof gdprConsent.Timestamp === 'number') {
jsonObject.gdpr[purpose].ts = gdprConsent.Timestamp;
}
if (typeof(gdprConsent.ConsentDocument) === 'string') {
jsonObject.gdpr[purpose].d = gdprConsent.ConsentDocument;
if (typeof gdprConsent.ConsentDocument === 'string') {
jsonObject.gdpr[purpose].d =
gdprConsent.ConsentDocument;
}
if (typeof(gdprConsent.Location) === 'string') {
if (typeof gdprConsent.Location === 'string') {
jsonObject.gdpr[purpose].l = gdprConsent.Location;
}
if (typeof(gdprConsent.HardwareId) === 'string') {
if (typeof gdprConsent.HardwareId === 'string') {
jsonObject.gdpr[purpose].h = gdprConsent.HardwareId;

@@ -71,9 +88,11 @@ }

if (json.gdpr) {
for (var purpose in json.gdpr){
for (var purpose in json.gdpr) {
if (json.gdpr.hasOwnProperty(purpose)) {
var gdprConsent = createGDPRConsent(json.gdpr[purpose].c,
var gdprConsent = createGDPRConsent(
json.gdpr[purpose].c,
json.gdpr[purpose].ts,
json.gdpr[purpose].d,
json.gdpr[purpose].l,
json.gdpr[purpose].h);
json.gdpr[purpose].h
);
state.addGDPRConsentState(purpose, gdprConsent);

@@ -84,3 +103,3 @@ }

return state;
}
},
};

@@ -96,3 +115,3 @@

function canonicalizeForDeduplication(purpose) {
if (typeof(purpose) !== 'string') {
if (typeof purpose !== 'string') {
return null;

@@ -112,3 +131,3 @@ }

gdpr = {};
for (var purpose in gdprConsentState){
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {

@@ -125,14 +144,20 @@ addGDPRConsentState(purpose, gdprConsentState[purpose]);

if (!normalizedPurpose) {
mParticle.Logger.error('addGDPRConsentState() invoked with bad purpose. Purpose must be a string.');
mParticle.Logger.error(
'addGDPRConsentState() invoked with bad purpose. Purpose must be a string.'
);
return this;
}
if (!Helpers.isObject(gdprConsent)) {
mParticle.Logger.error('addGDPRConsentState() invoked with bad or empty GDPR consent object.');
mParticle.Logger.error(
'addGDPRConsentState() invoked with bad or empty GDPR consent object.'
);
return this;
}
var gdprConsentCopy = createGDPRConsent(gdprConsent.Consented,
var gdprConsentCopy = createGDPRConsent(
gdprConsent.Consented,
gdprConsent.Timestamp,
gdprConsent.ConsentDocument,
gdprConsent.Location,
gdprConsent.HardwareId);
gdprConsent.HardwareId
);
if (gdprConsentCopy) {

@@ -161,3 +186,3 @@ gdpr[normalizedPurpose] = gdprConsentCopy;

getGDPRConsentState: getGDPRConsentState,
removeGDPRConsentState: removeGDPRConsentState
removeGDPRConsentState: removeGDPRConsentState,
};

@@ -169,3 +194,3 @@ }

Serialization: ConsentSerialization,
createConsentState: createConsentState
};
createConsentState: createConsentState,
};
var Constants = {
sdkVersion: '2.9.12',
sdkVersion: '2.9.13',
sdkVendor: 'mparticle',

@@ -20,3 +20,4 @@ platform: 'web',

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'
BadLogPurchase:
'Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions',
},

@@ -45,20 +46,34 @@ InformationMessages: {

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'
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. The onUserAlias provided is of type',
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'
}
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. The onUserAlias provided is of type',
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",
},
},

@@ -84,28 +99,28 @@ NativeSdkPaths: {

Modify: 'modify',
Alias: 'aliasUsers'
Alias: 'aliasUsers',
},
StorageNames: {
localStorageName: 'mprtcl-api', // Name of the mP localstorage, had cp and pb even if cookies were used, skipped v2
localStorageNameV3: 'mprtcl-v3', // v3 Name of the mP localstorage, final version on SDKv1
cookieName: 'mprtcl-api', // v1 Name of the cookie stored on the user's machine
cookieNameV2: 'mprtcl-v2', // v2 Name of the cookie stored on the user's machine. Removed keys with no values, moved cartProducts and productBags to localStorage.
cookieNameV3: 'mprtcl-v3', // v3 Name of the cookie stored on the user's machine. Base64 encoded keys in Base64CookieKeys object, final version on SDKv1
localStorageNameV4: 'mprtcl-v4', // v4 Name of the mP localstorage, Current Version
localStorageProductsV4: 'mprtcl-prodv4', // The name for mP localstorage that contains products for cartProducs and productBags
cookieNameV4: 'mprtcl-v4', // v4 Name of the cookie stored on the user's machine. Base64 encoded keys in Base64CookieKeys object, current version on SDK v2
localStorageName: 'mprtcl-api', // Name of the mP localstorage, had cp and pb even if cookies were used, skipped v2
localStorageNameV3: 'mprtcl-v3', // v3 Name of the mP localstorage, final version on SDKv1
cookieName: 'mprtcl-api', // v1 Name of the cookie stored on the user's machine
cookieNameV2: 'mprtcl-v2', // v2 Name of the cookie stored on the user's machine. Removed keys with no values, moved cartProducts and productBags to localStorage.
cookieNameV3: 'mprtcl-v3', // v3 Name of the cookie stored on the user's machine. Base64 encoded keys in Base64CookieKeys object, final version on SDKv1
localStorageNameV4: 'mprtcl-v4', // v4 Name of the mP localstorage, Current Version
localStorageProductsV4: 'mprtcl-prodv4', // The name for mP localstorage that contains products for cartProducs and productBags
cookieNameV4: 'mprtcl-v4', // v4 Name of the cookie stored on the user's machine. Base64 encoded keys in Base64CookieKeys object, current version on SDK v2
currentStorageName: 'mprtcl-v4',
currentStorageProductsName: 'mprtcl-prodv4'
currentStorageProductsName: 'mprtcl-prodv4',
},
DefaultConfig: {
cookieDomain: null, // If null, defaults to current location.host
cookieExpiration: 365, // Cookie expiration time in days
logLevel: null, // What logging will be provided in the console
timeout: 300, // timeout in milliseconds for logging functions
sessionTimeout: 30, // Session timeout in minutes
maxProducts: 20, // Number of products persisted in cartProducts and productBags
forwarderStatsTimeout: 5000, // Milliseconds for forwarderStats timeout
integrationDelayTimeout: 5000, // Milliseconds for forcing the integration delay to un-suspend event queueing due to integration partner errors
maxCookieSize: 3000, // Number of bytes for cookie size to not exceed
aliasMaxWindow: 90, // Max age of Alias request startTime, in days
uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
cookieDomain: null, // If null, defaults to current location.host
cookieExpiration: 365, // Cookie expiration time in days
logLevel: null, // What logging will be provided in the console
timeout: 300, // timeout in milliseconds for logging functions
sessionTimeout: 30, // Session timeout in minutes
maxProducts: 20, // Number of products persisted in cartProducts and productBags
forwarderStatsTimeout: 5000, // Milliseconds for forwarderStats timeout
integrationDelayTimeout: 5000, // Milliseconds for forcing the integration delay to un-suspend event queueing due to integration partner errors
maxCookieSize: 3000, // Number of bytes for cookie size to not exceed
aliasMaxWindow: 90, // Max age of Alias request startTime, in days
uploadInterval: 0, // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
},

@@ -118,3 +133,3 @@ DefaultUrls: {

identityUrl: 'identity.mparticle.com/v1/',
aliasUrl: 'jssdks.mparticle.com/v1/identity/'
aliasUrl: 'jssdks.mparticle.com/v1/identity/',
},

@@ -129,3 +144,3 @@ Base64CookieKeys: {

ia: 1,
con: 1
con: 1,
},

@@ -137,3 +152,3 @@ SDKv2NonMPIDCookieKeys: {

globalSettings: 1,
currentUserMPID: 1
currentUserMPID: 1,
},

@@ -147,3 +162,3 @@ HTTPCodes: {

loggingDisabledOrMissingAPIKey: -6,
tooManyRequests: 429
tooManyRequests: 429,
},

@@ -153,6 +168,6 @@ FeatureFlags: {

EventsV3: 'eventsV3',
EventBatchingIntervalMillis: 'eventBatchingIntervalMillis'
}
EventBatchingIntervalMillis: 'eventBatchingIntervalMillis',
},
};
export default Constants;
export default Constants;

@@ -10,12 +10,25 @@ import Constants from './constants';

if (mpid && !mParticle.Store.webviewBridgeEnabled) {
mParticle.Store.pixelConfigurations.forEach(function(pixelSettings) {
mParticle.Store.pixelConfigurations.forEach(function(
pixelSettings
) {
pixelConfig = {
moduleId: pixelSettings.moduleId,
frequencyCap: pixelSettings.frequencyCap,
pixelUrl: cookieSyncManager.replaceAmp(pixelSettings.pixelUrl),
redirectUrl: pixelSettings.redirectUrl ? cookieSyncManager.replaceAmp(pixelSettings.redirectUrl) : null
pixelUrl: cookieSyncManager.replaceAmp(
pixelSettings.pixelUrl
),
redirectUrl: pixelSettings.redirectUrl
? cookieSyncManager.replaceAmp(
pixelSettings.redirectUrl
)
: null,
};
url = cookieSyncManager.replaceMPID(pixelConfig.pixelUrl, mpid);
redirect = pixelConfig.redirectUrl ? cookieSyncManager.replaceMPID(pixelConfig.redirectUrl, mpid) : '';
redirect = pixelConfig.redirectUrl
? cookieSyncManager.replaceMPID(
pixelConfig.redirectUrl,
mpid
)
: '';
urlWithRedirect = url + encodeURIComponent(redirect);

@@ -29,3 +42,8 @@ var cookies = Persistence.getPersistence();

}
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
performCookieSync(
urlWithRedirect,
pixelConfig.moduleId,
mpid,
cookies[mpid].csd
);
}

@@ -38,11 +56,33 @@ return;

}
lastSyncDateForModule = cookies[mpid].csd[(pixelConfig.moduleId).toString()] ? cookies[mpid].csd[(pixelConfig.moduleId).toString()] : null;
lastSyncDateForModule = cookies[mpid].csd[
pixelConfig.moduleId.toString()
]
? cookies[mpid].csd[pixelConfig.moduleId.toString()]
: null;
if (lastSyncDateForModule) {
// Check to see if we need to refresh cookieSync
if ((new Date()).getTime() > (new Date(lastSyncDateForModule).getTime() + (pixelConfig.frequencyCap * 60 * 1000 * 60 * 24))) {
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
if (
new Date().getTime() >
new Date(lastSyncDateForModule).getTime() +
pixelConfig.frequencyCap *
60 *
1000 *
60 *
24
) {
performCookieSync(
urlWithRedirect,
pixelConfig.moduleId,
mpid,
cookies[mpid].csd
);
}
} else {
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
performCookieSync(
urlWithRedirect,
pixelConfig.moduleId,
mpid,
cookies[mpid].csd
);
}

@@ -61,3 +101,3 @@ }

return string.replace(/&amp;/g, '&');
}
},
};

@@ -71,6 +111,6 @@

img.src = url;
cookieSyncDates[moduleId.toString()] = (new Date()).getTime();
cookieSyncDates[moduleId.toString()] = new Date().getTime();
Persistence.saveUserCookieSyncDatesToCookies(mpid, cookieSyncDates);
}
export default cookieSyncManager;
export default cookieSyncManager;

@@ -8,4 +8,7 @@ import Types from './types';

Messages = Constants.Messages;
function convertTransactionAttributesToProductAction(transactionAttributes, productAction) {
function convertTransactionAttributesToProductAction(
transactionAttributes,
productAction
) {
productAction.TransactionId = transactionAttributes.Id;

@@ -83,3 +86,7 @@ productAction.Affiliation = transactionAttributes.Affiliation;

default:
mParticle.Logger.error('Could not convert product action type ' + productActionType + ' to event type');
mParticle.Logger.error(
'Could not convert product action type ' +
productActionType +
' to event type'
);
return null;

@@ -96,3 +103,7 @@ }

default:
mParticle.Logger.error('Could not convert promotion action type ' + promotionActionType + ' to event type');
mParticle.Logger.error(
'Could not convert promotion action type ' +
promotionActionType +
' to event type'
);
return null;

@@ -135,3 +146,2 @@ }

attributes['Total Product Amount'] = product.TotalAmount || 0;
}

@@ -207,3 +217,4 @@

function createProduct(name,
function createProduct(
name,
sku,

@@ -217,4 +228,4 @@ price,

couponCode,
attributes) {
attributes
) {
attributes = Helpers.sanitizeAttributes(attributes);

@@ -228,3 +239,5 @@

if (!Validators.isStringOrNumber(sku)) {
mParticle.Logger.error('SKU is required when creating a product, and must be a string or a number');
mParticle.Logger.error(
'SKU is required when creating a product, and must be a string or a number'
);
return null;

@@ -234,3 +247,5 @@ }

if (!Validators.isStringOrNumber(price)) {
mParticle.Logger.error('Price is required when creating a product, and must be a string or a number');
mParticle.Logger.error(
'Price is required when creating a product, and must be a string or a number'
);
return null;

@@ -240,3 +255,5 @@ }

if (position && !Validators.isNumber(position)) {
mParticle.Logger.error('Position must be a number, it will be set to null.');
mParticle.Logger.error(
'Position must be a number, it will be set to null.'
);
position = null;

@@ -260,3 +277,3 @@ }

TotalAmount: quantity * price,
Attributes: attributes
Attributes: attributes,
};

@@ -275,3 +292,3 @@ }

Name: name,
Position: position
Position: position,
};

@@ -287,3 +304,5 @@ }

if (!product) {
mParticle.Logger.error('Product is required when creating an impression.');
mParticle.Logger.error(
'Product is required when creating an impression.'
);
return null;

@@ -294,7 +313,8 @@ }

Name: name,
Product: product
Product: product,
};
}
function createTransactionAttributes(id,
function createTransactionAttributes(
id,
affiliation,

@@ -304,4 +324,4 @@ couponCode,

shipping,
tax) {
tax
) {
if (!Validators.isStringOrNumber(id)) {

@@ -318,3 +338,3 @@ mParticle.Logger.error(Messages.ErrorMessages.TransactionIdRequired);

Shipping: shipping,
Tax: tax
Tax: tax,
};

@@ -331,3 +351,7 @@ }

productImpression.ProductList.forEach(function(product) {
var attributes = Helpers.extend(false, {}, commerceEvent.EventAttributes);
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
if (product.Attributes) {

@@ -340,3 +364,4 @@ for (var attribute in product.Attributes) {

if (productImpression.ProductImpressionList) {
attributes['Product Impression List'] = productImpression.ProductImpressionList;
attributes['Product Impression List'] =
productImpression.ProductImpressionList;
}

@@ -347,3 +372,3 @@ var appEvent = ServerModel.createEventObject({

data: attributes,
eventType: Types.EventType.Transaction
eventType: Types.EventType.Transaction,
});

@@ -374,3 +399,7 @@ appEvents.push(appEvent);

promotions.forEach(function(promotion) {
var attributes = Helpers.extend(false, {}, commerceEvent.EventAttributes);
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
extractPromotionAttributes(attributes, promotion);

@@ -380,5 +409,9 @@

messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)),
name: generateExpandedEcommerceName(
Types.PromotionActionType.getExpansionName(
commerceEvent.PromotionAction.PromotionActionType
)
),
data: attributes,
eventType: Types.EventType.Transaction
eventType: Types.EventType.Transaction,
});

@@ -396,6 +429,16 @@ appEvents.push(appEvent);

var shouldExtractActionAttributes = false;
if (commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Purchase ||
commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Refund) {
var attributes = Helpers.extend(false, {}, commerceEvent.EventAttributes);
attributes['Product Count'] = commerceEvent.ProductAction.ProductList ? commerceEvent.ProductAction.ProductList.length : 0;
if (
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Purchase ||
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Refund
) {
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
attributes['Product Count'] = commerceEvent.ProductAction.ProductList
? commerceEvent.ProductAction.ProductList.length
: 0;
extractActionAttributes(attributes, commerceEvent.ProductAction);

@@ -407,9 +450,13 @@ if (commerceEvent.CurrencyCode) {

messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType), true),
name: generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
),
true
),
data: attributes,
eventType: Types.EventType.Transaction
eventType: Types.EventType.Transaction,
});
appEvents.push(plusOneEvent);
}
else {
} else {
shouldExtractActionAttributes = true;

@@ -425,7 +472,10 @@ }

products.forEach(function(product) {
var attributes = Helpers.extend(false, commerceEvent.EventAttributes, product.Attributes);
var attributes = Helpers.extend(
false,
commerceEvent.EventAttributes,
product.Attributes
);
if (shouldExtractActionAttributes) {
extractActionAttributes(attributes, commerceEvent.ProductAction);
}
else {
} else {
extractTransactionId(attributes, commerceEvent.ProductAction);

@@ -437,5 +487,9 @@ }

messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType)),
name: generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
)
),
data: attributes,
eventType: Types.EventType.Transaction
eventType: Types.EventType.Transaction,
});

@@ -452,10 +506,16 @@ appEvents.push(productEvent);

mParticle.Logger.verbose(Messages.InformationMessages.StartingLogCommerceEvent);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);
if (Helpers.canLog()) {
baseEvent = ServerModel.createEventObject({ messageType: Types.MessageType.Commerce });
baseEvent = ServerModel.createEventObject({
messageType: Types.MessageType.Commerce,
});
baseEvent.EventName = 'eCommerce - ';
baseEvent.CurrencyCode = mParticle.Store.currencyCode;
baseEvent.ShoppingCart = {
ProductList: currentUser ? currentUser.getCart().getCartProducts() : []
ProductList: currentUser
? currentUser.getCart().getCartProducts()
: [],
};

@@ -465,4 +525,3 @@ baseEvent.CustomFlags = customFlags;

return baseEvent;
}
else {
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);

@@ -486,3 +545,3 @@ }

expandCommerceEvent: expandCommerceEvent,
createCommerceEventObject: createCommerceEventObject
};
createCommerceEventObject: createCommerceEventObject,
};

@@ -12,5 +12,6 @@ import Types from './types';

function logEvent(event) {
mParticle.Logger.verbose(Messages.InformationMessages.StartingLogEvent + ': ' + event.name);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogEvent + ': ' + event.name
);
if (Helpers.canLog()) {

@@ -23,4 +24,3 @@ if (event.data) {

Persistence.update();
}
else {
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);

@@ -33,3 +33,6 @@ }

if ('geolocation' in navigator) {
mParticle.Store.watchPositionId = navigator.geolocation.watchPosition(successTracking, errorTracking);
mParticle.Store.watchPositionId = navigator.geolocation.watchPosition(
successTracking,
errorTracking
);
}

@@ -40,4 +43,4 @@ } else {

latitude: mParticle.Store.currentPosition.lat,
longitude: mParticle.Store.currentPosition.lng
}
longitude: mParticle.Store.currentPosition.lng,
},
};

@@ -50,3 +53,3 @@ triggerCallback(callback, position);

lat: position.coords.latitude,
lng: position.coords.longitude
lng: position.coords.longitude,
};

@@ -77,3 +80,5 @@

} catch (e) {
mParticle.Logger.error('Error invoking the callback passed to startTrackingLocation.');
mParticle.Logger.error(
'Error invoking the callback passed to startTrackingLocation.'
);
mParticle.Logger.error(e);

@@ -98,3 +103,3 @@ }

messageType: Types.MessageType.OptOut,
eventType: Types.EventType.Other
eventType: Types.EventType.Other,
});

@@ -112,3 +117,5 @@ sendEventToServer(event);

if (event) {
event.EventName += Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout);
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Checkout
);
event.EventCategory = Types.CommerceEventType.ProductCheckout;

@@ -119,3 +126,3 @@ event.ProductAction = {

CheckoutOptions: options,
ProductList: event.ShoppingCart.ProductList
ProductList: event.ShoppingCart.ProductList,
};

@@ -131,7 +138,11 @@

if (event) {
event.EventCategory = Ecommerce.convertProductActionToEventType(productActionType);
event.EventName += Ecommerce.getProductActionEventName(productActionType);
event.EventCategory = Ecommerce.convertProductActionToEventType(
productActionType
);
event.EventName += Ecommerce.getProductActionEventName(
productActionType
);
event.ProductAction = {
ProductActionType: productActionType,
ProductList: Array.isArray(product) ? product : [product]
ProductList: Array.isArray(product) ? product : [product],
};

@@ -147,10 +158,18 @@

if (event) {
event.EventName += Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase);
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Purchase
);
event.EventCategory = Types.CommerceEventType.ProductPurchase;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Purchase
ProductActionType: Types.ProductActionType.Purchase,
};
event.ProductAction.ProductList = Ecommerce.buildProductList(event, product);
event.ProductAction.ProductList = Ecommerce.buildProductList(
event,
product
);
Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction);
Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);

@@ -170,10 +189,18 @@ logCommerceEvent(event, attrs);

if (event) {
event.EventName += Ecommerce.getProductActionEventName(Types.ProductActionType.Refund);
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Refund
);
event.EventCategory = Types.CommerceEventType.ProductRefund;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Refund
ProductActionType: Types.ProductActionType.Refund,
};
event.ProductAction.ProductList = Ecommerce.buildProductList(event, product);
event.ProductAction.ProductList = Ecommerce.buildProductList(
event,
product
);
Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction);
Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);

@@ -189,6 +216,8 @@ logCommerceEvent(event, attrs);

event.EventName += Ecommerce.getPromotionActionEventName(promotionType);
event.EventCategory = Ecommerce.convertPromotionActionToEventType(promotionType);
event.EventCategory = Ecommerce.convertPromotionActionToEventType(
promotionType
);
event.PromotionAction = {
PromotionActionType: promotionType,
PromotionList: [promotion]
PromotionList: [promotion],
};

@@ -215,3 +244,5 @@

ProductImpressionList: impression.Name,
ProductList: Array.isArray(impression.Product) ? impression.Product : [impression.Product]
ProductList: Array.isArray(impression.Product)
? impression.Product
: [impression.Product],
});

@@ -224,5 +255,6 @@ });

function logCommerceEvent(commerceEvent, attrs) {
mParticle.Logger.verbose(Messages.InformationMessages.StartingLogCommerceEvent);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);

@@ -243,4 +275,3 @@ attrs = Helpers.sanitizeAttributes(attrs);

Persistence.update();
}
else {
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);

@@ -256,4 +287,3 @@ }

window.location.href = element.href;
}
else if (element.submit) {
} else if (element.submit) {
element.submit();

@@ -267,9 +297,15 @@ }

messageType: Types.MessageType.PageEvent,
name: typeof eventName === 'function' ? eventName(element) : eventName,
name:
typeof eventName === 'function'
? eventName(element)
: eventName,
data: typeof data === 'function' ? data(element) : data,
eventType: eventType || Types.EventType.Other
eventType: eventType || Types.EventType.Other,
});
// TODO: Handle middle-clicks and special keys (ctrl, alt, etc)
if ((element.href && element.target !== '_blank') || element.submit) {
if (
(element.href && element.target !== '_blank') ||
element.submit
) {
// Give xmlhttprequest enough time to execute before navigating a link or submitting form

@@ -279,4 +315,3 @@

e.preventDefault();
}
else {
} else {
e.returnValue = false;

@@ -292,3 +327,3 @@ }

if (!selector) {
mParticle.Logger.error('Can\'t bind event, selector is required');
mParticle.Logger.error("Can't bind event, selector is required");
return;

@@ -300,4 +335,3 @@ }

elements = document.querySelectorAll(selector);
}
else if (selector.nodeType) {
} else if (selector.nodeType) {
elements = [selector];

@@ -307,7 +341,9 @@ }

if (elements.length) {
mParticle.Logger.verbose('Found ' +
elements.length +
' element' +
(elements.length > 1 ? 's' : '') +
', attaching event handlers');
mParticle.Logger.verbose(
'Found ' +
elements.length +
' element' +
(elements.length > 1 ? 's' : '') +
', attaching event handlers'
);

@@ -319,12 +355,9 @@ for (i = 0; i < elements.length; i++) {

element.addEventListener(domEvent, handler, false);
}
else if (element.attachEvent) {
} else if (element.attachEvent) {
element.attachEvent('on' + domEvent, handler);
}
else {
} else {
element['on' + domEvent] = handler;
}
}
}
else {
} else {
mParticle.Logger.verbose('No elements found');

@@ -346,3 +379,3 @@ }

logAST: logAST,
addEventHandler: addEventHandler
};
addEventHandler: addEventHandler,
};

@@ -650,3 +650,3 @@ export interface ApplicationInformation {

export interface SessionStartEventData extends CommonEventData { }
export interface SessionStartEventData extends CommonEventData {}

@@ -653,0 +653,0 @@ export interface ShoppingCart {

import Helpers from './helpers';
import Types from './types';
import getFilteredMparticleUser from './mParticleUser';
import filteredMparticleUser from './filteredMparticleUser';
import Persistence from './persistence';

@@ -8,3 +8,6 @@

var user = mParticle.Identity.getCurrentUser();
if (!mParticle.Store.webviewBridgeEnabled && mParticle.Store.configuredForwarders) {
if (
!mParticle.Store.webviewBridgeEnabled &&
mParticle.Store.configuredForwarders
) {
// Some js libraries require that they be loaded first, or last, etc

@@ -17,32 +20,57 @@ mParticle.Store.configuredForwarders.sort(function(x, y) {

mParticle.Store.activeForwarders = mParticle.Store.configuredForwarders.filter(function(forwarder) {
if (!isEnabledForUserConsent(forwarder.filteringConsentRuleValues, user)) {
return false;
}
if (!isEnabledForUserAttributes(forwarder.filteringUserAttributeValue, user)) {
return false;
}
if (!isEnabledForUnknownUser(forwarder.excludeAnonymousUser, user)) {
return false;
}
mParticle.Store.activeForwarders = mParticle.Store.configuredForwarders.filter(
function(forwarder) {
if (
!isEnabledForUserConsent(
forwarder.filteringConsentRuleValues,
user
)
) {
return false;
}
if (
!isEnabledForUserAttributes(
forwarder.filteringUserAttributeValue,
user
)
) {
return false;
}
if (
!isEnabledForUnknownUser(
forwarder.excludeAnonymousUser,
user
)
) {
return false;
}
var filteredUserIdentities = Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters);
var filteredUserAttributes = Helpers.filterUserAttributes(user ? user.getAllUserAttributes() : {}, forwarder.userAttributeFilters);
var filteredUserIdentities = Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
var filteredUserAttributes = Helpers.filterUserAttributes(
user ? user.getAllUserAttributes() : {},
forwarder.userAttributeFilters
);
if (!forwarder.initialized) {
forwarder.init(forwarder.settings,
forwardingStatsCallback,
false,
null,
filteredUserAttributes,
filteredUserIdentities,
mParticle.Store.SDKConfig.appVersion,
mParticle.Store.SDKConfig.appName,
mParticle.Store.SDKConfig.customFlags,
mParticle.Store.clientId);
forwarder.initialized = true;
if (!forwarder.initialized) {
forwarder.init(
forwarder.settings,
forwardingStatsCallback,
false,
null,
filteredUserAttributes,
filteredUserIdentities,
mParticle.Store.SDKConfig.appVersion,
mParticle.Store.SDKConfig.appName,
mParticle.Store.SDKConfig.customFlags,
mParticle.Store.clientId
);
forwarder.initialized = true;
}
return true;
}
return true;
});
);
}

@@ -52,5 +80,3 @@ }

function isEnabledForUserConsent(consentRules, user) {
if (!consentRules
|| !consentRules.values
|| !consentRules.values.length) {
if (!consentRules || !consentRules.values || !consentRules.values.length) {
return true;

@@ -69,4 +95,7 @@ }

if (gdprConsentState.hasOwnProperty(purpose)) {
var purposeHash = Helpers.generateHash(GDPRConsentHashPrefix + purpose).toString();
purposeHashes[purposeHash] = gdprConsentState[purpose].Consented;
var purposeHash = Helpers.generateHash(
GDPRConsentHashPrefix + purpose
).toString();
purposeHashes[purposeHash] =
gdprConsentState[purpose].Consented;
}

@@ -81,4 +110,6 @@ }

var hasConsented = consentRule.hasConsented;
if (purposeHashes.hasOwnProperty(purposeHash)
&& purposeHashes[purposeHash] === hasConsented) {
if (
purposeHashes.hasOwnProperty(purposeHash) &&
purposeHashes[purposeHash] === hasConsented
) {
isMatch = true;

@@ -93,11 +124,11 @@ }

function isEnabledForUserAttributes(filterObject, user) {
if (!filterObject ||
if (
!filterObject ||
!Helpers.isObject(filterObject) ||
!Object.keys(filterObject).length) {
!Object.keys(filterObject).length
) {
return true;
}
var attrHash,
valueHash,
userAttributes;
var attrHash, valueHash, userAttributes;

@@ -113,9 +144,18 @@ if (!user) {

try {
if (userAttributes && Helpers.isObject(userAttributes) && Object.keys(userAttributes).length) {
if (
userAttributes &&
Helpers.isObject(userAttributes) &&
Object.keys(userAttributes).length
) {
for (var attrName in userAttributes) {
if (userAttributes.hasOwnProperty(attrName)) {
attrHash = Helpers.generateHash(attrName).toString();
valueHash = Helpers.generateHash(userAttributes[attrName]).toString();
valueHash = Helpers.generateHash(
userAttributes[attrName]
).toString();
if ((attrHash === filterObject.userAttributeName) && (valueHash === filterObject.userAttributeValue)) {
if (
attrHash === filterObject.userAttributeName &&
valueHash === filterObject.userAttributeValue
) {
isMatch = true;

@@ -159,4 +199,3 @@ break;

}
}
catch (e) {
} catch (e) {
mParticle.Logger.verbose(e);

@@ -186,3 +225,2 @@ }

},
filterAttributes = function(event, filterList) {

@@ -197,3 +235,5 @@ var hash;

if (event.EventAttributes.hasOwnProperty(attrName)) {
hash = Helpers.generateHash(event.EventCategory + event.EventName + attrName);
hash = Helpers.generateHash(
event.EventCategory + event.EventName + attrName
);

@@ -218,7 +258,12 @@ if (Helpers.inArray(filterList, hash)) {

Types.MessageType.PageView,
Types.MessageType.Commerce
Types.MessageType.Commerce,
];
if (!mParticle.Store.webviewBridgeEnabled && mParticle.Store.activeForwarders) {
hashedEventName = Helpers.generateHash(event.EventCategory + event.EventName);
if (
!mParticle.Store.webviewBridgeEnabled &&
mParticle.Store.activeForwarders
) {
hashedEventName = Helpers.generateHash(
event.EventCategory + event.EventName
);
hashedEventType = Helpers.generateHash(event.EventCategory);

@@ -233,7 +278,11 @@

if (forwardingRuleMessageTypes.indexOf(event.EventDataType) > -1
&& mParticle.Store.activeForwarders[i].filteringEventAttributeValue
&& mParticle.Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName
&& mParticle.Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue) {
if (
forwardingRuleMessageTypes.indexOf(event.EventDataType) > -1 &&
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue &&
mParticle.Store.activeForwarders[i].filteringEventAttributeValue
.eventAttributeName &&
mParticle.Store.activeForwarders[i].filteringEventAttributeValue
.eventAttributeValue
) {
var foundProp = null;

@@ -245,11 +294,19 @@

var hashedEventAttributeName;
hashedEventAttributeName = Helpers.generateHash(prop).toString();
hashedEventAttributeName = Helpers.generateHash(
prop
).toString();
if (hashedEventAttributeName === mParticle.Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName) {
if (
hashedEventAttributeName ===
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeName
) {
foundProp = {
name: hashedEventAttributeName,
value: Helpers.generateHash(event.EventAttributes[prop]).toString()
value: Helpers.generateHash(
event.EventAttributes[prop]
).toString(),
};
}
if (foundProp) {

@@ -261,5 +318,13 @@ break;

var isMatch = foundProp !== null && foundProp.value === mParticle.Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue;
var isMatch =
foundProp !== null &&
foundProp.value ===
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeValue;
var shouldInclude = mParticle.Store.activeForwarders[i].filteringEventAttributeValue.includeOnMatch === true ? isMatch : !isMatch;
var shouldInclude =
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.includeOnMatch === true
? isMatch
: !isMatch;

@@ -275,11 +340,29 @@ if (!shouldInclude) {

// Check event filtering rules
if (event.EventDataType === Types.MessageType.PageEvent
&& (inFilteredList(mParticle.Store.activeForwarders[i].eventNameFilters, hashedEventName)
|| inFilteredList(mParticle.Store.activeForwarders[i].eventTypeFilters, hashedEventType))) {
if (
event.EventDataType === Types.MessageType.PageEvent &&
(inFilteredList(
mParticle.Store.activeForwarders[i].eventNameFilters,
hashedEventName
) ||
inFilteredList(
mParticle.Store.activeForwarders[i].eventTypeFilters,
hashedEventType
))
) {
continue;
}
else if (event.EventDataType === Types.MessageType.Commerce && inFilteredList(mParticle.Store.activeForwarders[i].eventTypeFilters, hashedEventType)) {
} else if (
event.EventDataType === Types.MessageType.Commerce &&
inFilteredList(
mParticle.Store.activeForwarders[i].eventTypeFilters,
hashedEventType
)
) {
continue;
}
else if (event.EventDataType === Types.MessageType.PageView && inFilteredList(mParticle.Store.activeForwarders[i].screenNameFilters, hashedEventName)) {
} else if (
event.EventDataType === Types.MessageType.PageView &&
inFilteredList(
mParticle.Store.activeForwarders[i].screenNameFilters,
hashedEventName
)
) {
continue;

@@ -291,19 +374,36 @@ }

if (event.EventDataType === Types.MessageType.PageEvent) {
filterAttributes(clonedEvent, mParticle.Store.activeForwarders[i].attributeFilters);
filterAttributes(
clonedEvent,
mParticle.Store.activeForwarders[i].attributeFilters
);
} else if (event.EventDataType === Types.MessageType.PageView) {
filterAttributes(
clonedEvent,
mParticle.Store.activeForwarders[i]
.pageViewAttributeFilters
);
}
else if (event.EventDataType === Types.MessageType.PageView) {
filterAttributes(clonedEvent, mParticle.Store.activeForwarders[i].pageViewAttributeFilters);
}
}
// Check user identity filtering rules
filterUserIdentities(clonedEvent, mParticle.Store.activeForwarders[i].userIdentityFilters);
filterUserIdentities(
clonedEvent,
mParticle.Store.activeForwarders[i].userIdentityFilters
);
// Check user attribute filtering rules
clonedEvent.UserAttributes = Helpers.filterUserAttributes(clonedEvent.UserAttributes, mParticle.Store.activeForwarders[i].userAttributeFilters);
clonedEvent.UserAttributes = Helpers.filterUserAttributes(
clonedEvent.UserAttributes,
mParticle.Store.activeForwarders[i].userAttributeFilters
);
mParticle.Logger.verbose('Sending message to forwarder: ' + mParticle.Store.activeForwarders[i].name);
mParticle.Logger.verbose(
'Sending message to forwarder: ' +
mParticle.Store.activeForwarders[i].name
);
if (mParticle.Store.activeForwarders[i].process) {
var result = mParticle.Store.activeForwarders[i].process(clonedEvent);
var result = mParticle.Store.activeForwarders[i].process(
clonedEvent
);

@@ -314,3 +414,2 @@ if (result) {

}
}

@@ -323,6 +422,10 @@ }

mParticle.Store.activeForwarders.forEach(function(forwarder) {
if (forwarder.setUserAttribute &&
if (
forwarder.setUserAttribute &&
forwarder.userAttributeFilters &&
!Helpers.inArray(forwarder.userAttributeFilters, Helpers.generateHash(key))) {
!Helpers.inArray(
forwarder.userAttributeFilters,
Helpers.generateHash(key)
)
) {
try {

@@ -334,4 +437,3 @@ var result = forwarder.setUserAttribute(key, value);

}
}
catch (e) {
} catch (e) {
mParticle.Logger.error(e);

@@ -346,6 +448,12 @@ }

mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUserIdentities = Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters);
var filteredUserIdentities = Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
if (forwarder.setUserIdentity) {
filteredUserIdentities.forEach(function(identity) {
var result = forwarder.setUserIdentity(identity.Identity, identity.Type);
var result = forwarder.setUserIdentity(
identity.Identity,
identity.Type
);
if (result) {

@@ -361,3 +469,3 @@ mParticle.Logger.verbose(result);

mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = getFilteredMparticleUser(user.getMPID(), forwarder);
var filteredUser = filteredMparticleUser(user.getMPID(), forwarder);
if (forwarder.onUserIdentified) {

@@ -376,3 +484,3 @@ var result = forwarder.onUserIdentified(filteredUser);

mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = getFilteredMparticleUser(user.getMPID(), forwarder);
var filteredUser = filteredMparticleUser(user.getMPID(), forwarder);
if (identityMethod === 'identify') {

@@ -385,4 +493,3 @@ if (forwarder.onIdentifyComplete) {

}
}
else if (identityMethod === 'login') {
} else if (identityMethod === 'login') {
if (forwarder.onLoginComplete) {

@@ -426,7 +533,10 @@ result = forwarder.onLoginComplete(filteredUser);

// if there are kits inside of mParticle.Store.SDKConfig.kits, then mParticle is self hosted
if (Helpers.isObject(mParticle.Store.SDKConfig.kits) && Object.keys(mParticle.Store.SDKConfig.kits).length > 0) {
if (
Helpers.isObject(mParticle.Store.SDKConfig.kits) &&
Object.keys(mParticle.Store.SDKConfig.kits).length > 0
) {
forwarders = mParticle.Store.SDKConfig.kits;
// otherwise mParticle is loaded via script tag
// otherwise mParticle is loaded via script tag
} else if (mParticle.preInit.forwarderConstructors.length > 0) {
mParticle.preInit.forwarderConstructors.forEach(function (forwarder) {
mParticle.preInit.forwarderConstructors.forEach(function(forwarder) {
forwarders[forwarder.name] = forwarder;

@@ -438,4 +548,8 @@ });

if (name === config.name) {
if (config.isDebug === mParticle.Store.SDKConfig.isDevelopmentMode || config.isSandbox === mParticle.Store.SDKConfig.isDevelopmentMode) {
newForwarder = new (forwarders[name]).constructor();
if (
config.isDebug ===
mParticle.Store.SDKConfig.isDevelopmentMode ||
config.isSandbox === mParticle.Store.SDKConfig.isDevelopmentMode
) {
newForwarder = new forwarders[name].constructor();

@@ -454,3 +568,4 @@ newForwarder.id = config.moduleId;

newForwarder.screenNameFilters = config.screenNameFilters;
newForwarder.pageViewAttributeFilters = config.pageViewAttributeFilters;
newForwarder.pageViewAttributeFilters =
config.pageViewAttributeFilters;

@@ -460,6 +575,9 @@ newForwarder.userIdentityFilters = config.userIdentityFilters;

newForwarder.filteringEventAttributeValue = config.filteringEventAttributeValue;
newForwarder.filteringUserAttributeValue = config.filteringUserAttributeValue;
newForwarder.filteringEventAttributeValue =
config.filteringEventAttributeValue;
newForwarder.filteringUserAttributeValue =
config.filteringUserAttributeValue;
newForwarder.eventSubscriptionId = config.eventSubscriptionId;
newForwarder.filteringConsentRuleValues = config.filteringConsentRuleValues;
newForwarder.filteringConsentRuleValues =
config.filteringConsentRuleValues;
newForwarder.excludeAnonymousUser = config.excludeAnonymousUser;

@@ -475,3 +593,6 @@

function configurePixel(settings) {
if (settings.isDebug === mParticle.Store.SDKConfig.isDevelopmentMode || settings.isProduction !== mParticle.Store.SDKConfig.isDevelopmentMode) {
if (
settings.isDebug === mParticle.Store.SDKConfig.isDevelopmentMode ||
settings.isProduction !== mParticle.Store.SDKConfig.isDevelopmentMode
) {
mParticle.Store.pixelConfigurations.push(settings);

@@ -483,3 +604,5 @@ }

if (!config) {
mParticle.Logger.warning('No config was passed. Cannot process forwarders');
mParticle.Logger.warning(
'No config was passed. Cannot process forwarders'
);
} else {

@@ -493,3 +616,6 @@ try {

if (Array.isArray(config.pixelConfigs) && config.pixelConfigs.length) {
if (
Array.isArray(config.pixelConfigs) &&
config.pixelConfigs.length
) {
config.pixelConfigs.forEach(function(pixelConfig) {

@@ -499,5 +625,10 @@ configurePixel(pixelConfig);

}
initForwarders(mParticle.Store.SDKConfig.identifyRequest.userIdentities, forwardingStatsCallback);
initForwarders(
mParticle.Store.SDKConfig.identifyRequest.userIdentities,
forwardingStatsCallback
);
} catch (e) {
mParticle.Logger.error('Config was not parsed propertly. Forwarders may not be initialized.');
mParticle.Logger.error(
'Config was not parsed propertly. Forwarders may not be initialized.'
);
}

@@ -520,3 +651,3 @@ }

configurePixel: configurePixel,
processForwarders: processForwarders
};
processForwarders: processForwarders,
};

@@ -18,3 +18,3 @@ import ApiClient from './apiClient';

if (forwarderQueue.length) {
uploadsTable[now] = {uploading: false, data: forwarderQueue};
uploadsTable[now] = { uploading: false, data: forwarderQueue };
Forwarders.setForwarderStatsQueue([]);

@@ -30,3 +30,7 @@ }

if (xhr.status === 200 || xhr.status === 202) {
mParticle.Logger.verbose('Successfully sent ' + xhr.statusText + ' from server');
mParticle.Logger.verbose(
'Successfully sent ' +
xhr.statusText +
' from server'
);
delete uploadsTable[date];

@@ -37,4 +41,3 @@ } else if (xhr.status.toString()[0] === '4') {

}
}
else {
} else {
uploadsTable[date].uploading = false;

@@ -48,3 +51,6 @@ }

uploadsTable[date].uploading = true;
ApiClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr);
ApiClient.sendBatchForwardingStatsToServer(
forwardingStatsData,
xhr
);
}

@@ -54,2 +60,2 @@ }

}
}
}

@@ -7,3 +7,6 @@ import Types from './types';

function canLog() {
if (mParticle.Store.isEnabled && (mParticle.Store.devToken || mParticle.Store.webviewBridgeEnabled)) {
if (
mParticle.Store.isEnabled &&
(mParticle.Store.devToken || mParticle.Store.webviewBridgeEnabled)
) {
return true;

@@ -61,4 +64,10 @@ }

var mostRecentUser = users.shift();
var currentUser = mParticleUser || mParticle.Identity.getCurrentUser();
if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) {
var currentUser =
mParticleUser ||
mParticle.Identity.getCurrentUser();
if (
mostRecentUser &&
currentUser &&
mostRecentUser.getMPID() === currentUser.getMPID()
) {
mostRecentUser = users.shift();

@@ -70,3 +79,3 @@ }

}
}
},
});

@@ -86,3 +95,3 @@ }

var callbackMessage = {
httpCode: code
httpCode: code,
};

@@ -101,3 +110,8 @@ if (message) {

function extend() {
var options, name, src, copy, copyIsArray, clone,
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0] || {},

@@ -112,8 +126,15 @@ i = 1,

type: function(obj) {
return obj == null ?
String(obj) :
objectHelper.class2type[Object.prototype.toString.call(obj)] || 'object';
return obj == null
? String(obj)
: objectHelper.class2type[
Object.prototype.toString.call(obj)
] || 'object';
},
isPlainObject: function(obj) {
if (!obj || objectHelper.type(obj) !== 'object' || obj.nodeType || objectHelper.isWindow(obj)) {
if (
!obj ||
objectHelper.type(obj) !== 'object' ||
obj.nodeType ||
objectHelper.isWindow(obj)
) {
return false;

@@ -123,5 +144,10 @@ }

try {
if (obj.constructor &&
if (
obj.constructor &&
!objectHelper.hasOwn.call(obj, 'constructor') &&
!objectHelper.hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
!objectHelper.hasOwn.call(
obj.constructor.prototype,
'isPrototypeOf'
)
) {
return false;

@@ -134,9 +160,12 @@ }

var key;
for (key in obj) { } // eslint-disable-line no-empty
for (key in obj) {
} // eslint-disable-line no-empty
return key === undefined || objectHelper.hasOwn.call(obj, key);
},
isArray: Array.isArray || function(obj) {
return objectHelper.type(obj) === 'array';
},
isArray:
Array.isArray ||
function(obj) {
return objectHelper.type(obj) === 'array';
},
isFunction: function(obj) {

@@ -147,4 +176,4 @@ return objectHelper.type(obj) === 'function';

return obj != null && obj == obj.window;
}
}; // end of objectHelper
},
}; // end of objectHelper

@@ -184,9 +213,14 @@ // Handle a deep copy situation

// Recurse if we're merging plain objects or arrays
if (deep && copy && (objectHelper.isPlainObject(copy) || (copyIsArray = objectHelper.isArray(copy)))) {
if (
deep &&
copy &&
(objectHelper.isPlainObject(copy) ||
(copyIsArray = objectHelper.isArray(copy)))
) {
if (copyIsArray) {
copyIsArray = false;
clone = src && objectHelper.isArray(src) ? src : [];
} else {
clone = src && objectHelper.isPlainObject(src) ? src : {};
clone =
src && objectHelper.isPlainObject(src) ? src : {};
}

@@ -212,4 +246,3 @@

return objType === '[object Object]'
|| objType === '[object Error]';
return objType === '[object Object]' || objType === '[object Error]';
}

@@ -222,4 +255,3 @@

return items.indexOf(name, 0) >= 0;
}
else {
} else {
for (var n = items.length; i < n; i++) {

@@ -234,3 +266,6 @@ if (i in items && items[i] === name) {

function createServiceUrl(secureServiceUrl, devToken) {
var serviceScheme = window.mParticle && mParticle.Store.SDKConfig.forceHttps ? 'https://' : window.location.protocol + '//';
var serviceScheme =
window.mParticle && mParticle.Store.SDKConfig.forceHttps
? 'https://'
: window.location.protocol + '//';
var baseUrl;

@@ -253,4 +288,3 @@ if (mParticle.Store.SDKConfig.forceHttps) {

xhr = new window.XMLHttpRequest();
}
catch (e) {
} catch (e) {
mParticle.Logger.error('Error creating XMLHttpRequest object.');

@@ -261,4 +295,3 @@ }

xhr.onreadystatechange = cb;
}
else if (typeof window.XDomainRequest !== 'undefined') {
} else if (typeof window.XDomainRequest !== 'undefined') {
mParticle.Logger.verbose('Creating XDomainRequest object');

@@ -269,4 +302,3 @@

xhr.onload = cb;
}
catch (e) {
} catch (e) {
mParticle.Logger.error('Error creating XDomainRequest object');

@@ -285,6 +317,6 @@ }

if (randomValue) {
return (a ^ randomValue[0] % 16 >> a/4).toString(16);
return (a ^ (randomValue[0] % 16 >> (a / 4))).toString(16);
}
return (a ^ Math.random() * 16 >> a/4).toString(16);
return (a ^ ((Math.random() * 16) >> (a / 4))).toString(16);
}

@@ -296,14 +328,17 @@

return a // if the placeholder was passed, return
? generateRandomValue(a) // a random number
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
generateUniqueId // random hex digits
);
return a // if the placeholder was passed, return
? generateRandomValue(a) // a random number
: // or otherwise a concatenated string:
(
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11
) // -100000000000,
.replace(
// replacing
/[018]/g, // zeroes, ones, and eights with
generateUniqueId // random hex digits
);
}

@@ -317,9 +352,13 @@

if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(userIdentityName);
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!inArray(filterList, userIdentityType)) {
var identity = {
Type: userIdentityType,
Identity: userIdentitiesObject[userIdentityName]
Identity: userIdentitiesObject[userIdentityName],
};
if (userIdentityType === mParticle.IdentityType.CustomerId) {
if (
userIdentityType === mParticle.IdentityType.CustomerId
) {
filteredUserIdentities.unshift(identity);

@@ -343,5 +382,8 @@ } else {

if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(userIdentityName);
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!inArray(filterList, userIdentityType)) {
filteredUserIdentities[userIdentityName] = userIdentitiesObject[userIdentityName];
filteredUserIdentities[userIdentityName] =
userIdentitiesObject[userIdentityName];
}

@@ -363,3 +405,4 @@ }

if (!inArray(filterList, hashedUserAttribute)) {
filteredUserAttributes[userAttribute] = userAttributes[userAttribute];
filteredUserAttributes[userAttribute] =
userAttributes[userAttribute];
}

@@ -376,3 +419,6 @@ }

for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop.toLowerCase() === key.toLowerCase()) {
if (
obj.hasOwnProperty(prop) &&
prop.toLowerCase() === key.toLowerCase()
) {
return prop;

@@ -392,3 +438,6 @@ }

if (s.indexOf('"') === 0) {
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
s = s
.slice(1, -1)
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}

@@ -438,3 +487,6 @@

if (Array.prototype.reduce) {
return name.split('').reduce(function(a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0);
return name.split('').reduce(function(a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}

@@ -448,3 +500,3 @@

character = name.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = (hash << 5) - hash + character;
hash = hash & hash;

@@ -465,6 +517,13 @@ }

// Make sure that attribute values are not objects or arrays, which are not valid
if (attrs.hasOwnProperty(prop) && Validators.isValidAttributeValue(attrs[prop])) {
if (
attrs.hasOwnProperty(prop) &&
Validators.isValidAttributeValue(attrs[prop])
) {
sanitizedAttrs[prop] = attrs[prop];
} else {
mParticle.Logger.warning('The corresponding attribute value of ' + prop + ' must be a string, number, boolean, or null.');
mParticle.Logger.warning(
'The corresponding attribute value of ' +
prop +
' must be a string, number, boolean, or null.'
);
}

@@ -487,7 +546,7 @@ }

isStringOrNumber: function(value) {
return (typeof value === 'string' || typeof value === 'number');
return typeof value === 'string' || typeof value === 'number';
},
isNumber: function(value) {
return (typeof value === 'number');
return typeof value === 'number';
},

@@ -503,10 +562,16 @@

onUserAlias: 1,
copyUserAttributes: 1
copyUserAttributes: 1,
};
if (identityApiData) {
if (method === 'modify') {
if (isObject(identityApiData.userIdentities) && !Object.keys(identityApiData.userIdentities).length || !isObject(identityApiData.userIdentities)) {
if (
(isObject(identityApiData.userIdentities) &&
!Object.keys(identityApiData.userIdentities).length) ||
!isObject(identityApiData.userIdentities)
) {
return {
valid: false,
error: Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent
error:
Constants.Messages.ValidationMessages
.ModifyIdentityRequestUserIdentitiesPresent,
};

@@ -520,9 +585,17 @@ }

valid: false,
error: Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey
error:
Constants.Messages.ValidationMessages
.IdentityRequesetInvalidKey,
};
}
if (key === 'onUserAlias' && !Validators.isFunction(identityApiData[key])) {
if (
key === 'onUserAlias' &&
!Validators.isFunction(identityApiData[key])
) {
return {
valid: false,
error: Constants.Messages.ValidationMessages.OnUserAliasType + typeof identityApiData[key]
error:
Constants.Messages.ValidationMessages
.OnUserAliasType +
typeof identityApiData[key],
};

@@ -534,3 +607,3 @@ }

return {
valid: true
valid: true,
};

@@ -542,24 +615,55 @@ } else {

valid: false,
error: Constants.Messages.ValidationMessages.UserIdentities
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
} else if (identityApiData.userIdentities !== null && !isObject(identityApiData.userIdentities)) {
// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
} else if (
identityApiData.userIdentities !== null &&
!isObject(identityApiData.userIdentities)
) {
return {
valid: false,
error: Constants.Messages.ValidationMessages.UserIdentities
error:
Constants.Messages.ValidationMessages
.UserIdentities,
};
}
if (isObject(identityApiData.userIdentities) && Object.keys(identityApiData.userIdentities).length) {
if (
isObject(identityApiData.userIdentities) &&
Object.keys(identityApiData.userIdentities).length
) {
for (var identityType in identityApiData.userIdentities) {
if (identityApiData.userIdentities.hasOwnProperty(identityType)) {
if (Types.IdentityType.getIdentityType(identityType) === false) {
if (
identityApiData.userIdentities.hasOwnProperty(
identityType
)
) {
if (
Types.IdentityType.getIdentityType(
identityType
) === false
) {
return {
valid: false,
error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey
error:
Constants.Messages.ValidationMessages
.UserIdentitiesInvalidKey,
};
}
if (!(typeof identityApiData.userIdentities[identityType] === 'string' || identityApiData.userIdentities[identityType] === null)) {
if (
!(
typeof identityApiData.userIdentities[
identityType
] === 'string' ||
identityApiData.userIdentities[
identityType
] === null
)
) {
return {
valid: false,
error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues
error:
Constants.Messages.ValidationMessages
.UserIdentitiesInvalidValues,
};

@@ -573,9 +677,12 @@ }

return {
valid: true
valid: true,
};
}
},
};
function isDelayedByIntegration(delayedIntegrations, timeoutStart, now) {
if (now - timeoutStart > mParticle.Store.SDKConfig.integrationDelayTimeout) {
if (
now - timeoutStart >
mParticle.Store.SDKConfig.integrationDelayTimeout
) {
return false;

@@ -636,3 +743,3 @@ }

Validators: Validators,
getRampNumber: getRampNumber
getRampNumber: getRampNumber,
};

@@ -19,3 +19,5 @@ import Helpers from './helpers';

if (previousMPID && currentMPID && previousMPID !== currentMPID) {
var cookies = Persistence.useLocalStorage() ? Persistence.getLocalStorage() : Persistence.getCookie();
var cookies = Persistence.useLocalStorage()
? Persistence.getLocalStorage()
: Persistence.getCookie();
cookies.cu = currentMPID;

@@ -31,5 +33,10 @@ cookies.gs.csm = currentSessionMPIDs;

if (identityApiData && identityApiData.userIdentities && Helpers.isObject(identityApiData.userIdentities)) {
if (
identityApiData &&
identityApiData.userIdentities &&
Helpers.isObject(identityApiData.userIdentities)
) {
for (var identity in identityApiData.userIdentities) {
identitiesResult[identity] = identityApiData.userIdentities[identity];
identitiesResult[identity] =
identityApiData.userIdentities[identity];
}

@@ -43,5 +50,10 @@ }

preProcessIdentityRequest: function(identityApiData, callback, method) {
mParticle.Logger.verbose(Messages.InformationMessages.StartingLogEvent + ': ' + method);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogEvent + ': ' + method
);
var identityValidationResult = Validators.validateIdentities(identityApiData, method);
var identityValidationResult = Validators.validateIdentities(
identityApiData,
method
);

@@ -52,3 +64,3 @@ if (!identityValidationResult.valid) {

valid: false,
error: identityValidationResult.error
error: identityValidationResult.error,
};

@@ -58,7 +70,9 @@ }

if (callback && !Validators.isFunction(callback)) {
var error = 'The optional callback must be a function. You tried entering a(n) ' + typeof callback;
var error =
'The optional callback must be a function. You tried entering a(n) ' +
typeof callback;
mParticle.Logger.error(error);
return {
valid: false,
error: error
error: error,
};

@@ -68,7 +82,15 @@ }

return {
valid: true
valid: true,
};
},
createIdentityRequest: function(identityApiData, platform, sdkVendor, sdkVersion, deviceId, context, mpid) {
createIdentityRequest: function(
identityApiData,
platform,
sdkVendor,
sdkVersion,
deviceId,
context,
mpid
) {
var APIRequest = {

@@ -78,10 +100,15 @@ client_sdk: {

sdk_vendor: sdkVendor,
sdk_version: sdkVersion
sdk_version: sdkVersion,
},
context: context,
environment: mParticle.Store.SDKConfig.isDevelopmentMode ? 'development' : 'production',
environment: mParticle.Store.SDKConfig.isDevelopmentMode
? 'development'
: 'production',
request_id: Helpers.generateUniqueId(),
request_timestamp_ms: new Date().getTime(),
previous_mpid: mpid || null,
known_identities: this.createKnownIdentities(identityApiData, deviceId)
known_identities: this.createKnownIdentities(
identityApiData,
deviceId
),
};

@@ -92,3 +119,10 @@

createModifyIdentityRequest: function(currentUserIdentities, newUserIdentities, platform, sdkVendor, sdkVersion, context) {
createModifyIdentityRequest: function(
currentUserIdentities,
newUserIdentities,
platform,
sdkVendor,
sdkVersion,
context
) {
return {

@@ -98,9 +132,14 @@ client_sdk: {

sdk_vendor: sdkVendor,
sdk_version: sdkVersion
sdk_version: sdkVersion,
},
context: context,
environment: mParticle.Store.SDKConfig.isDevelopmentMode ? 'development' : 'production',
environment: mParticle.Store.SDKConfig.isDevelopmentMode
? 'development'
: 'production',
request_id: Helpers.generateUniqueId(),
request_timestamp_ms: new Date().getTime(),
identity_changes: this.createIdentityChanges(currentUserIdentities, newUserIdentities)
identity_changes: this.createIdentityChanges(
currentUserIdentities,
newUserIdentities
),
};

@@ -112,3 +151,8 @@ },

var key;
if (newIdentities && Helpers.isObject(newIdentities) && previousIdentities && Helpers.isObject(previousIdentities)) {
if (
newIdentities &&
Helpers.isObject(newIdentities) &&
previousIdentities &&
Helpers.isObject(previousIdentities)
) {
for (key in newIdentities) {

@@ -118,3 +162,3 @@ identityChanges.push({

new_value: newIdentities[key],
identity_type: key
identity_type: key,
});

@@ -131,3 +175,4 @@ }

for (var key in newUserIdentities) {
modifiedUserIdentities[Types.IdentityType.getIdentityType(key)] = newUserIdentities[key];
modifiedUserIdentities[Types.IdentityType.getIdentityType(key)] =
newUserIdentities[key];
}

@@ -148,3 +193,5 @@

request_type: 'alias',
environment: mParticle.Store.SDKConfig.isDevelopmentMode ? 'development' : 'production',
environment: mParticle.Store.SDKConfig.isDevelopmentMode
? 'development'
: 'production',
api_key: mParticle.Store.devToken,

@@ -156,4 +203,4 @@ data: {

end_unixtime_ms: aliasRequest.endTime,
device_application_stamp: mParticle.Store.deviceId
}
device_application_stamp: mParticle.Store.deviceId,
},
};

@@ -167,3 +214,3 @@ },

StartUnixtimeMs: aliasRequest.startTime,
EndUnixtimeMs: aliasRequest.endTime
EndUnixtimeMs: aliasRequest.endTime,
};

@@ -179,3 +226,3 @@ },

Type: Types.IdentityType.getIdentityType(key),
Identity: identityApiData.userIdentities[key]
Identity: identityApiData.userIdentities[key],
});

@@ -186,24 +233,28 @@ }

return {
UserIdentities: nativeIdentityRequest
UserIdentities: nativeIdentityRequest,
};
}
}
},
};
/**
* Invoke these methods on the mParticle.Identity object.
* Example: mParticle.Identity.getCurrentUser().
* @class mParticle.Identity
*/
* Invoke these methods on the mParticle.Identity object.
* Example: mParticle.Identity.getCurrentUser().
* @class mParticle.Identity
*/
var IdentityAPI = {
HTTPCodes: HTTPCodes,
/**
* Initiate a logout request to the mParticle server
* @method identify
* @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)
* @param {Function} [callback] A callback function that is called when the identify request completes
*/
* Initiate a logout request to the mParticle server
* @method identify
* @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)
* @param {Function} [callback] A callback function that is called when the identify request completes
*/
identify: function(identityApiData, callback) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser(),
preProcessResult = IdentityRequest.preProcessIdentityRequest(identityApiData, callback, 'identify');
preProcessResult = IdentityRequest.preProcessIdentityRequest(
identityApiData,
callback,
'identify'
);
if (currentUser) {

@@ -214,17 +265,51 @@ mpid = currentUser.getMPID();

if (preProcessResult.valid) {
var identityApiRequest = IdentityRequest.createIdentityRequest(identityApiData, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mParticle.Store.deviceId, mParticle.Store.context, mpid);
var identityApiRequest = IdentityRequest.createIdentityRequest(
identityApiData,
Constants.platform,
Constants.sdkVendor,
Constants.sdkVersion,
mParticle.Store.deviceId,
mParticle.Store.context,
mpid
);
if (Helpers.canLog()) {
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify, JSON.stringify(IdentityRequest.convertToNative(identityApiData)));
Helpers.invokeCallback(callback, HTTPCodes.nativeIdentityRequest, 'Identify request sent to native sdk');
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Identify,
JSON.stringify(
IdentityRequest.convertToNative(identityApiData)
)
);
Helpers.invokeCallback(
callback,
HTTPCodes.nativeIdentityRequest,
'Identify request sent to native sdk'
);
} else {
sendIdentityRequest(identityApiRequest, 'identify', callback, identityApiData, parseIdentityResponse, mpid);
sendIdentityRequest(
identityApiRequest,
'identify',
callback,
identityApiData,
parseIdentityResponse,
mpid
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.loggingDisabledOrMissingAPIKey, Messages.InformationMessages.AbandonLogEvent);
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
Helpers.invokeCallback(
callback,
HTTPCodes.loggingDisabledOrMissingAPIKey,
Messages.InformationMessages.AbandonLogEvent
);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.validationIssue, preProcessResult.error);
Helpers.invokeCallback(
callback,
HTTPCodes.validationIssue,
preProcessResult.error
);
mParticle.Logger.verbose(preProcessResult);

@@ -234,11 +319,15 @@ }

/**
* Initiate a logout request to the mParticle server
* @method logout
* @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)
* @param {Function} [callback] A callback function that is called when the logout request completes
*/
* Initiate a logout request to the mParticle server
* @method logout
* @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)
* @param {Function} [callback] A callback function that is called when the logout request completes
*/
logout: function(identityApiData, callback) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser(),
preProcessResult = IdentityRequest.preProcessIdentityRequest(identityApiData, callback, 'logout');
preProcessResult = IdentityRequest.preProcessIdentityRequest(
identityApiData,
callback,
'logout'
);
if (currentUser) {

@@ -250,14 +339,42 @@ mpid = currentUser.getMPID();

var evt,
identityApiRequest = IdentityRequest.createIdentityRequest(identityApiData, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mParticle.Store.deviceId, mParticle.Store.context, mpid);
identityApiRequest = IdentityRequest.createIdentityRequest(
identityApiData,
Constants.platform,
Constants.sdkVendor,
Constants.sdkVersion,
mParticle.Store.deviceId,
mParticle.Store.context,
mpid
);
if (Helpers.canLog()) {
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout, JSON.stringify(IdentityRequest.convertToNative(identityApiData)));
Helpers.invokeCallback(callback, HTTPCodes.nativeIdentityRequest, 'Logout request sent to native sdk');
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Logout,
JSON.stringify(
IdentityRequest.convertToNative(identityApiData)
)
);
Helpers.invokeCallback(
callback,
HTTPCodes.nativeIdentityRequest,
'Logout request sent to native sdk'
);
} else {
sendIdentityRequest(identityApiRequest, 'logout', callback, identityApiData, parseIdentityResponse, mpid);
evt = ServerModel.createEventObject({ messageType: Types.MessageType.Profile });
sendIdentityRequest(
identityApiRequest,
'logout',
callback,
identityApiData,
parseIdentityResponse,
mpid
);
evt = ServerModel.createEventObject({
messageType: Types.MessageType.Profile,
});
evt.ProfileMessageType = Types.ProfileMessageType.Logout;
if (mParticle.Store.activeForwarders.length) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
mParticle.Store.activeForwarders.forEach(function(
forwarder
) {
if (forwarder.logOut) {

@@ -270,7 +387,17 @@ forwarder.logOut(evt);

} else {
Helpers.invokeCallback(callback, HTTPCodes.loggingDisabledOrMissingAPIKey, Messages.InformationMessages.AbandonLogEvent);
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
Helpers.invokeCallback(
callback,
HTTPCodes.loggingDisabledOrMissingAPIKey,
Messages.InformationMessages.AbandonLogEvent
);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.validationIssue, preProcessResult.error);
Helpers.invokeCallback(
callback,
HTTPCodes.validationIssue,
preProcessResult.error
);
mParticle.Logger.verbose(preProcessResult);

@@ -280,11 +407,15 @@ }

/**
* Initiate a login request to the mParticle server
* @method login
* @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)
* @param {Function} [callback] A callback function that is called when the login request completes
*/
* Initiate a login request to the mParticle server
* @method login
* @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)
* @param {Function} [callback] A callback function that is called when the login request completes
*/
login: function(identityApiData, callback) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser(),
preProcessResult = IdentityRequest.preProcessIdentityRequest(identityApiData, callback, 'login');
preProcessResult = IdentityRequest.preProcessIdentityRequest(
identityApiData,
callback,
'login'
);
if (currentUser) {

@@ -295,17 +426,51 @@ mpid = currentUser.getMPID();

if (preProcessResult.valid) {
var identityApiRequest = IdentityRequest.createIdentityRequest(identityApiData, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mParticle.Store.deviceId, mParticle.Store.context, mpid);
var identityApiRequest = IdentityRequest.createIdentityRequest(
identityApiData,
Constants.platform,
Constants.sdkVendor,
Constants.sdkVersion,
mParticle.Store.deviceId,
mParticle.Store.context,
mpid
);
if (Helpers.canLog()) {
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login, JSON.stringify(IdentityRequest.convertToNative(identityApiData)));
Helpers.invokeCallback(callback, HTTPCodes.nativeIdentityRequest, 'Login request sent to native sdk');
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Login,
JSON.stringify(
IdentityRequest.convertToNative(identityApiData)
)
);
Helpers.invokeCallback(
callback,
HTTPCodes.nativeIdentityRequest,
'Login request sent to native sdk'
);
} else {
sendIdentityRequest(identityApiRequest, 'login', callback, identityApiData, parseIdentityResponse, mpid);
sendIdentityRequest(
identityApiRequest,
'login',
callback,
identityApiData,
parseIdentityResponse,
mpid
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.loggingDisabledOrMissingAPIKey, Messages.InformationMessages.AbandonLogEvent);
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
Helpers.invokeCallback(
callback,
HTTPCodes.loggingDisabledOrMissingAPIKey,
Messages.InformationMessages.AbandonLogEvent
);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.validationIssue, preProcessResult.error);
Helpers.invokeCallback(
callback,
HTTPCodes.validationIssue,
preProcessResult.error
);
mParticle.Logger.verbose(preProcessResult);

@@ -315,31 +480,73 @@ }

/**
* Initiate a modify request to the mParticle server
* @method modify
* @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)
* @param {Function} [callback] A callback function that is called when the modify request completes
*/
* Initiate a modify request to the mParticle server
* @method modify
* @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)
* @param {Function} [callback] A callback function that is called when the modify request completes
*/
modify: function(identityApiData, callback) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser(),
preProcessResult = IdentityRequest.preProcessIdentityRequest(identityApiData, callback, 'modify');
preProcessResult = IdentityRequest.preProcessIdentityRequest(
identityApiData,
callback,
'modify'
);
if (currentUser) {
mpid = currentUser.getMPID();
}
var newUserIdentities = (identityApiData && identityApiData.userIdentities) ? identityApiData.userIdentities : {};
var newUserIdentities =
identityApiData && identityApiData.userIdentities
? identityApiData.userIdentities
: {};
if (preProcessResult.valid) {
var identityApiRequest = IdentityRequest.createModifyIdentityRequest(currentUser ? currentUser.getUserIdentities().userIdentities : {}, newUserIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mParticle.Store.context);
var identityApiRequest = IdentityRequest.createModifyIdentityRequest(
currentUser
? currentUser.getUserIdentities().userIdentities
: {},
newUserIdentities,
Constants.platform,
Constants.sdkVendor,
Constants.sdkVersion,
mParticle.Store.context
);
if (Helpers.canLog()) {
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify, JSON.stringify(IdentityRequest.convertToNative(identityApiData)));
Helpers.invokeCallback(callback, HTTPCodes.nativeIdentityRequest, 'Modify request sent to native sdk');
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Modify,
JSON.stringify(
IdentityRequest.convertToNative(identityApiData)
)
);
Helpers.invokeCallback(
callback,
HTTPCodes.nativeIdentityRequest,
'Modify request sent to native sdk'
);
} else {
sendIdentityRequest(identityApiRequest, 'modify', callback, identityApiData, parseIdentityResponse, mpid);
sendIdentityRequest(
identityApiRequest,
'modify',
callback,
identityApiData,
parseIdentityResponse,
mpid
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.loggingDisabledOrMissingAPIKey, Messages.InformationMessages.AbandonLogEvent);
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
Helpers.invokeCallback(
callback,
HTTPCodes.loggingDisabledOrMissingAPIKey,
Messages.InformationMessages.AbandonLogEvent
);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
} else {
Helpers.invokeCallback(callback, HTTPCodes.validationIssue, preProcessResult.error);
Helpers.invokeCallback(
callback,
HTTPCodes.validationIssue,
preProcessResult.error
);
mParticle.Logger.verbose(preProcessResult);

@@ -349,6 +556,6 @@ }

/**
* Returns a user object with methods to interact with the current user
* @method getCurrentUser
* @return {Object} the current user object
*/
* Returns a user object with methods to interact with the current user
* @method getCurrentUser
* @return {Object} the current user object
*/
getCurrentUser: function() {

@@ -367,12 +574,15 @@ var mpid = mParticle.Store.mpid;

/**
* Returns a the user object associated with the mpid parameter or 'null' if no such
* user exists
* @method getUser
* @param {String} mpid of the desired user
* @return {Object} the user for mpid
*/
* Returns a the user object associated with the mpid parameter or 'null' if no such
* user exists
* @method getUser
* @param {String} mpid of the desired user
* @return {Object} the user for mpid
*/
getUser: function(mpid) {
var cookies = Persistence.getPersistence();
if (cookies) {
if (cookies[mpid] && !Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)) {
if (
cookies[mpid] &&
!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)
) {
return mParticleUser(mpid);

@@ -388,6 +598,6 @@ } else {

/**
* Returns all users, including the current user and all previous users that are stored on the device.
* @method getUsers
* @return {Array} array of users
*/
* Returns all users, including the current user and all previous users that are stored on the device.
* @method getUsers
* @return {Array} array of users
*/
getUsers: function() {

@@ -416,7 +626,7 @@ var cookies = Persistence.getPersistence();

/**
* Initiate an alias request to the mParticle server
* @method aliasUsers
* @param {Object} aliasRequest object representing an AliasRequest
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
*/
* Initiate an alias request to the mParticle server
* @method aliasUsers
* @param {Object} aliasRequest object representing an AliasRequest
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
*/
aliasUsers: function(aliasRequest, callback) {

@@ -438,3 +648,7 @@ var message;

mParticle.Logger.warning(message);
Helpers.invokeAliasCallback(callback, HTTPCodes.validationIssue, message);
Helpers.invokeAliasCallback(
callback,
HTTPCodes.validationIssue,
message
);
return;

@@ -444,12 +658,35 @@ }

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias, JSON.stringify(IdentityRequest.convertAliasToNative(aliasRequest)));
Helpers.invokeAliasCallback(callback, HTTPCodes.nativeIdentityRequest, 'Alias request sent to native sdk');
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Alias,
JSON.stringify(
IdentityRequest.convertAliasToNative(aliasRequest)
)
);
Helpers.invokeAliasCallback(
callback,
HTTPCodes.nativeIdentityRequest,
'Alias request sent to native sdk'
);
} else {
mParticle.Logger.verbose(Messages.InformationMessages.StartingAliasRequest + ': ' + aliasRequest.sourceMpid + ' -> ' + aliasRequest.destinationMpid);
var aliasRequestMessage = IdentityRequest.createAliasNetworkRequest(aliasRequest);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingAliasRequest +
': ' +
aliasRequest.sourceMpid +
' -> ' +
aliasRequest.destinationMpid
);
var aliasRequestMessage = IdentityRequest.createAliasNetworkRequest(
aliasRequest
);
ApiClient.sendAliasRequest(aliasRequestMessage, callback);
}
} else {
Helpers.invokeAliasCallback(callback, HTTPCodes.loggingDisabledOrMissingAPIKey, Messages.InformationMessages.AbandonAliasUsers);
mParticle.Logger.verbose(Messages.InformationMessages.AbandonAliasUsers);
Helpers.invokeAliasCallback(
callback,
HTTPCodes.loggingDisabledOrMissingAPIKey,
Messages.InformationMessages.AbandonAliasUsers
);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonAliasUsers
);
}

@@ -476,3 +713,5 @@ },

if (!destinationUser || !sourceUser) {
mParticle.Logger.error('\'destinationUser\' and \'sourceUser\' must both be present');
mParticle.Logger.error(
"'destinationUser' and 'sourceUser' must both be present"
);
return null;

@@ -483,3 +722,6 @@ }

mParticle.Identity.getUsers().forEach(function(user) {
if (user.getFirstSeenTime() && (!startTime || user.getFirstSeenTime() < startTime)) {
if (
user.getFirstSeenTime() &&
(!startTime || user.getFirstSeenTime() < startTime)
) {
startTime = user.getFirstSeenTime();

@@ -489,3 +731,5 @@ }

}
var minFirstSeenTimeMs = new Date().getTime() - mParticle.Store.SDKConfig.aliasMaxWindow * 24 * 60 * 60 * 1000 ;
var minFirstSeenTimeMs =
new Date().getTime() -
mParticle.Store.SDKConfig.aliasMaxWindow * 24 * 60 * 60 * 1000;
var endTime = sourceUser.getLastSeenTime() || new Date().getTime();

@@ -496,3 +740,7 @@ //if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed

if (endTime < startTime) {
mParticle.Logger.warning('Source User has not been seen in the last ' + mParticle.Store.SDKConfig.maxAliasWindow + ' days, Alias Request will likely fail');
mParticle.Logger.warning(
'Source User has not been seen in the last ' +
mParticle.Store.SDKConfig.maxAliasWindow +
' days, Alias Request will likely fail'
);
}

@@ -504,23 +752,25 @@ }

startTime: startTime,
endTime: endTime
endTime: endTime,
};
} catch (e) {
mParticle.Logger.error('There was a problem with creating an alias request: ' + e);
mParticle.Logger.error(
'There was a problem with creating an alias request: ' + e
);
return null;
}
}
},
};
/**
* Invoke these methods on the mParticle.Identity.getCurrentUser() object.
* Example: mParticle.Identity.getCurrentUser().getAllUserAttributes()
* @class mParticle.Identity.getCurrentUser()
*/
* Invoke these methods on the mParticle.Identity.getCurrentUser() object.
* Example: mParticle.Identity.getCurrentUser().getAllUserAttributes()
* @class mParticle.Identity.getCurrentUser()
*/
function mParticleUser(mpid, isLoggedIn) {
return {
/**
* Get user identities for current user
* @method getUserIdentities
* @return {Object} an object with userIdentities as its key
*/
* Get user identities for current user
* @method getUserIdentities
* @return {Object} an object with userIdentities as its key
*/
getUserIdentities: function() {

@@ -533,3 +783,7 @@ var currentUserIdentities = {};

if (identities.hasOwnProperty(identityType)) {
currentUserIdentities[Types.IdentityType.getIdentityName(Helpers.parseNumber(identityType))] = identities[identityType];
currentUserIdentities[
Types.IdentityType.getIdentityName(
Helpers.parseNumber(identityType)
)
] = identities[identityType];
}

@@ -539,10 +793,10 @@ }

return {
userIdentities: currentUserIdentities
userIdentities: currentUserIdentities,
};
},
/**
* Get the MPID of the current user
* @method getMPID
* @return {String} the current user MPID as a string
*/
* Get the MPID of the current user
* @method getMPID
* @return {String} the current user MPID as a string
*/
getMPID: function() {

@@ -552,6 +806,6 @@ return mpid;

/**
* Sets a user tag
* @method setUserTag
* @param {String} tagName
*/
* Sets a user tag
* @method setUserTag
* @param {String} tagName
*/
setUserTag: function(tagName) {

@@ -566,6 +820,6 @@ if (!Validators.isValidKeyValue(tagName)) {

/**
* Removes a user tag
* @method removeUserTag
* @param {String} tagName
*/
* Removes a user tag
* @method removeUserTag
* @param {String} tagName
*/
removeUserTag: function(tagName) {

@@ -580,10 +834,9 @@ if (!Validators.isValidKeyValue(tagName)) {

/**
* Sets a user attribute
* @method setUserAttribute
* @param {String} key
* @param {String} value
*/
* Sets a user attribute
* @method setUserAttribute
* @param {String} key
* @param {String} value
*/
setUserAttribute: function(key, value) {
var cookies,
userAttributes;
var cookies, userAttributes;

@@ -603,3 +856,6 @@ mParticle.sessionManager.resetSessionTimer();

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute, JSON.stringify({ key: key, value: value }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.SetUserAttribute,
JSON.stringify({ key: key, value: value })
);
} else {

@@ -610,3 +866,6 @@ cookies = Persistence.getPersistence();

var existingProp = Helpers.findKeyInObject(userAttributes, key);
var existingProp = Helpers.findKeyInObject(
userAttributes,
key
);

@@ -623,3 +882,6 @@ if (existingProp) {

Forwarders.initForwarders(IdentityAPI.getCurrentUser().getUserIdentities(), ApiClient.prepareForwardingStats);
Forwarders.initForwarders(
IdentityAPI.getCurrentUser().getUserIdentities(),
ApiClient.prepareForwardingStats
);
Forwarders.callSetUserAttributeOnForwarders(key, value);

@@ -630,6 +892,6 @@ }

/**
* Set multiple user attributes
* @method setUserAttributes
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
*/
* Set multiple user attributes
* @method setUserAttributes
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
*/
setUserAttributes: function(userAttributes) {

@@ -646,10 +908,13 @@ mParticle.sessionManager.resetSessionTimer();

} else {
mParticle.Logger.error('Must pass an object into setUserAttributes. You passed a ' + typeof userAttributes);
mParticle.Logger.error(
'Must pass an object into setUserAttributes. You passed a ' +
typeof userAttributes
);
}
},
/**
* Removes a specific user attribute
* @method removeUserAttribute
* @param {String} key
*/
* Removes a specific user attribute
* @method removeUserAttribute
* @param {String} key
*/
removeUserAttribute: function(key) {

@@ -665,3 +930,6 @@ var cookies, userAttributes;

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute, JSON.stringify({ key: key, value: null }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.RemoveUserAttribute,
JSON.stringify({ key: key, value: null })
);
} else {

@@ -685,3 +953,6 @@ cookies = Persistence.getPersistence();

Forwarders.initForwarders(IdentityAPI.getCurrentUser().getUserIdentities(), ApiClient.prepareForwardingStats);
Forwarders.initForwarders(
IdentityAPI.getCurrentUser().getUserIdentities(),
ApiClient.prepareForwardingStats
);
Forwarders.applyToForwarders('removeUserAttribute', key);

@@ -691,7 +962,7 @@ }

/**
* Sets a list of user attributes
* @method setUserAttributeList
* @param {String} key
* @param {Array} value an array of values
*/
* Sets a list of user attributes
* @method setUserAttributeList
* @param {String} key
* @param {Array} value an array of values
*/
setUserAttributeList: function(key, value) {

@@ -708,3 +979,6 @@ var cookies, userAttributes;

if (!Array.isArray(value)) {
mParticle.Logger.error('The value you passed in to setUserAttributeList must be an array. You passed in a ' + typeof value);
mParticle.Logger.error(
'The value you passed in to setUserAttributeList must be an array. You passed in a ' +
typeof value
);
return;

@@ -716,3 +990,6 @@ }

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList, JSON.stringify({ key: key, value: arrayCopy }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.SetUserAttributeList,
JSON.stringify({ key: key, value: arrayCopy })
);
} else {

@@ -735,3 +1012,6 @@ cookies = Persistence.getPersistence();

Forwarders.initForwarders(IdentityAPI.getCurrentUser().getUserIdentities(), ApiClient.prepareForwardingStats);
Forwarders.initForwarders(
IdentityAPI.getCurrentUser().getUserIdentities(),
ApiClient.prepareForwardingStats
);
Forwarders.callSetUserAttributeOnForwarders(key, arrayCopy);

@@ -741,5 +1021,5 @@ }

/**
* Removes all user attributes
* @method removeAllUserAttributes
*/
* Removes all user attributes
* @method removeAllUserAttributes
*/
removeAllUserAttributes: function() {

@@ -751,3 +1031,5 @@ var cookies, userAttributes;

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.RemoveAllUserAttributes
);
} else {

@@ -758,7 +1040,13 @@ cookies = Persistence.getPersistence();

Forwarders.initForwarders(IdentityAPI.getCurrentUser().getUserIdentities()), ApiClient.prepareForwardingStats;
Forwarders.initForwarders(
IdentityAPI.getCurrentUser().getUserIdentities(),
ApiClient.prepareForwardingStats
);
if (userAttributes) {
for (var prop in userAttributes) {
if (userAttributes.hasOwnProperty(prop)) {
Forwarders.applyToForwarders('removeUserAttribute', prop);
Forwarders.applyToForwarders(
'removeUserAttribute',
prop
);
}

@@ -775,6 +1063,6 @@ }

/**
* Returns all user attribute keys that have values that are arrays
* @method getUserAttributesLists
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
*/
* Returns all user attribute keys that have values that are arrays
* @method getUserAttributesLists
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
*/
getUserAttributesLists: function() {

@@ -786,3 +1074,6 @@ var userAttributes,

for (var key in userAttributes) {
if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) {
if (
userAttributes.hasOwnProperty(key) &&
Array.isArray(userAttributes[key])
) {
userAttributesLists[key] = userAttributes[key].slice();

@@ -795,6 +1086,6 @@ }

/**
* Returns all user attributes
* @method getAllUserAttributes
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
*/
* Returns all user attributes
* @method getAllUserAttributes
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
*/
getAllUserAttributes: function() {

@@ -808,5 +1099,6 @@ var userAttributesCopy = {};

if (Array.isArray(userAttributes[prop])) {
userAttributesCopy[prop] = userAttributes[prop].slice();
}
else {
userAttributesCopy[prop] = userAttributes[
prop
].slice();
} else {
userAttributesCopy[prop] = userAttributes[prop];

@@ -821,6 +1113,6 @@ }

/**
* Returns the cart object for the current user
* @method getCart
* @return a cart object
*/
* Returns the cart object for the current user
* @method getCart
* @return a cart object
*/
getCart: function() {

@@ -831,6 +1123,6 @@ return mParticleUserCart(mpid);

/**
* Returns the Consent State stored locally for this user.
* @method getConsentState
* @return a ConsentState object
*/
* Returns the Consent State stored locally for this user.
* @method getConsentState
* @return a ConsentState object
*/
getConsentState: function() {

@@ -840,9 +1132,12 @@ return Persistence.getConsentState(mpid);

/**
* Sets the Consent State stored locally for this user.
* @method setConsentState
* @param {Object} consent state
*/
* Sets the Consent State stored locally for this user.
* @method setConsentState
* @param {Object} consent state
*/
setConsentState: function(state) {
Persistence.saveUserConsentStateToCookies(mpid, state);
Forwarders.initForwarders(this.getUserIdentities().userIdentities), ApiClient.prepareForwardingStats;
Forwarders.initForwarders(
this.getUserIdentities().userIdentities,
ApiClient.prepareForwardingStats
);
},

@@ -857,3 +1152,3 @@ isLoggedIn: function() {

return Persistence.getFirstSeenTime(mpid);
}
},
};

@@ -863,26 +1158,29 @@ }

/**
* Invoke these methods on the mParticle.Identity.getCurrentUser().getCart() object.
* Example: mParticle.Identity.getCurrentUser().getCart().add(...);
* @class mParticle.Identity.getCurrentUser().getCart()
*/
function mParticleUserCart(mpid){
* Invoke these methods on the mParticle.Identity.getCurrentUser().getCart() object.
* Example: mParticle.Identity.getCurrentUser().getCart().add(...);
* @class mParticle.Identity.getCurrentUser().getCart()
*/
function mParticleUserCart(mpid) {
return {
/**
* Adds a cart product to the user cart
* @method add
* @param {Object} product the product
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
*/
* Adds a cart product to the user cart
* @method add
* @param {Object} product the product
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
*/
add: function(product, logEvent) {
var allProducts,
userProducts,
arrayCopy;
var allProducts, userProducts, arrayCopy;
arrayCopy = Array.isArray(product) ? product.slice() : [product];
arrayCopy.forEach(function(product) {
product.Attributes = Helpers.sanitizeAttributes(product.Attributes);
product.Attributes = Helpers.sanitizeAttributes(
product.Attributes
);
});
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.AddToCart, JSON.stringify(arrayCopy));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.AddToCart,
JSON.stringify(arrayCopy)
);
} else {

@@ -896,11 +1194,24 @@ mParticle.sessionManager.resetSessionTimer();

if (logEvent === true) {
Events.logProductActionEvent(Types.ProductActionType.AddToCart, arrayCopy);
Events.logProductActionEvent(
Types.ProductActionType.AddToCart,
arrayCopy
);
}
var productsForMemory = {};
productsForMemory[mpid] = {cp: userProducts};
productsForMemory[mpid] = { cp: userProducts };
if (userProducts.length > mParticle.Store.SDKConfig.maxProducts) {
mParticle.Logger.verbose('The cart contains ' + userProducts.length + ' items. Only ' + mParticle.Store.SDKConfig.maxProducts + ' can currently be saved in cookies.');
userProducts = userProducts.slice(-mParticle.Store.SDKConfig.maxProducts);
if (
userProducts.length > mParticle.Store.SDKConfig.maxProducts
) {
mParticle.Logger.verbose(
'The cart contains ' +
userProducts.length +
' items. Only ' +
mParticle.Store.SDKConfig.maxProducts +
' can currently be saved in cookies.'
);
userProducts = userProducts.slice(
-mParticle.Store.SDKConfig.maxProducts
);
}

@@ -915,7 +1226,7 @@

/**
* Removes a cart product from the current user cart
* @method remove
* @param {Object} product the product
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
*/
* Removes a cart product from the current user cart
* @method remove
* @param {Object} product the product
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
*/
remove: function(product, logEvent) {

@@ -928,3 +1239,6 @@ var allProducts,

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveFromCart, JSON.stringify(product));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.RemoveFromCart,
JSON.stringify(product)
);
} else {

@@ -947,3 +1261,6 @@ mParticle.sessionManager.resetSessionTimer();

if (logEvent === true) {
Events.logProductActionEvent(Types.ProductActionType.RemoveFromCart, cartItem);
Events.logProductActionEvent(
Types.ProductActionType.RemoveFromCart,
cartItem
);
}

@@ -954,3 +1271,3 @@ }

var productsForMemory = {};
productsForMemory[mpid] = {cp: userProducts};
productsForMemory[mpid] = { cp: userProducts };

@@ -965,5 +1282,5 @@ allProducts = Persistence.getAllUserProductsFromLS();

/**
* Clears the user's cart
* @method clear
*/
* Clears the user's cart
* @method clear
*/
clear: function() {

@@ -973,3 +1290,5 @@ var allProducts;

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.ClearCart);
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.ClearCart
);
} else {

@@ -989,13 +1308,19 @@ mParticle.sessionManager.resetSessionTimer();

/**
* Returns all cart products
* @method getCartProducts
* @return {Array} array of cart products
*/
* Returns all cart products
* @method getCartProducts
* @return {Array} array of cart products
*/
getCartProducts: function() {
return Persistence.getCartProducts(mpid);
}
},
};
}
function parseIdentityResponse(xhr, previousMPID, callback, identityApiData, method) {
function parseIdentityResponse(
xhr,
previousMPID,
callback,
identityApiData,
method
) {
var prevUser = mParticle.Identity.getCurrentUser(),

@@ -1007,5 +1332,9 @@ newUser,

var userIdentitiesForModify = {},
userIdentities = prevUser ? prevUser.getUserIdentities().userIdentities : {};
userIdentities = prevUser
? prevUser.getUserIdentities().userIdentities
: {};
for (var identityKey in userIdentities) {
userIdentitiesForModify[Types.IdentityType.getIdentityType(identityKey)] = userIdentities[identityKey];
userIdentitiesForModify[
Types.IdentityType.getIdentityType(identityKey)
] = userIdentities[identityKey];
}

@@ -1018,3 +1347,5 @@

try {
mParticle.Logger.verbose('Parsing "' + method + '" identity response from server');
mParticle.Logger.verbose(
'Parsing "' + method + '" identity response from server'
);
if (xhr.responseText) {

@@ -1028,10 +1359,23 @@ identityApiResult = JSON.parse(xhr.responseText);

if (method === 'modify') {
newIdentities = IdentityRequest.modifyUserIdentities(userIdentitiesForModify, identityApiData.userIdentities);
Persistence.saveUserIdentitiesToCookies(prevUser.getMPID(), newIdentities);
newIdentities = IdentityRequest.modifyUserIdentities(
userIdentitiesForModify,
identityApiData.userIdentities
);
Persistence.saveUserIdentitiesToCookies(
prevUser.getMPID(),
newIdentities
);
} else {
identityApiResult = JSON.parse(xhr.responseText);
mParticle.Logger.verbose('Successfully parsed Identity Response');
mParticle.Logger.verbose(
'Successfully parsed Identity Response'
);
if (!(prevUser) || (prevUser.getMPID() && identityApiResult.mpid && identityApiResult.mpid !== prevUser.getMPID())) {
if (
!prevUser ||
(prevUser.getMPID() &&
identityApiResult.mpid &&
identityApiResult.mpid !== prevUser.getMPID())
) {
mParticle.Store.mpid = identityApiResult.mpid;

@@ -1047,34 +1391,81 @@ if (prevUser) {

//the current MPID will never change
if (method === 'identify' && prevUser && identityApiResult.mpid === prevUser.getMPID()) {
if (
method === 'identify' &&
prevUser &&
identityApiResult.mpid === prevUser.getMPID()
) {
Persistence.setFirstSeenTime(identityApiResult.mpid);
}
indexOfMPID = mParticle.Store.currentSessionMPIDs.indexOf(identityApiResult.mpid);
indexOfMPID = mParticle.Store.currentSessionMPIDs.indexOf(
identityApiResult.mpid
);
if (mParticle.Store.sessionId && identityApiResult.mpid && previousMPID !== identityApiResult.mpid && indexOfMPID < 0) {
mParticle.Store.currentSessionMPIDs.push(identityApiResult.mpid);
if (
mParticle.Store.sessionId &&
identityApiResult.mpid &&
previousMPID !== identityApiResult.mpid &&
indexOfMPID < 0
) {
mParticle.Store.currentSessionMPIDs.push(
identityApiResult.mpid
);
}
if (indexOfMPID > -1) {
mParticle.Store.currentSessionMPIDs = (mParticle.Store.currentSessionMPIDs.slice(0, indexOfMPID)).concat(mParticle.Store.currentSessionMPIDs.slice(indexOfMPID + 1, mParticle.Store.currentSessionMPIDs.length));
mParticle.Store.currentSessionMPIDs.push(identityApiResult.mpid);
mParticle.Store.currentSessionMPIDs = mParticle.Store.currentSessionMPIDs
.slice(0, indexOfMPID)
.concat(
mParticle.Store.currentSessionMPIDs.slice(
indexOfMPID + 1,
mParticle.Store.currentSessionMPIDs.length
)
);
mParticle.Store.currentSessionMPIDs.push(
identityApiResult.mpid
);
}
Persistence.saveUserIdentitiesToCookies(identityApiResult.mpid, newIdentities);
CookieSyncManager.attemptCookieSync(previousMPID, identityApiResult.mpid);
Persistence.saveUserIdentitiesToCookies(
identityApiResult.mpid,
newIdentities
);
CookieSyncManager.attemptCookieSync(
previousMPID,
identityApiResult.mpid
);
checkIdentitySwap(previousMPID, identityApiResult.mpid, mParticle.Store.currentSessionMPIDs);
checkIdentitySwap(
previousMPID,
identityApiResult.mpid,
mParticle.Store.currentSessionMPIDs
);
//if there is any previous migration data
if (Object.keys(mParticle.Store.migrationData).length) {
newIdentities = mParticle.Store.migrationData.userIdentities || {};
var userAttributes = mParticle.Store.migrationData.userAttributes || {};
Persistence.saveUserAttributesToCookies(identityApiResult.mpid, userAttributes);
newIdentities =
mParticle.Store.migrationData.userIdentities || {};
var userAttributes =
mParticle.Store.migrationData.userAttributes || {};
Persistence.saveUserAttributesToCookies(
identityApiResult.mpid,
userAttributes
);
} else {
if (identityApiData && identityApiData.userIdentities && Object.keys(identityApiData.userIdentities).length) {
newIdentities = IdentityRequest.modifyUserIdentities(userIdentitiesForModify, identityApiData.userIdentities);
if (
identityApiData &&
identityApiData.userIdentities &&
Object.keys(identityApiData.userIdentities).length
) {
newIdentities = IdentityRequest.modifyUserIdentities(
userIdentitiesForModify,
identityApiData.userIdentities
);
}
}
Persistence.saveUserIdentitiesToCookies(identityApiResult.mpid, newIdentities);
Persistence.saveUserIdentitiesToCookies(
identityApiResult.mpid,
newIdentities
);
Persistence.update();

@@ -1084,3 +1475,4 @@

mParticle.Store.context = identityApiResult.context || mParticle.Store.context;
mParticle.Store.context =
identityApiResult.context || mParticle.Store.context;
}

@@ -1090,19 +1482,37 @@

if (identityApiData && identityApiData.onUserAlias && Helpers.Validators.isFunction(identityApiData.onUserAlias)) {
if (
identityApiData &&
identityApiData.onUserAlias &&
Helpers.Validators.isFunction(identityApiData.onUserAlias)
) {
try {
mParticle.Logger.warning('Deprecated function onUserAlias will be removed in future releases');
mParticle.Logger.warning(
'Deprecated function onUserAlias will be removed in future releases'
);
identityApiData.onUserAlias(prevUser, newUser);
} catch (e) {
mParticle.Logger.error(
'There was an error with your onUserAlias function - ' +
e
);
}
catch (e) {
mParticle.Logger.error('There was an error with your onUserAlias function - ' + e);
}
}
var cookies = Persistence.getCookie() || Persistence.getLocalStorage();
var cookies =
Persistence.getCookie() || Persistence.getLocalStorage();
if (newUser) {
Persistence.storeDataInMemory(cookies, newUser.getMPID());
if (!prevUser || newUser.getMPID() !== prevUser.getMPID() || prevUser.isLoggedIn() !== newUser.isLoggedIn()) {
Forwarders.initForwarders(newUser.getUserIdentities().userIdentities, ApiClient.prepareForwardingStats);
if (
!prevUser ||
newUser.getMPID() !== prevUser.getMPID() ||
prevUser.isLoggedIn() !== newUser.isLoggedIn()
) {
Forwarders.initForwarders(
newUser.getUserIdentities().userIdentities,
ApiClient.prepareForwardingStats
);
}
Forwarders.setForwarderUserIdentities(newUser.getUserIdentities().userIdentities);
Forwarders.setForwarderUserIdentities(
newUser.getUserIdentities().userIdentities
);
Forwarders.setForwarderOnIdentityComplete(newUser, method);

@@ -1117,17 +1527,41 @@ Forwarders.setForwarderOnUserIdentified(newUser, method);

if (xhr.status === 0) {
Helpers.invokeCallback(callback, HTTPCodes.noHttpCoverage, identityApiResult || null, newUser);
Helpers.invokeCallback(
callback,
HTTPCodes.noHttpCoverage,
identityApiResult || null,
newUser
);
} else {
Helpers.invokeCallback(callback, xhr.status, identityApiResult || null, newUser);
Helpers.invokeCallback(
callback,
xhr.status,
identityApiResult || null,
newUser
);
}
} else {
if (identityApiResult && identityApiResult.errors && identityApiResult.errors.length) {
mParticle.Logger.error('Received HTTP response code of ' + xhr.status + ' - ' + identityApiResult.errors[0].message);
if (
identityApiResult &&
identityApiResult.errors &&
identityApiResult.errors.length
) {
mParticle.Logger.error(
'Received HTTP response code of ' +
xhr.status +
' - ' +
identityApiResult.errors[0].message
);
}
}
}
catch (e) {
} catch (e) {
if (callback) {
Helpers.invokeCallback(callback, xhr.status, identityApiResult || null);
Helpers.invokeCallback(
callback,
xhr.status,
identityApiResult || null
);
}
mParticle.Logger.error('Error parsing JSON response from Identity server: ' + e);
mParticle.Logger.error(
'Error parsing JSON response from Identity server: ' + e
);
}

@@ -1141,3 +1575,3 @@ }

mParticleUser: mParticleUser,
mParticleUserCart: mParticleUserCart
};
mParticleUserCart: mParticleUserCart,
};

@@ -19,3 +19,6 @@ function Logger(config) {

if (logLevel !== 'none') {
if ((this.logger.warning && (logLevel === 'verbose' || logLevel === 'warning'))) {
if (
this.logger.warning &&
(logLevel === 'verbose' || logLevel === 'warning')
) {
this.logger.warning(msg);

@@ -34,3 +37,3 @@ }

this.setLogLevel = function (newLogLevel) {
this.setLogLevel = function(newLogLevel) {
logLevel = newLogLevel;

@@ -41,3 +44,3 @@ };

function ConsoleLogger() {
this.verbose = function (msg) {
this.verbose = function(msg) {
if (window.console && window.console.info) {

@@ -48,3 +51,3 @@ window.console.info(msg);

this.error = function (msg) {
this.error = function(msg) {
if (window.console && window.console.error) {

@@ -54,3 +57,3 @@ window.console.error(msg);

};
this.warning = function (msg) {
this.warning = function(msg) {
if (window.console && window.console.warn) {

@@ -62,2 +65,2 @@ window.console.warn(msg);

export default Logger;
export default Logger;

@@ -63,7 +63,7 @@ //

/**
* Invoke these methods on the mParticle object.
* Example: mParticle.endSession()
*
* @class mParticle
*/
* Invoke these methods on the mParticle object.
* Example: mParticle.endSession()
*
* @class mParticle
*/

@@ -78,3 +78,6 @@ var mParticle = {

persistence: Persistence,
isIOS: window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false,
isIOS:
window.mParticle && window.mParticle.isIOS
? window.mParticle.isIOS
: false,
Identity: IdentityAPI,

@@ -90,11 +93,13 @@ Validators: Validators,

/**
* Initializes the mParticle SDK
*
* @method init
* @param {String} apiKey your mParticle assigned API key
* @param {Object} [options] an options object for additional configuration
*/
* Initializes the mParticle SDK
*
* @method init
* @param {String} apiKey your mParticle assigned API key
* @param {Object} [options] an options object for additional configuration
*/
init: function(apiKey, config) {
if (!config && window.mParticle.config) {
window.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');
window.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'
);
config = window.mParticle.config;

@@ -109,4 +114,11 @@ }

if (config) {
if (!config.hasOwnProperty('requestConfig') || config.requestConfig) {
ApiClient.getSDKConfiguration(apiKey, config, completeSDKInitialization);
if (
!config.hasOwnProperty('requestConfig') ||
config.requestConfig
) {
ApiClient.getSDKConfiguration(
apiKey,
config,
completeSDKInitialization
);
} else {

@@ -116,3 +128,5 @@ completeSDKInitialization(apiKey, config);

} else {
window.console.error('No config available on the window, please pass a config object to mParticle.init()');
window.console.error(
'No config available on the window, please pass a config object to mParticle.init()'
);
return;

@@ -125,6 +139,6 @@ }

/**
* Completely resets the state of the SDK. mParticle.init(apiKey, window.mParticle.config) will need to be called again.
* @method reset
* @param {Boolean} keepPersistence if passed as true, this method will only reset the in-memory SDK state.
*/
* Completely resets the state of the SDK. mParticle.init(apiKey, window.mParticle.config) will need to be called again.
* @method reset
* @param {Boolean} keepPersistence if passed as true, this method will only reset the in-memory SDK state.
*/
reset: function(config, keepPersistence) {

@@ -135,3 +149,5 @@ if (mParticle.Store) {

mParticle.Store = new Store(config);
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(
window.localStorage
);
Events.stopTracking();

@@ -148,3 +164,3 @@ if (!keepPersistence) {

forwarderConstructors: [],
isDevelopmentMode: false
isDevelopmentMode: false,
};

@@ -155,4 +171,3 @@ },

f();
}
else {
} else {
mParticle.preInit.readyQueue.push(f);

@@ -162,6 +177,6 @@ }

/**
* Returns the mParticle SDK version number
* @method getVersion
* @return {String} mParticle SDK version number
*/
* Returns the mParticle SDK version number
* @method getVersion
* @return {String} mParticle SDK version number
*/
getVersion: function() {

@@ -171,6 +186,6 @@ return Constants.sdkVersion;

/**
* Sets the app version
* @method setAppVersion
* @param {String} version version number
*/
* Sets the app version
* @method setAppVersion
* @param {String} version version number
*/
setAppVersion: function(version) {

@@ -181,6 +196,6 @@ mParticle.Store.SDKConfig.appVersion = version;

/**
* Gets the app name
* @method getAppName
* @return {String} App name
*/
* Gets the app name
* @method getAppName
* @return {String} App name
*/
getAppName: function() {

@@ -190,6 +205,6 @@ return mParticle.Store.SDKConfig.appName;

/**
* Sets the app name
* @method setAppName
* @param {String} name App Name
*/
* Sets the app name
* @method setAppName
* @param {String} name App Name
*/
setAppName: function(name) {

@@ -199,6 +214,6 @@ mParticle.Store.SDKConfig.appName = name;

/**
* Gets the app version
* @method getAppVersion
* @return {String} App version
*/
* Gets the app version
* @method getAppVersion
* @return {String} App version
*/
getAppVersion: function() {

@@ -208,5 +223,5 @@ return mParticle.Store.SDKConfig.appVersion;

/**
* Stops tracking the location of the user
* @method stopTrackingLocation
*/
* Stops tracking the location of the user
* @method stopTrackingLocation
*/
stopTrackingLocation: function() {

@@ -217,9 +232,11 @@ SessionManager.resetSessionTimer();

/**
* Starts tracking the location of the user
* @method startTrackingLocation
* @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback
*/
* Starts tracking the location of the user
* @method startTrackingLocation
* @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback
*/
startTrackingLocation: function(callback) {
if (!Validators.isFunction(callback)) {
mParticle.Logger.warning('Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.');
mParticle.Logger.warning(
'Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.'
);
}

@@ -231,7 +248,7 @@

/**
* Sets the position of the user
* @method setPosition
* @param {Number} lattitude lattitude digit
* @param {Number} longitude longitude digit
*/
* Sets the position of the user
* @method setPosition
* @param {Number} lattitude lattitude digit
* @param {Number} longitude longitude digit
*/
setPosition: function(lat, lng) {

@@ -242,13 +259,14 @@ SessionManager.resetSessionTimer();

lat: lat,
lng: lng
lng: lng,
};
} else {
mParticle.Logger.error(
'Position latitude and/or longitude must both be of type number'
);
}
else {
mParticle.Logger.error('Position latitude and/or longitude must both be of type number');
}
},
/**
* Starts a new session
* @method startNewSession
*/
* Starts a new session
* @method startNewSession
*/
startNewSession: function() {

@@ -258,5 +276,5 @@ SessionManager.startNewSession();

/**
* Ends the current session
* @method endSession
*/
* Ends the current session
* @method endSession
*/
endSession: function() {

@@ -271,5 +289,5 @@ // Sends true as an over ride vs when endSession is called from the setInterval

*/
logBaseEvent: function (event) {
logBaseEvent: function(event) {
SessionManager.resetSessionTimer();
if (typeof (event.name) !== 'string') {
if (typeof event.name !== 'string') {
mParticle.Logger.error(Messages.ErrorMessages.EventNameInvalidType);

@@ -291,12 +309,12 @@ return;

/**
* Logs an event to mParticle's servers
* @method logEvent
* @param {String} eventName The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* @param {Object} [customFlags] Additional customFlags
*/
* Logs an event to mParticle's servers
* @method logEvent
* @param {String} eventName The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* @param {Object} [customFlags] Additional customFlags
*/
logEvent: function(eventName, eventType, eventInfo, customFlags) {
SessionManager.resetSessionTimer();
if (typeof (eventName) !== 'string') {
if (typeof eventName !== 'string') {
mParticle.Logger.error(Messages.ErrorMessages.EventNameInvalidType);

@@ -311,3 +329,8 @@ return;

if (!Helpers.isEventType(eventType)) {
mParticle.Logger.error('Invalid event type: ' + eventType + ', must be one of: \n' + JSON.stringify(Types.EventType));
mParticle.Logger.error(
'Invalid event type: ' +
eventType +
', must be one of: \n' +
JSON.stringify(Types.EventType)
);
return;

@@ -326,12 +349,12 @@ }

eventType: eventType,
customFlags: customFlags
customFlags: customFlags,
});
},
/**
* Used to log custom errors
*
* @method logError
* @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'}
* @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean
*/
* Used to log custom errors
*
* @method logError
* @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'}
* @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean
*/
logError: function(error, attrs) {

@@ -345,3 +368,3 @@ SessionManager.resetSessionTimer();

error = {
message: error
message: error,
};

@@ -353,3 +376,3 @@ }

s: 'Error',
t: error.stack
t: error.stack,
};

@@ -368,36 +391,48 @@

data: data,
eventType: Types.EventType.Other
eventType: Types.EventType.Other,
});
},
/**
* Logs `click` events
* @method logLink
* @param {String} selector The selector to add a 'click' event to (ex. #purchase-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
* Logs `click` events
* @method logLink
* @param {String} selector The selector to add a 'click' event to (ex. #purchase-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
logLink: function(selector, eventName, eventType, eventInfo) {
SessionManager.resetSessionTimer();
Events.addEventHandler('click', selector, eventName, eventInfo, eventType);
Events.addEventHandler(
'click',
selector,
eventName,
eventInfo,
eventType
);
},
/**
* Logs `submit` events
* @method logForm
* @param {String} selector The selector to add the event handler to (ex. #search-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
* Logs `submit` events
* @method logForm
* @param {String} selector The selector to add the event handler to (ex. #search-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
logForm: function(selector, eventName, eventType, eventInfo) {
SessionManager.resetSessionTimer();
Events.addEventHandler('submit', selector, eventName, eventInfo, eventType);
Events.addEventHandler(
'submit',
selector,
eventName,
eventInfo,
eventType
);
},
/**
* Logs a page view
* @method logPageView
* @param {String} eventName The name of the event. Defaults to 'PageView'.
* @param {Object} [attrs] Attributes for the event
* @param {Object} [customFlags] Custom flags for the event
*/
* Logs a page view
* @method logPageView
* @param {String} eventName The name of the event. Defaults to 'PageView'.
* @param {Object} [attrs] Attributes for the event
* @param {Object} [customFlags] Custom flags for the event
*/
logPageView: function(eventName, attrs, customFlags) {

@@ -413,11 +448,18 @@ SessionManager.resetSessionTimer();

hostname: window.location.hostname,
title: window.document.title
title: window.document.title,
};
}
else if (!Helpers.isObject(attrs)){
mParticle.Logger.error('The attributes argument must be an object. A ' + typeof attrs + ' was entered. Please correct and retry.');
} else if (!Helpers.isObject(attrs)) {
mParticle.Logger.error(
'The attributes argument must be an object. A ' +
typeof attrs +
' was entered. Please correct and retry.'
);
return;
}
if (customFlags && !Helpers.isObject(customFlags)) {
mParticle.Logger.error('The customFlags argument must be an object. A ' + typeof customFlags + ' was entered. Please correct and retry.');
mParticle.Logger.error(
'The customFlags argument must be an object. A ' +
typeof customFlags +
' was entered. Please correct and retry.'
);
return;

@@ -432,3 +474,3 @@ }

eventType: Types.EventType.Unknown,
customFlags: customFlags
customFlags: customFlags,
});

@@ -438,22 +480,22 @@ },

createGDPRConsent: Consent.createGDPRConsent,
createConsentState: Consent.createConsentState
createConsentState: Consent.createConsentState,
},
/**
* Invoke these methods on the mParticle.eCommerce object.
* Example: mParticle.eCommerce.createImpresion(...)
* @class mParticle.eCommerce
*/
* Invoke these methods on the mParticle.eCommerce object.
* Example: mParticle.eCommerce.createImpresion(...)
* @class mParticle.eCommerce
*/
eCommerce: {
/**
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
*/
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
*/
Cart: {
/**
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
add: function(product, logEventBoolean) {

@@ -468,7 +510,7 @@ var mpid,

/**
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
remove: function(product, logEventBoolean) {

@@ -483,5 +525,5 @@ var mpid,

/**
* Clears the cart
* @method clear
*/
* Clears the cart
* @method clear
*/
clear: function() {

@@ -494,10 +536,10 @@ var mpid,

mParticleUserCart(mpid).clear();
}
},
},
/**
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/
setCurrencyCode: function(code) {

@@ -512,29 +554,51 @@ if (typeof code !== 'string') {

/**
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/
createProduct: function(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) {
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/
createProduct: function(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
coupon,
attributes
) {
SessionManager.resetSessionTimer();
return Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes);
return Ecommerce.createProduct(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
coupon,
attributes
);
},
/**
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/
createPromotion: function(id, creative, name, position) {

@@ -545,8 +609,8 @@ SessionManager.resetSessionTimer();

/**
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/
createImpression: function(name, product) {

@@ -557,25 +621,39 @@ SessionManager.resetSessionTimer();

/**
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/
createTransactionAttributes: function(id, affiliation, couponCode, revenue, shipping, tax) {
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/
createTransactionAttributes: function(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
) {
SessionManager.resetSessionTimer();
return Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax);
return Ecommerce.createTransactionAttributes(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
);
},
/**
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {Object} options
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
*/
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {Object} options
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
*/
logCheckout: function(step, options, attrs, customFlags) {

@@ -586,25 +664,41 @@ SessionManager.resetSessionTimer();

/**
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
*/
logProductAction: function(productActionType, product, attrs, customFlags) {
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
*/
logProductAction: function(
productActionType,
product,
attrs,
customFlags
) {
SessionManager.resetSessionTimer();
Events.logProductActionEvent(productActionType, product, attrs, customFlags);
Events.logProductActionEvent(
productActionType,
product,
attrs,
customFlags
);
},
/**
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
*/
logPurchase: function(transactionAttributes, product, clearCart, attrs, customFlags) {
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
*/
logPurchase: function(
transactionAttributes,
product,
clearCart,
attrs,
customFlags
) {
if (!transactionAttributes || !product) {

@@ -615,3 +709,8 @@ mParticle.Logger.error(Messages.ErrorMessages.BadLogPurchase);

SessionManager.resetSessionTimer();
Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags);
Events.logPurchaseEvent(
transactionAttributes,
product,
attrs,
customFlags
);

@@ -623,10 +722,10 @@ if (clearCart === true) {

/**
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
*/
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
*/
logPromotion: function(type, promotion, attrs, customFlags) {

@@ -637,9 +736,9 @@ SessionManager.resetSessionTimer();

/**
* Logs a product impression
* @for mParticle.eCommerce
* @method logImpression
* @param {Object} impression product impression object
* @param {Object} attrs attributes related to the impression log
* @param {Object} [customFlags] Custom flags for the event
*/
* Logs a product impression
* @for mParticle.eCommerce
* @method logImpression
* @param {Object} impression product impression object
* @param {Object} attrs attributes related to the impression log
* @param {Object} [customFlags] Custom flags for the event
*/
logImpression: function(impression, attrs, customFlags) {

@@ -650,14 +749,25 @@ SessionManager.resetSessionTimer();

/**
* Logs a refund
* @for mParticle.eCommerce
* @method logRefund
* @param {Object} transactionAttributes transaction attributes related to the refund
* @param {Object} product product being refunded
* @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
* @param {Object} [attrs] attributes related to the refund
* @param {Object} [customFlags] Custom flags for the event
*/
logRefund: function(transactionAttributes, product, clearCart, attrs, customFlags) {
* Logs a refund
* @for mParticle.eCommerce
* @method logRefund
* @param {Object} transactionAttributes transaction attributes related to the refund
* @param {Object} product product being refunded
* @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
* @param {Object} [attrs] attributes related to the refund
* @param {Object} [customFlags] Custom flags for the event
*/
logRefund: function(
transactionAttributes,
product,
clearCart,
attrs,
customFlags
) {
SessionManager.resetSessionTimer();
Events.logRefundEvent(transactionAttributes, product, attrs, customFlags);
Events.logRefundEvent(
transactionAttributes,
product,
attrs,
customFlags
);

@@ -671,11 +781,11 @@ if (clearCart === true) {

return Ecommerce.expandCommerceEvent(event);
}
},
},
/**
* Sets a session attribute
* @for mParticle
* @method setSessionAttribute
* @param {String} key key for session attribute
* @param {String or Number} value value for session attribute
*/
* Sets a session attribute
* @for mParticle
* @method setSessionAttribute
* @param {String} key key for session attribute
* @param {String or Number} value value for session attribute
*/
setSessionAttribute: function(key, value) {

@@ -698,5 +808,11 @@ SessionManager.resetSessionTimer();

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: key, value: value }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.SetSessionAttribute,
JSON.stringify({ key: key, value: value })
);
} else {
var existingProp = Helpers.findKeyInObject(mParticle.Store.sessionAttributes, key);
var existingProp = Helpers.findKeyInObject(
mParticle.Store.sessionAttributes,
key
);

@@ -710,3 +826,6 @@ if (existingProp) {

Forwarders.applyToForwarders('setSessionAttribute', [key, value]);
Forwarders.applyToForwarders('setSessionAttribute', [
key,
value,
]);
}

@@ -716,7 +835,7 @@ }

/**
* Set opt out of logging
* @for mParticle
* @method setOptOut
* @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging.
*/
* Set opt out of logging
* @for mParticle
* @method setOptOut
* @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging.
*/
setOptOut: function(isOptingOut) {

@@ -742,15 +861,15 @@ SessionManager.resetSessionTimer();

/**
* Set or remove the integration attributes for a given integration ID.
* Integration attributes are keys and values specific to a given integration. For example,
* many integrations have their own internal user/device ID. mParticle will store integration attributes
* for a given device, and will be able to use these values for server-to-server communication to services.
* This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched
* with the necessary integration attributes to be properly forwarded to the given integration.
* @for mParticle
* @method setIntegrationAttribute
* @param {Number} integrationId mParticle integration ID
* @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle.
* Please consult with the mParticle docs or your solutions consultant for the correct value. You may
* also pass a null or empty map here to remove all of the attributes.
*/
* Set or remove the integration attributes for a given integration ID.
* Integration attributes are keys and values specific to a given integration. For example,
* many integrations have their own internal user/device ID. mParticle will store integration attributes
* for a given device, and will be able to use these values for server-to-server communication to services.
* This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched
* with the necessary integration attributes to be properly forwarded to the given integration.
* @for mParticle
* @method setIntegrationAttribute
* @param {Number} integrationId mParticle integration ID
* @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle.
* Please consult with the mParticle docs or your solutions consultant for the correct value. You may
* also pass a null or empty map here to remove all of the attributes.
*/
setIntegrationAttribute: function(integrationId, attrs) {

@@ -770,14 +889,31 @@ if (typeof integrationId !== 'number') {

if (typeof attrs[key] === 'string') {
if (Helpers.isObject(mParticle.Store.integrationAttributes[integrationId])) {
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
if (
Helpers.isObject(
mParticle.Store.integrationAttributes[
integrationId
]
)
) {
mParticle.Store.integrationAttributes[
integrationId
][key] = attrs[key];
} else {
mParticle.Store.integrationAttributes[integrationId] = {};
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
mParticle.Store.integrationAttributes[
integrationId
] = {};
mParticle.Store.integrationAttributes[
integrationId
][key] = attrs[key];
}
} else {
mParticle.Logger.error('Values for integration attributes must be strings. You entered a ' + typeof attrs[key]);
mParticle.Logger.error(
'Values for integration attributes must be strings. You entered a ' +
typeof attrs[key]
);
continue;
}
} else {
mParticle.Logger.error('Keys must be strings, you entered a ' + typeof key);
mParticle.Logger.error(
'Keys must be strings, you entered a ' + typeof key
);
continue;

@@ -788,3 +924,6 @@ }

} else {
mParticle.Logger.error('Attrs must be an object with keys and values. You entered a ' + typeof attrs);
mParticle.Logger.error(
'Attrs must be an object with keys and values. You entered a ' +
typeof attrs
);
return;

@@ -795,7 +934,7 @@ }

/**
* Get integration attributes for a given integration ID.
* @method getIntegrationAttributes
* @param {Number} integrationId mParticle integration ID
* @return {Object} an object map of the integrationId's attributes
*/
* Get integration attributes for a given integration ID.
* @method getIntegrationAttributes
* @param {Number} integrationId mParticle integration ID
* @return {Object} an object map of the integrationId's attributes
*/
getIntegrationAttributes: function(integrationId) {

@@ -822,3 +961,3 @@ if (mParticle.Store.integrationAttributes[integrationId]) {

mParticle.preInit.integrationDelays[module] = boolean;
}
},
};

@@ -829,5 +968,11 @@

if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_env', value: 'webview' }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.SetSessionAttribute,
JSON.stringify({ key: '$src_env', value: 'webview' })
);
if (apiKey) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_key', value: apiKey }));
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.SetSessionAttribute,
JSON.stringify({ key: '$src_key', value: apiKey })
);
}

@@ -838,4 +983,12 @@ } else {

// If no initialIdentityRequest is passed in, we set the user identities to what is currently in cookies for the identify request
if ((Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest) && Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest.userIdentities) &&
Object.keys(mParticle.Store.SDKConfig.identifyRequest.userIdentities).length === 0) || !mParticle.Store.SDKConfig.identifyRequest) {
if (
(Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest) &&
Helpers.isObject(
mParticle.Store.SDKConfig.identifyRequest.userIdentities
) &&
Object.keys(
mParticle.Store.SDKConfig.identifyRequest.userIdentities
).length === 0) ||
!mParticle.Store.SDKConfig.identifyRequest
) {
var modifiedUIforIdentityRequest = {};

@@ -845,6 +998,8 @@

if (currentUser) {
var identities = currentUser.getUserIdentities().userIdentities || {};
var identities =
currentUser.getUserIdentities().userIdentities || {};
for (var identityKey in identities) {
if (identities.hasOwnProperty(identityKey)) {
modifiedUIforIdentityRequest[identityKey] = identities[identityKey];
modifiedUIforIdentityRequest[identityKey] =
identities[identityKey];
}

@@ -855,3 +1010,3 @@ }

mParticle.Store.SDKConfig.identifyRequest = {
userIdentities: modifiedUIforIdentityRequest
userIdentities: modifiedUIforIdentityRequest,
};

@@ -862,3 +1017,6 @@ }

if (mParticle.Store.migratingToIDSyncCookies) {
IdentityAPI.identify(mParticle.Store.SDKConfig.identifyRequest, mParticle.Store.SDKConfig.identityCallback);
IdentityAPI.identify(
mParticle.Store.SDKConfig.identifyRequest,
mParticle.Store.SDKConfig.identityCallback
);
mParticle.Store.migratingToIDSyncCookies = false;

@@ -876,12 +1034,21 @@ }

// Call mParticle.Store.SDKConfig.identityCallback when identify was not called due to a reload or a sessionId already existing
if (!mParticle.Store.identifyCalled && mParticle.Store.SDKConfig.identityCallback && currentUser && currentUser.getMPID()) {
if (
!mParticle.Store.identifyCalled &&
mParticle.Store.SDKConfig.identityCallback &&
currentUser &&
currentUser.getMPID()
) {
mParticle.Store.SDKConfig.identityCallback({
httpCode: HTTPCodes.activeSession,
getUser: function () {
getUser: function() {
return mParticleUser(currentUser.getMPID());
},
getPreviousUser: function () {
getPreviousUser: function() {
var users = mParticle.Identity.getUsers();
var mostRecentUser = users.shift();
if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) {
if (
mostRecentUser &&
currentUser &&
mostRecentUser.getMPID() === currentUser.getMPID()
) {
mostRecentUser = users.shift();

@@ -894,6 +1061,7 @@ }

is_logged_in: mParticle.Store.isLoggedIn,
matched_identities: currentUser.getUserIdentities().userIdentities,
matched_identities: currentUser.getUserIdentities()
.userIdentities,
context: null,
is_ephemeral: false
}
is_ephemeral: false,
},
});

@@ -907,3 +1075,3 @@ }

if (mParticle.preInit.readyQueue && mParticle.preInit.readyQueue.length) {
mParticle.preInit.readyQueue.forEach(function (readyQueueItem) {
mParticle.preInit.readyQueue.forEach(function(readyQueueItem) {
if (Validators.isFunction(readyQueueItem)) {

@@ -915,3 +1083,3 @@ readyQueueItem();

});
mParticle.preInit.readyQueue = [];

@@ -930,13 +1098,20 @@ }

mParticle.Store.devToken = apiKey || null;
mParticle.Logger.verbose(Messages.InformationMessages.StartingInitialization);
mParticle.Logger.verbose(
Messages.InformationMessages.StartingInitialization
);
//check to see if localStorage is available for migrating purposes
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
mParticle.Store.webviewBridgeEnabled = NativeSdkHelpers.isWebviewEnabled(mParticle.Store.SDKConfig.requiredWebviewBridgeName, mParticle.Store.SDKConfig.minWebviewBridgeVersion);
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(
window.localStorage
);
mParticle.Store.webviewBridgeEnabled = NativeSdkHelpers.isWebviewEnabled(
mParticle.Store.SDKConfig.requiredWebviewBridgeName,
mParticle.Store.SDKConfig.minWebviewBridgeVersion
);
if (!mParticle.Store.webviewBridgeEnabled) {
// Migrate any cookies from previous versions to current cookie version
Migrations.migrate();
// Load any settings/identities/attributes from cookie or localStorage

@@ -962,4 +1137,6 @@ Persistence.initializeStorage();

computedMPFunction.apply(currentUser, args);
} catch(e) {
mParticle.Logger.verbose('Unable to compute proper mParticle function ' + e);
} catch (e) {
mParticle.Logger.verbose(
'Unable to compute proper mParticle function ' + e
);
}

@@ -972,3 +1149,3 @@ }

integrationDelays: {},
forwarderConstructors: []
forwarderConstructors: [],
};

@@ -984,2 +1161,2 @@

export default mParticle;
export default mParticle;

@@ -9,6 +9,6 @@ import Persistence from './persistence';

CookiesGlobalSettingsKeys = {
das: 1
das: 1,
},
MPIDKeys = {
ui: 1
ui: 1,
};

@@ -49,3 +49,5 @@

mParticle.Logger.verbose(Constants.Messages.InformationMessages.CookieSearch);
mParticle.Logger.verbose(
Constants.Messages.InformationMessages.CookieSearch
);

@@ -55,4 +57,3 @@ for (i = 0, l = cookies.length; i < l; i++) {

name = Helpers.decoded(parts.shift());
cookie = Helpers.decoded(parts.join('=')),
foundCookie;
cookie = Helpers.decoded(parts.join('='));

@@ -70,3 +71,3 @@ //most recent version needs no migration

return;
// migration path for SDKv1CookiesV3, doesn't need to be encoded
// migration path for SDKv1CookiesV3, doesn't need to be encoded
}

@@ -87,4 +88,5 @@ if (name === StorageNames.cookieNameV3) {

expires = new Date(date.getTime() +
(StorageNames.CookieExpiration * 24 * 60 * 60 * 1000)).toGMTString();
expires = new Date(
date.getTime() + StorageNames.CookieExpiration * 24 * 60 * 60 * 1000
).toGMTString();

@@ -100,5 +102,9 @@ if (cookieDomain === '') {

window.document.cookie =
encodeURIComponent(mParticle.Store.storageName) + '=' + cookie +
';expires=' + expires +
';path=/' + domain;
encodeURIComponent(mParticle.Store.storageName) +
'=' +
cookie +
';expires=' +
expires +
';path=/' +
domain;

@@ -110,3 +116,5 @@ Persistence.expireCookies(cookieName);

function convertSDKv1CookiesV3ToSDKv2CookiesV4(SDKv1CookiesV3) {
SDKv1CookiesV3 = Persistence.replacePipesWithCommas(Persistence.replaceApostrophesWithQuotes(SDKv1CookiesV3));
SDKv1CookiesV3 = Persistence.replacePipesWithCommas(
Persistence.replaceApostrophesWithQuotes(SDKv1CookiesV3)
);
var parsedSDKv1CookiesV3 = JSON.parse(SDKv1CookiesV3);

@@ -118,4 +126,9 @@ var parsedCookiesV4 = JSON.parse(restructureToV4Cookie(SDKv1CookiesV3));

// all other values are already encoded, so we have to encode any new values
parsedCookiesV4.gs.csm = Base64.encode(JSON.stringify(parsedCookiesV4.gs.csm));
migrateProductsFromSDKv1ToSDKv2CookiesV4(parsedSDKv1CookiesV3, parsedSDKv1CookiesV3.mpid);
parsedCookiesV4.gs.csm = Base64.encode(
JSON.stringify(parsedCookiesV4.gs.csm)
);
migrateProductsFromSDKv1ToSDKv2CookiesV4(
parsedSDKv1CookiesV3,
parsedSDKv1CookiesV3.mpid
);
}

@@ -128,3 +141,3 @@

try {
var cookiesV4Schema = { gs: {csm: []} };
var cookiesV4Schema = { gs: { csm: [] } };
cookies = JSON.parse(cookies);

@@ -139,3 +152,4 @@

} else if (cookies.mpid) {
cookiesV4Schema[cookies.mpid] = cookiesV4Schema[cookies.mpid] || {};
cookiesV4Schema[cookies.mpid] =
cookiesV4Schema[cookies.mpid] || {};
if (MPIDKeys[key]) {

@@ -148,6 +162,7 @@ cookiesV4Schema[cookies.mpid][key] = cookies[key];

return JSON.stringify(cookiesV4Schema);
} catch (e) {
mParticle.Logger.error(
'Failed to restructure previous cookie into most current cookie schema'
);
}
catch (e) {
mParticle.Logger.error('Failed to restructure previous cookie into most current cookie schema');
}
}

@@ -171,5 +186,6 @@

try {
localStorageProducts[mpid].cp = JSON.parse(Base64.decode(cookies.cp));
}
catch (e) {
localStorageProducts[mpid].cp = JSON.parse(
Base64.decode(cookies.cp)
);
} catch (e) {
localStorageProducts[mpid].cp = cookies.cp;

@@ -183,3 +199,6 @@ }

localStorage.setItem(mParticle.Store.prodStorageName, Base64.encode(JSON.stringify(localStorageProducts)));
localStorage.setItem(
mParticle.Store.prodStorageName,
Base64.encode(JSON.stringify(localStorageProducts))
);
}

@@ -191,3 +210,5 @@

v4LSName = StorageNames.localStorageNameV4,
currentVersionLSData = window.localStorage.getItem(mParticle.Store.storageName),
currentVersionLSData = window.localStorage.getItem(
mParticle.Store.storageName
),
v4LSData,

@@ -212,10 +233,16 @@ v3LSData,

v3LSDataStringCopy = v3LSData.slice();
v3LSData = JSON.parse(Persistence.replacePipesWithCommas(Persistence.replaceApostrophesWithQuotes(v3LSData)));
v3LSData = JSON.parse(
Persistence.replacePipesWithCommas(
Persistence.replaceApostrophesWithQuotes(v3LSData)
)
);
// localStorage may contain only products, or the full persistence
// when there is an MPID on the cookie, it is the full persistence
if (v3LSData.mpid) {
v3LSData = JSON.parse(convertSDKv1CookiesV3ToSDKv2CookiesV4(v3LSDataStringCopy));
v3LSData = JSON.parse(
convertSDKv1CookiesV3ToSDKv2CookiesV4(v3LSDataStringCopy)
);
finishLSMigration(JSON.stringify(v3LSData), v3LSName);
return;
// if no MPID, it is only the products
// if no MPID, it is only the products
} else if ((v3LSData.cp || v3LSData.pb) && !v3LSData.mpid) {

@@ -236,5 +263,7 @@ cookies = Persistence.getCookie();

try {
window.localStorage.setItem(encodeURIComponent(mParticle.Store.storageName), data);
}
catch (e) {
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.storageName),
data
);
} catch (e) {
mParticle.Logger.error('Error with setting localStorage item.');

@@ -248,3 +277,3 @@ }

migrate: migrate,
convertSDKv1CookiesV3ToSDKv2CookiesV4: convertSDKv1CookiesV3ToSDKv2CookiesV4
};
convertSDKv1CookiesV3ToSDKv2CookiesV4: convertSDKv1CookiesV3ToSDKv2CookiesV4,
};

@@ -16,3 +16,7 @@ import Constants from './constants';

// iOS v2 bridge
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)) {
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)
) {
return true;

@@ -32,3 +36,5 @@ }

function isWebviewEnabled(requiredWebviewBridgeName, minWebviewBridgeVersion) {
mParticle.Store.bridgeV2Available = isBridgeV2Available(requiredWebviewBridgeName);
mParticle.Store.bridgeV2Available = isBridgeV2Available(
requiredWebviewBridgeName
);
mParticle.Store.bridgeV1Available = isBridgeV1Available();

@@ -41,3 +47,7 @@

// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== (iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2')) {
if (
window.mParticle.uiwebviewBridgeName &&
window.mParticle.uiwebviewBridgeName !==
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2'
) {
return false;

@@ -48,3 +58,6 @@ }

// ios
return mParticle.Store.bridgeV2Available || mParticle.Store.bridgeV1Available;
return (
mParticle.Store.bridgeV2Available ||
mParticle.Store.bridgeV1Available
);
}

@@ -56,4 +69,7 @@

function isBridgeV1Available() {
if (mParticle.Store.SDKConfig.useNativeSdk || window.mParticleAndroid
|| mParticle.Store.SDKConfig.isIOS) {
if (
mParticle.Store.SDKConfig.useNativeSdk ||
window.mParticleAndroid ||
mParticle.Store.SDKConfig.isIOS
) {
return true;

@@ -66,11 +82,28 @@ }

function sendToNative(path, value) {
if (mParticle.Store.bridgeV2Available && mParticle.Store.SDKConfig.minWebviewBridgeVersion === 2) {
sendViaBridgeV2(path, value, mParticle.Store.SDKConfig.requiredWebviewBridgeName);
if (
mParticle.Store.bridgeV2Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion === 2
) {
sendViaBridgeV2(
path,
value,
mParticle.Store.SDKConfig.requiredWebviewBridgeName
);
return;
}
if (mParticle.Store.bridgeV2Available && mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2) {
sendViaBridgeV2(path, value, mParticle.Store.SDKConfig.requiredWebviewBridgeName);
if (
mParticle.Store.bridgeV2Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2
) {
sendViaBridgeV2(
path,
value,
mParticle.Store.SDKConfig.requiredWebviewBridgeName
);
return;
}
if (mParticle.Store.bridgeV1Available && mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2) {
if (
mParticle.Store.bridgeV1Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2
) {
sendViaBridgeV1(path, value);

@@ -82,7 +115,11 @@ return;

function sendViaBridgeV1(path, value) {
if (window.mParticleAndroid && window.mParticleAndroid.hasOwnProperty(path)) {
mParticle.Logger.verbose(Messages.InformationMessages.SendAndroid + path);
if (
window.mParticleAndroid &&
window.mParticleAndroid.hasOwnProperty(path)
) {
mParticle.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
window.mParticleAndroid[path](value);
}
else if (mParticle.Store.SDKConfig.isIOS) {
} else if (mParticle.Store.SDKConfig.isIOS) {
mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);

@@ -95,6 +132,8 @@ sendViaIframeToIOS(path, value);

var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'mp-sdk://' + path + '/' + encodeURIComponent(value));
iframe.setAttribute(
'src',
'mp-sdk://' + path + '/' + encodeURIComponent(value)
);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}

@@ -107,9 +146,15 @@

var androidBridgeName = androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
var androidBridgeName =
androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
androidBridge = window[androidBridgeName],
iosBridgeName = iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
iosBridgeName =
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
iOSBridgeMessageHandler,
iOSBridgeNonMessageHandler;
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers[iosBridgeName]) {
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers[iosBridgeName]
) {
iOSBridgeMessageHandler = window.webkit.messageHandlers[iosBridgeName];

@@ -123,3 +168,5 @@ }

if (androidBridge && androidBridge.hasOwnProperty(path)) {
mParticle.Logger.verbose(Messages.InformationMessages.SendAndroid + path);
mParticle.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
androidBridge[path](value);

@@ -129,3 +176,8 @@ return;

mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);
iOSBridgeMessageHandler.postMessage(JSON.stringify({path:path, value: value ? JSON.parse(value) : null}));
iOSBridgeMessageHandler.postMessage(
JSON.stringify({
path: path,
value: value ? JSON.parse(value) : null,
})
);
} else if (iOSBridgeNonMessageHandler) {

@@ -140,3 +192,3 @@ mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);

isBridgeV2Available: isBridgeV2Available,
sendToNative: sendToNative
};
sendToNative: sendToNative,
};

@@ -12,5 +12,7 @@ import Helpers from './helpers';

function useLocalStorage() {
return (!mParticle.Store.SDKConfig.useCookieStorage && mParticle.Store.isLocalStorageAvailable);
return (
!mParticle.Store.SDKConfig.useCookieStorage &&
mParticle.Store.isLocalStorageAvailable
);
}

@@ -44,3 +46,7 @@

if (cookies) {
allData = Helpers.extend(false, localStorageData, cookies);
allData = Helpers.extend(
false,
localStorageData,
cookies
);
} else {

@@ -54,4 +60,3 @@ allData = localStorageData;

storeDataInMemory(allData);
}
else {
} else {
// For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then

@@ -61,3 +66,7 @@ // no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies.

if (localStorageData) {
allData = Helpers.extend(false, localStorageData, cookies);
allData = Helpers.extend(
false,
localStorageData,
cookies
);
} else {

@@ -78,9 +87,16 @@ allData = cookies;

if (mParticle.Store.isLocalStorageAvailable) {
var encodedProducts = localStorage.getItem(mParticle.Store.prodStorageName);
var encodedProducts = localStorage.getItem(
mParticle.Store.prodStorageName
);
if (encodedProducts) {
var decodedProducts = JSON.parse(Base64.decode(encodedProducts));
var decodedProducts = JSON.parse(
Base64.decode(encodedProducts)
);
}
if (mParticle.Store.mpid) {
storeProductsInMemory(decodedProducts, mParticle.Store.mpid);
storeProductsInMemory(
decodedProducts,
mParticle.Store.mpid
);
}

@@ -93,6 +109,7 @@ }

mParticle.Store.cartProducts = [];
mParticle.Logger.error('Error loading products in initialization: ' + e);
mParticle.Logger.error(
'Error loading products in initialization: ' + e
);
}
for (var key in allData) {

@@ -129,5 +146,5 @@ if (allData.hasOwnProperty(key)) {

try {
mParticle.Store.cartProducts = products[mpid] && products[mpid].cp ? products[mpid].cp : [];
}
catch(e) {
mParticle.Store.cartProducts =
products[mpid] && products[mpid].cp ? products[mpid].cp : [];
} catch (e) {
mParticle.Logger.error(Messages.ErrorMessages.CookieParseError);

@@ -141,5 +158,9 @@ }

if (!obj) {
mParticle.Logger.verbose(Messages.InformationMessages.CookieNotFound);
mParticle.Store.clientId = mParticle.Store.clientId || Helpers.generateUniqueId();
mParticle.Store.deviceId = mParticle.Store.deviceId || Helpers.generateUniqueId();
mParticle.Logger.verbose(
Messages.InformationMessages.CookieNotFound
);
mParticle.Store.clientId =
mParticle.Store.clientId || Helpers.generateUniqueId();
mParticle.Store.deviceId =
mParticle.Store.deviceId || Helpers.generateUniqueId();
} else {

@@ -156,12 +177,25 @@ // Set MPID first, then change object to match MPID data

mParticle.Store.sessionId = obj.gs.sid || mParticle.Store.sessionId;
mParticle.Store.isEnabled = (typeof obj.gs.ie !== 'undefined') ? obj.gs.ie : mParticle.Store.isEnabled;
mParticle.Store.sessionAttributes = obj.gs.sa || mParticle.Store.sessionAttributes;
mParticle.Store.serverSettings = obj.gs.ss || mParticle.Store.serverSettings;
mParticle.Store.isEnabled =
typeof obj.gs.ie !== 'undefined'
? obj.gs.ie
: mParticle.Store.isEnabled;
mParticle.Store.sessionAttributes =
obj.gs.sa || mParticle.Store.sessionAttributes;
mParticle.Store.serverSettings =
obj.gs.ss || mParticle.Store.serverSettings;
mParticle.Store.devToken = mParticle.Store.devToken || obj.gs.dt;
mParticle.Store.SDKConfig.appVersion = mParticle.Store.SDKConfig.appVersion || obj.gs.av;
mParticle.Store.clientId = obj.gs.cgid || mParticle.Store.clientId || Helpers.generateUniqueId();
mParticle.Store.deviceId = obj.gs.das || mParticle.Store.deviceId || Helpers.generateUniqueId();
mParticle.Store.SDKConfig.appVersion =
mParticle.Store.SDKConfig.appVersion || obj.gs.av;
mParticle.Store.clientId =
obj.gs.cgid ||
mParticle.Store.clientId ||
Helpers.generateUniqueId();
mParticle.Store.deviceId =
obj.gs.das ||
mParticle.Store.deviceId ||
Helpers.generateUniqueId();
mParticle.Store.integrationAttributes = obj.gs.ia || {};
mParticle.Store.context = obj.gs.c || mParticle.Store.context;
mParticle.Store.currentSessionMPIDs = obj.gs.csm || mParticle.Store.currentSessionMPIDs;
mParticle.Store.currentSessionMPIDs =
obj.gs.csm || mParticle.Store.currentSessionMPIDs;

@@ -186,4 +220,3 @@ mParticle.Store.isLoggedIn = obj.l === true;

}
}
catch (e) {
} catch (e) {
mParticle.Logger.error(Messages.ErrorMessages.CookieParseError);

@@ -205,4 +238,3 @@ }

return result && storage;
}
catch (e) {
} catch (e) {
return false;

@@ -230,3 +262,8 @@ }

}
if (decodedProducts && parsedProducts[mpid] && parsedProducts[mpid].cp && Array.isArray(parsedProducts[mpid].cp)) {
if (
decodedProducts &&
parsedProducts[mpid] &&
parsedProducts[mpid].cp &&
Array.isArray(parsedProducts[mpid].cp)
) {
userProducts = parsedProducts[mpid].cp;

@@ -273,3 +310,5 @@ } else {

currentUserProducts = {
cp: allLocalStorageProducts[mpid] ? allLocalStorageProducts[mpid].cp : []
cp: allLocalStorageProducts[mpid]
? allLocalStorageProducts[mpid].cp
: [],
};

@@ -280,7 +319,11 @@ if (mpid) {

try {
window.localStorage.setItem(encodeURIComponent(mParticle.Store.prodStorageName), Base64.encode(JSON.stringify(allLocalStorageProducts)));
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.prodStorageName),
Base64.encode(JSON.stringify(allLocalStorageProducts))
);
} catch (e) {
mParticle.Logger.error(
'Error with setting products on localStorage.'
);
}
catch (e) {
mParticle.Logger.error('Error with setting products on localStorage.');
}
}

@@ -304,3 +347,7 @@

if (Object.keys(mParticle.Store.nonCurrentUserMPIDs).length) {
localStorageData = Helpers.extend({}, localStorageData, mParticle.Store.nonCurrentUserMPIDs);
localStorageData = Helpers.extend(
{},
localStorageData,
mParticle.Store.nonCurrentUserMPIDs
);
mParticle.Store.nonCurrentUserMPIDs = {};

@@ -312,5 +359,7 @@ }

try {
window.localStorage.setItem(encodeURIComponent(key), encodeCookies(JSON.stringify(localStorageData)));
}
catch (e) {
window.localStorage.setItem(
encodeURIComponent(key),
encodeCookies(JSON.stringify(localStorageData))
);
} catch (e) {
mParticle.Logger.error('Error with setting localStorage item.');

@@ -328,3 +377,5 @@ }

data.gs.dt = store.devToken;
data.gs.les = store.dateLastEventSent ? store.dateLastEventSent.getTime() : null;
data.gs.les = store.dateLastEventSent
? store.dateLastEventSent.getTime()
: null;
data.gs.av = store.SDKConfig.appVersion;

@@ -334,3 +385,5 @@ data.gs.cgid = store.clientId;

data.gs.c = store.context;
data.gs.ssd = store.sessionStartDate ? store.sessionStartDate.getTime() : null;
data.gs.ssd = store.sessionStartDate
? store.sessionStartDate.getTime()
: null;
data.gs.ia = store.integrationAttributes;

@@ -395,4 +448,3 @@

return Helpers.generateUniqueId();
}
catch (e) {
} catch (e) {
return Helpers.generateUniqueId();

@@ -416,3 +468,3 @@ }

date.setTime(date.getTime() - (24 * 60 * 60 * 1000));
date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toUTCString();

@@ -466,4 +518,6 @@ document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain;

cookies = getCookie() || {},
expires = new Date(date.getTime() +
(mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000)).toGMTString(),
expires = new Date(
date.getTime() +
mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000
).toGMTString(),
cookieDomain,

@@ -496,7 +550,16 @@ domain,

if (Object.keys(mParticle.Store.nonCurrentUserMPIDs).length) {
cookies = Helpers.extend({}, cookies, mParticle.Store.nonCurrentUserMPIDs);
cookies = Helpers.extend(
{},
cookies,
mParticle.Store.nonCurrentUserMPIDs
);
mParticle.Store.nonCurrentUserMPIDs = {};
}
encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(cookies, expires, domain, mParticle.Store.SDKConfig.maxCookieSize);
encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(
cookies,
expires,
domain,
mParticle.Store.SDKConfig.maxCookieSize
);

@@ -528,4 +591,10 @@ mParticle.Logger.verbose(Messages.InformationMessages.CookieSet);

if (cookies.hasOwnProperty(key)) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(cookies, expires, domain);
if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (
encodedCookiesWithExpirationAndPath.length > maxCookieSize
) {
if (!SDKv2NonMPIDCookieKeys[key] && key !== cookies.cu) {

@@ -542,3 +611,6 @@ delete cookies[key];

if (cookies.hasOwnProperty(potentialMPID)) {
if (!SDKv2NonMPIDCookieKeys[potentialMPID] && potentialMPID !==cookies.cu) {
if (
!SDKv2NonMPIDCookieKeys[potentialMPID] &&
potentialMPID !== cookies.cu
) {
MPIDsOnCookie[potentialMPID] = 1;

@@ -551,4 +623,10 @@ }

for (var mpid in MPIDsOnCookie) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(cookies, expires, domain);
if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (
encodedCookiesWithExpirationAndPath.length > maxCookieSize
) {
if (MPIDsOnCookie.hasOwnProperty(mpid)) {

@@ -564,10 +642,23 @@ if (currentSessionMPIDs.indexOf(mpid) === -1) {

for (var i = 0; i < currentSessionMPIDs.length; i++) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(cookies, expires, domain);
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) {
var MPIDtoRemove = currentSessionMPIDs[i];
if (cookies[MPIDtoRemove]) {
mParticle.Logger.verbose('Size of new encoded cookie is larger than maxCookieSize setting of ' + maxCookieSize + '. Removing from cookie the earliest logged in MPID containing: ' + JSON.stringify(cookies[MPIDtoRemove], 0, 2));
mParticle.Logger.verbose(
'Size of new encoded cookie is larger than maxCookieSize setting of ' +
maxCookieSize +
'. Removing from cookie the earliest logged in MPID containing: ' +
JSON.stringify(cookies[MPIDtoRemove], 0, 2)
);
delete cookies[MPIDtoRemove];
} else {
mParticle.Logger.error('Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' + maxCookieSize + '. We recommend using a maxCookieSize of 1500.');
mParticle.Logger.error(
'Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' +
maxCookieSize +
'. We recommend using a maxCookieSize of 1500.'
);
}

@@ -584,3 +675,9 @@ } else {

function createFullEncodedCookie(cookies, expires, domain) {
return encodeCookies(JSON.stringify(cookies)) + ';expires=' + expires +';path=/' + domain;
return (
encodeCookies(JSON.stringify(cookies)) +
';expires=' +
expires +
';path=/' +
domain
);
}

@@ -601,4 +698,8 @@

for (var cookieUIType in cookieUIs) {
if (requestedIdentityType === cookieUIType
&& identityApiData.userIdentities[requestedIdentityType] === cookieUIs[cookieUIType]) {
if (
requestedIdentityType === cookieUIType &&
identityApiData.userIdentities[
requestedIdentityType
] === cookieUIs[cookieUIType]
) {
matchedUser = key;

@@ -623,9 +724,14 @@ break;

if (cookie.gs.hasOwnProperty(key)) {
// base64 encode any value that is an object or Array in globalSettings first
if (Base64CookieKeys[key]) {
if (cookie.gs[key]) {
if (Array.isArray(cookie.gs[key]) && cookie.gs[key].length) {
cookie.gs[key] = Base64.encode(JSON.stringify(cookie.gs[key]));
} else if (Helpers.isObject(cookie.gs[key]) && Object.keys(cookie.gs[key]).length) {
cookie.gs[key] = Base64.encode(JSON.stringify(cookie.gs[key]));
// base64 encode any value that is an object or Array in globalSettings
if (
(Array.isArray(cookie.gs[key]) &&
cookie.gs[key].length) ||
(Helpers.isObject(cookie.gs[key]) &&
Object.keys(cookie.gs[key]).length)
) {
cookie.gs[key] = Base64.encode(
JSON.stringify(cookie.gs[key])
);
} else {

@@ -651,4 +757,9 @@ delete cookie.gs[key];

if (Base64CookieKeys[key]) {
if (Helpers.isObject(cookie[mpid][key]) && Object.keys(cookie[mpid][key]).length) {
cookie[mpid][key] = Base64.encode(JSON.stringify(cookie[mpid][key]));
if (
Helpers.isObject(cookie[mpid][key]) &&
Object.keys(cookie[mpid][key]).length
) {
cookie[mpid][key] = Base64.encode(
JSON.stringify(cookie[mpid][key])
);
} else {

@@ -675,3 +786,5 @@ delete cookie[mpid][key];

if (Base64CookieKeys[key]) {
cookie.gs[key] = JSON.parse(Base64.decode(cookie.gs[key]));
cookie.gs[key] = JSON.parse(
Base64.decode(cookie.gs[key])
);
} else if (key === 'ie') {

@@ -690,3 +803,5 @@ cookie.gs[key] = Boolean(cookie.gs[key]);

if (cookie[mpid][key].length) {
cookie[mpid][key] = JSON.parse(Base64.decode(cookie[mpid][key]));
cookie[mpid][key] = JSON.parse(
Base64.decode(cookie[mpid][key])
);
}

@@ -723,3 +838,3 @@ }

function replaceQuotesWithApostrophes(string) {
return string.replace(/\"/g, '\'');
return string.replace(/\"/g, "'");
}

@@ -761,4 +876,8 @@

doc.cookie = mpTest + ';domain=.' + testParts + ';';
if (doc.cookie.indexOf(mpTest) > -1){
doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
if (doc.cookie.indexOf(mpTest) > -1) {
doc.cookie =
mpTest.split('=')[0] +
'=;domain=.' +
testParts +
';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
return testParts;

@@ -792,6 +911,12 @@ }

var allCartProducts,
cartProductsString = localStorage.getItem(mParticle.Store.prodStorageName);
cartProductsString = localStorage.getItem(
mParticle.Store.prodStorageName
);
if (cartProductsString) {
allCartProducts = JSON.parse(Base64.decode(cartProductsString));
if (allCartProducts && allCartProducts[mpid] && allCartProducts[mpid].cp) {
if (
allCartProducts &&
allCartProducts[mpid] &&
allCartProducts[mpid].cp
) {
return allCartProducts[mpid].cp;

@@ -810,5 +935,7 @@ }

try {
window.localStorage.setItem(encodeURIComponent(mParticle.Store.prodStorageName), Base64.encode(JSON.stringify(allProducts)));
}
catch (e) {
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.prodStorageName),
Base64.encode(JSON.stringify(allProducts))
);
} catch (e) {
mParticle.Logger.error('Error with setting products on localStorage.');

@@ -825,3 +952,3 @@ }

cookies[mpid] = {
ui: userIdentities
ui: userIdentities,
};

@@ -842,3 +969,3 @@ }

cookies[mpid] = {
ui: userAttributes
ui: userAttributes,
};

@@ -859,3 +986,3 @@ }

cookies[mpid] = {
csd: csd
csd: csd,
};

@@ -869,4 +996,4 @@ }

function saveUserConsentStateToCookies(mpid, consentState) {
//it's currently not supported to set persistence
//for any MPID that's not the current one.
//it's currently not supported to set persistence
//for any MPID that's not the current one.
if (consentState || consentState === null) {

@@ -876,6 +1003,10 @@ var cookies = getPersistence();

if (cookies[mpid]) {
cookies[mpid].con = Consent.Serialization.toMinifiedJsonObject(consentState);
cookies[mpid].con = Consent.Serialization.toMinifiedJsonObject(
consentState
);
} else {
cookies[mpid] = {
con: Consent.Serialization.toMinifiedJsonObject(consentState)
con: Consent.Serialization.toMinifiedJsonObject(
consentState
),
};

@@ -892,4 +1023,6 @@ }

key = mParticle.Store.storageName,
expires = new Date(date.getTime() +
(mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000)).toGMTString(),
expires = new Date(
date.getTime() +
mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000
).toGMTString(),
cookieDomain = getCookieDomain(),

@@ -905,3 +1038,8 @@ domain;

if (mParticle.Store.SDKConfig.useCookieStorage) {
var encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(cookies, expires, domain, mParticle.Store.SDKConfig.maxCookieSize);
var encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(
cookies,
expires,
domain,
mParticle.Store.SDKConfig.maxCookieSize
);
window.document.cookie =

@@ -950,5 +1088,5 @@ encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath;

/**
* set the "first seen" time for a user. the time will only be set once for a given
* mpid after which subsequent calls will be ignored
*/
* set the "first seen" time for a user. the time will only be set once for a given
* mpid after which subsequent calls will be ignored
*/
function setFirstSeenTime(mpid, time) {

@@ -974,6 +1112,6 @@ if (!mpid) {

/**
* returns the "last seen" time for a user. If the mpid represents the current user, the
* return value will always be the current time, otherwise it will be to stored "last seen"
* time
*/
* returns the "last seen" time for a user. If the mpid represents the current user, the
* return value will always be the current time, otherwise it will be to stored "last seen"
* time
*/
function getLastSeenTime(mpid) {

@@ -1028,3 +1166,5 @@ if (!mpid) {

expireCookies(Helpers.createMainStorageName(testWorkspaceToken));
removeLocalStorage(Helpers.createProductStorageName(testWorkspaceToken));
removeLocalStorage(
Helpers.createProductStorageName(testWorkspaceToken)
);
}

@@ -1036,3 +1176,3 @@ }

uploadsTable: {},
forwardingStatsEventQueue: []
forwardingStatsEventQueue: [],
};

@@ -1082,3 +1222,3 @@

setFirstSeenTime: setFirstSeenTime,
setLastSeenTime: setLastSeenTime
};
setLastSeenTime: setLastSeenTime,
};
// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html
var Base64 = {
_keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
_keyStr:
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',

@@ -30,4 +31,4 @@ // Input must be a string

enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;

@@ -41,3 +42,8 @@

output = output + Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) + Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
output =
output +
Base64._keyStr.charAt(enc1) +
Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) +
Base64._keyStr.charAt(enc4);
}

@@ -72,5 +78,5 @@ return output;

chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;

@@ -88,3 +94,3 @@ output = output + String.fromCharCode(chr1);

return output;
}
},
};

@@ -102,8 +108,8 @@

} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode(c >> 6 | 192);
utftext += String.fromCharCode(c & 63 | 128);
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode(c >> 12 | 224);
utftext += String.fromCharCode(c >> 6 & 63 | 128);
utftext += String.fromCharCode(c & 63 | 128);
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}

@@ -128,3 +134,3 @@ }

c1 = utftext.charCodeAt(i + 1);
s += String.fromCharCode((c & 31) << 6 | c1 & 63);
s += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;

@@ -134,3 +140,5 @@ } else {

c2 = utftext.charCodeAt(i + 2);
s += String.fromCharCode((c & 15) << 12 | (c1 & 63) << 6 | c2 & 63);
s += String.fromCharCode(
((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63)
);
i += 3;

@@ -140,3 +148,3 @@ }

return s;
}
},
};

@@ -219,3 +227,3 @@

// Reference: http://es5.github.io/#x15.4.4.20
filter: function(fun/*, thisArg*/) {
filter: function(fun /*, thisArg*/) {
'use strict';

@@ -252,3 +260,3 @@

Base64: Base64
};
Base64: Base64,
};

@@ -6,4 +6,4 @@ export interface SDKEvent {

EventCategory: number;
UserAttributes?: { [key: string]: string | string[] | null};
UserIdentities?: SDKUserIdentity [];
UserAttributes?: { [key: string]: string | string[] | null };
UserIdentities?: SDKUserIdentity[];
MPID: string;

@@ -33,7 +33,7 @@ EventAttributes?: { [key: string]: string };

export interface SDKUserIdentity {
Identity?: string,
Type: number
Identity?: string;
Type: number;
}
export interface SDKShoppingCart {
ProductList?: SDKProduct[]
ProductList?: SDKProduct[];
}

@@ -46,11 +46,11 @@ export interface SDKPromotionAction {

export interface SDKPromotion {
Id?: string,
Name?: string,
Creative?: string,
Position?: string
Id?: string;
Name?: string;
Creative?: string;
Position?: string;
}
export interface SDKProductImpression {
ProductImpressionList?: string,
ProductList?: SDKProduct[]
ProductImpressionList?: string;
ProductList?: SDKProduct[];
}

@@ -69,29 +69,29 @@

AddToWishlist = 9,
RemoveFromWishlist = 10
RemoveFromWishlist = 10,
}
export interface SDKProductAction {
ProductActionType: SDKProductActionType,
CheckoutStep?: number,
CheckoutOptions?: string,
ProductList?: SDKProduct[],
TransactionId?: string,
Affiliation?: string,
CouponCode?: string,
TotalAmount?: number,
ShippingAmount?: number,
TaxAmount?: number
ProductActionType: SDKProductActionType;
CheckoutStep?: number;
CheckoutOptions?: string;
ProductList?: SDKProduct[];
TransactionId?: string;
Affiliation?: string;
CouponCode?: string;
TotalAmount?: number;
ShippingAmount?: number;
TaxAmount?: number;
}
export interface SDKProduct {
Sku?: string,
Name?: string,
Price?: number,
Quantity?: number,
Brand?: string,
Variant?: string,
Category?: string,
Position?: number,
CouponCode?: string,
TotalAmount?: number,
Sku?: string;
Name?: string;
Price?: number;
Quantity?: number;
Brand?: string;
Variant?: string;
Category?: string;
Position?: number;
CouponCode?: string;
TotalAmount?: number;
Attributes?: { [key: string]: string };

@@ -98,0 +98,0 @@ }

@@ -8,3 +8,3 @@ import {

SDKUserIdentity,
SDKProductActionType
SDKProductActionType,
} from './sdkRuntimeModels';

@@ -17,3 +17,4 @@ import * as EventsApi from './eventsApiModels';

mpid: string,
sdkEvents: SDKEvent[]): EventsApi.Batch | null {
sdkEvents: SDKEvent[]
): EventsApi.Batch | null {
if (!mpid) {

@@ -51,3 +52,3 @@ return null;

application_info: {
application_version: lastEvent.AppVersion
application_version: lastEvent.AppVersion,
},

@@ -62,3 +63,3 @@ device_info: {

consent_state: convertConsentState(lastEvent.ConsentState),
integration_attributes: lastEvent.IntegrationAttributes
integration_attributes: lastEvent.IntegrationAttributes,
};

@@ -82,3 +83,3 @@ return upload;

[key: string]: SDKGDPRConsentState;
}): { [key: string]: EventsApi.GDPRConsentState | null} {
}): { [key: string]: EventsApi.GDPRConsentState | null } {
if (!sdkGdprConsentState) {

@@ -102,3 +103,5 @@ return null;

export function convertUserIdentities(sdkUserIdentities?: SDKUserIdentity[]): EventsApi.BatchUserIdentities | null {
export function convertUserIdentities(
sdkUserIdentities?: SDKUserIdentity[]
): EventsApi.BatchUserIdentities | null {
if (!sdkUserIdentities || !sdkUserIdentities.length) {

@@ -120,4 +123,3 @@ return null;

case Types.IdentityType.FacebookCustomAudienceId:
batchIdentities.facebook_custom_audience_id =
identity.Identity;
batchIdentities.facebook_custom_audience_id = identity.Identity;
break;

@@ -169,5 +171,5 @@ case Types.IdentityType.Google:

case Types.MessageType.SessionEnd:
return convertSessionEndEvent(sdkEvent);
return convertSessionEndEvent(sdkEvent);
case Types.MessageType.SessionStart:
return convertSessionStartEvent(sdkEvent);
return convertSessionStartEvent(sdkEvent);
default:

@@ -179,3 +181,5 @@ break;

export function convertProductActionType(actionType: SDKProductActionType) : EventsApi.ProductActionActionEnum {
export function convertProductActionType(
actionType: SDKProductActionType
): EventsApi.ProductActionActionEnum {
if (!actionType) {

@@ -204,3 +208,3 @@ return 'unknown';

case SDKProductActionType.ViewDetail:
return 'view_detail';
return 'view_detail';
default:

@@ -211,8 +215,12 @@ return 'unknown';

export function convertProductAction(sdkEvent: SDKEvent): EventsApi.ProductAction | null {
export function convertProductAction(
sdkEvent: SDKEvent
): EventsApi.ProductAction | null {
if (!sdkEvent.ProductAction) {
return null;
}
const productAction : EventsApi.ProductAction = {
action: convertProductActionType(sdkEvent.ProductAction.ProductActionType),
const productAction: EventsApi.ProductAction = {
action: convertProductActionType(
sdkEvent.ProductAction.ProductActionType
),
checkout_step: sdkEvent.ProductAction.CheckoutStep,

@@ -226,3 +234,3 @@ checkout_options: sdkEvent.ProductAction.CheckoutOptions,

coupon_code: sdkEvent.ProductAction.CouponCode,
products: convertProducts(sdkEvent.ProductAction.ProductList)
products: convertProducts(sdkEvent.ProductAction.ProductList),
};

@@ -232,3 +240,5 @@ return productAction;

export function convertProducts(sdkProducts: SDKProduct[]): EventsApi.Product[] | null {
export function convertProducts(
sdkProducts: SDKProduct[]
): EventsApi.Product[] | null {
if (!sdkProducts || !sdkProducts.length) {

@@ -250,3 +260,3 @@ return null;

coupon_code: sdkProduct.CouponCode,
custom_attributes: sdkProduct.Attributes
custom_attributes: sdkProduct.Attributes,
};

@@ -258,3 +268,5 @@ products.push(product);

export function convertPromotionAction(sdkEvent: SDKEvent): EventsApi.PromotionAction | null {
export function convertPromotionAction(
sdkEvent: SDKEvent
): EventsApi.PromotionAction | null {
if (!sdkEvent.PromotionAction) {

@@ -264,4 +276,5 @@ return null;

const promotionAction: EventsApi.PromotionAction = {
action: sdkEvent.PromotionAction.PromotionActionType as EventsApi.PromotionActionActionEnum,
promotions: convertPromotions(sdkEvent.PromotionAction.PromotionList)
action: sdkEvent.PromotionAction
.PromotionActionType as EventsApi.PromotionActionActionEnum,
promotions: convertPromotions(sdkEvent.PromotionAction.PromotionList),
};

@@ -271,3 +284,5 @@ return promotionAction;

export function convertPromotions(sdkPromotions: SDKPromotion[]): EventsApi.Promotion[] | null {
export function convertPromotions(
sdkPromotions: SDKPromotion[]
): EventsApi.Promotion[] | null {
if (!sdkPromotions || !sdkPromotions.length) {

@@ -282,4 +297,3 @@ return null;

creative: sdkPromotion.Creative,
position: sdkPromotion.Position
position: sdkPromotion.Position,
};

@@ -291,3 +305,5 @@ promotions.push(promotion);

export function convertImpressions(sdkEvent: SDKEvent): EventsApi.ProductImpression[] | null {
export function convertImpressions(
sdkEvent: SDKEvent
): EventsApi.ProductImpression[] | null {
if (!sdkEvent.ProductImpressions) {

@@ -300,3 +316,3 @@ return null;

product_impression_list: sdkImpression.ProductImpressionList,
products: convertProducts(sdkImpression.ProductList)
products: convertProducts(sdkImpression.ProductList),
};

@@ -308,10 +324,14 @@ impressions.push(impression);

export function convertShoppingCart(sdkEvent: SDKEvent): EventsApi.ShoppingCart | null {
if (!sdkEvent.ShoppingCart ||
!sdkEvent.ShoppingCart.ProductList ||
!sdkEvent.ShoppingCart.ProductList.length) {
export function convertShoppingCart(
sdkEvent: SDKEvent
): EventsApi.ShoppingCart | null {
if (
!sdkEvent.ShoppingCart ||
!sdkEvent.ShoppingCart.ProductList ||
!sdkEvent.ShoppingCart.ProductList.length
) {
return null;
}
const shoppingCart: EventsApi.ShoppingCart = {
products: convertProducts(sdkEvent.ShoppingCart.ProductList)
products: convertProducts(sdkEvent.ShoppingCart.ProductList),
};

@@ -321,3 +341,5 @@ return shoppingCart;

export function convertCommerceEvent(sdkEvent: SDKEvent): EventsApi.CommerceEvent {
export function convertCommerceEvent(
sdkEvent: SDKEvent
): EventsApi.CommerceEvent {
const commonEventData: EventsApi.CommonEventData = convertBaseEventData(

@@ -332,3 +354,3 @@ sdkEvent

shopping_cart: convertShoppingCart(sdkEvent),
currency_code: sdkEvent.CurrencyCode
currency_code: sdkEvent.CurrencyCode,
};

@@ -342,3 +364,5 @@

}
export function convertCrashReportEvent(sdkEvent: SDKEvent): EventsApi.CrashReportEvent {
export function convertCrashReportEvent(
sdkEvent: SDKEvent
): EventsApi.CrashReportEvent {
const commonEventData: EventsApi.CommonEventData = convertBaseEventData(

@@ -348,4 +372,4 @@ sdkEvent

let crashReportEventData: EventsApi.CrashReportEventData = {
message: sdkEvent.EventName
}
message: sdkEvent.EventName,
};
crashReportEventData = Object.assign(crashReportEventData, commonEventData);

@@ -376,3 +400,5 @@ return {

export function convertSessionEndEvent(sdkEvent: SDKEvent): EventsApi.SessionEndEvent {
export function convertSessionEndEvent(
sdkEvent: SDKEvent
): EventsApi.SessionEndEvent {
const commonEventData: EventsApi.CommonEventData = convertBaseEventData(

@@ -385,3 +411,3 @@ sdkEvent

//spanning_mpids: sdkEvent.SessionMpids
}
};
sessionEndEventData = Object.assign(sessionEndEventData, commonEventData);

@@ -394,8 +420,13 @@ return {

export function convertSessionStartEvent(sdkEvent: SDKEvent): EventsApi.SessionStartEvent {
export function convertSessionStartEvent(
sdkEvent: SDKEvent
): EventsApi.SessionStartEvent {
const commonEventData: EventsApi.CommonEventData = convertBaseEventData(
sdkEvent
);
let sessionStartEventData: EventsApi.SessionStartEventData = {}
sessionStartEventData = Object.assign(sessionStartEventData, commonEventData);
let sessionStartEventData: EventsApi.SessionStartEventData = {};
sessionStartEventData = Object.assign(
sessionStartEventData,
commonEventData
);
return {

@@ -407,3 +438,5 @@ event_type: 'session_start',

export function convertPageViewEvent(sdkEvent: SDKEvent): EventsApi.ScreenViewEvent {
export function convertPageViewEvent(
sdkEvent: SDKEvent
): EventsApi.ScreenViewEvent {
const commonEventData: EventsApi.CommonEventData = convertBaseEventData(

@@ -414,3 +447,3 @@ sdkEvent

custom_flags: sdkEvent.CustomFlags,
screen_name: sdkEvent.EventName
screen_name: sdkEvent.EventName,
};

@@ -429,3 +462,3 @@ screenViewEventData = Object.assign(screenViewEventData, commonEventData);

let optOutEventData: EventsApi.OptOutEventData = {
is_opted_out: sdkEvent.OptOut
is_opted_out: sdkEvent.OptOut,
};

@@ -432,0 +465,0 @@ optOutEventData = Object.assign(optOutEventData, commonEventData);

@@ -19,12 +19,15 @@ import Types from './types';

event.CustomFlags[prop].forEach(function(customFlagProperty) {
if (typeof customFlagProperty === 'number'
|| typeof customFlagProperty === 'string'
|| typeof customFlagProperty === 'boolean') {
if (
typeof customFlagProperty === 'number' ||
typeof customFlagProperty === 'string' ||
typeof customFlagProperty === 'boolean'
) {
valueArray.push(customFlagProperty.toString());
}
});
}
else if (typeof event.CustomFlags[prop] === 'number'
|| typeof event.CustomFlags[prop] === 'string'
|| typeof event.CustomFlags[prop] === 'boolean') {
} else if (
typeof event.CustomFlags[prop] === 'number' ||
typeof event.CustomFlags[prop] === 'string' ||
typeof event.CustomFlags[prop] === 'boolean'
) {
valueArray.push(event.CustomFlags[prop].toString());

@@ -103,3 +106,3 @@ }

tpa: parseNumber(product.TotalAmount),
attrs: product.Attributes
attrs: product.Attributes,
};

@@ -117,19 +120,19 @@ }

jsonObject.gdpr = gdpr;
for (var purpose in gdprConsentState){
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof(gdprConsent.Consented) === 'boolean') {
if (typeof gdprConsent.Consented === 'boolean') {
gdpr[purpose].c = gdprConsent.Consented;
}
if (typeof(gdprConsent.Timestamp) === 'number') {
if (typeof gdprConsent.Timestamp === 'number') {
gdpr[purpose].ts = gdprConsent.Timestamp;
}
if (typeof(gdprConsent.ConsentDocument) === 'string') {
if (typeof gdprConsent.ConsentDocument === 'string') {
gdpr[purpose].d = gdprConsent.ConsentDocument;
}
if (typeof(gdprConsent.Location) === 'string') {
if (typeof gdprConsent.Location === 'string') {
gdpr[purpose].l = gdprConsent.Location;
}
if (typeof(gdprConsent.HardwareId) === 'string') {
if (typeof gdprConsent.HardwareId === 'string') {
gdpr[purpose].h = gdprConsent.HardwareId;

@@ -147,5 +150,12 @@ }

var eventObject = {};
var optOut = (event.messageType === Types.MessageType.OptOut ? !mParticle.Store.isEnabled : null);
var optOut =
event.messageType === Types.MessageType.OptOut
? !mParticle.Store.isEnabled
: null;
if (mParticle.Store.sessionId || event.messageType == Types.MessageType.OptOut || mParticle.Store.webviewBridgeEnabled) {
if (
mParticle.Store.sessionId ||
event.messageType == Types.MessageType.OptOut ||
mParticle.Store.webviewBridgeEnabled
) {
if (event.hasOwnProperty('toEventAPIObject')) {

@@ -159,3 +169,3 @@ eventObject = event.toEventAPIObject();

EventDataType: event.messageType,
CustomFlags: event.customFlags || {}
CustomFlags: event.customFlags || {},
};

@@ -172,3 +182,5 @@ }

SessionId: mParticle.Store.sessionId,
SessionStartDate: mParticle.Store.sessionStartDate ? mParticle.Store.sessionStartDate.getTime() : null,
SessionStartDate: mParticle.Store.sessionStartDate
? mParticle.Store.sessionStartDate.getTime()
: null,
Debug: mParticle.Store.SDKConfig.isDevelopmentMode,

@@ -182,3 +194,3 @@ Location: mParticle.Store.currentPosition,

IntegrationAttributes: mParticle.Store.integrationAttributes,
CurrencyCode: mParticle.Store.currencyCode
CurrencyCode: mParticle.Store.currencyCode,
};

@@ -189,6 +201,9 @@

appendUserInfo(currentUser, eventObject);
if (event.messageType === Types.MessageType.SessionEnd) {
eventObject.SessionLength = mParticle.Store.dateLastEventSent.getTime() - mParticle.Store.sessionStartDate.getTime();
eventObject.currentSessionMPIDs = mParticle.Store.currentSessionMPIDs;
eventObject.SessionLength =
mParticle.Store.dateLastEventSent.getTime() -
mParticle.Store.sessionStartDate.getTime();
eventObject.currentSessionMPIDs =
mParticle.Store.currentSessionMPIDs;
eventObject.EventAttributes = mParticle.Store.sessionAttributes;

@@ -231,3 +246,3 @@

mpid: event.MPID,
smpids: event.currentSessionMPIDs
smpids: event.currentSessionMPIDs,
};

@@ -257,3 +272,3 @@

dto.sc = {
pl: convertProductListToDTO(event.ShoppingCart.ProductList)
pl: convertProductListToDTO(event.ShoppingCart.ProductList),
};

@@ -273,9 +288,10 @@ }

ts: parseNumber(event.ProductAction.ShippingAmount),
tt: parseNumber(event.ProductAction.TaxAmount)
tt: parseNumber(event.ProductAction.TaxAmount),
};
}
else if (event.PromotionAction) {
} else if (event.PromotionAction) {
dto.pm = {
an: event.PromotionAction.PromotionActionType,
pl: event.PromotionAction.PromotionList.map(function(promotion) {
pl: event.PromotionAction.PromotionList.map(function(
promotion
) {
return {

@@ -285,17 +301,15 @@ id: promotion.Id,

cr: promotion.Creative,
ps: promotion.Position ? promotion.Position : 0
ps: promotion.Position ? promotion.Position : 0,
};
})
}),
};
}
else if (event.ProductImpressions) {
} else if (event.ProductImpressions) {
dto.pi = event.ProductImpressions.map(function(impression) {
return {
pil: impression.ProductImpressionList,
pl: convertProductListToDTO(impression.ProductList)
pl: convertProductListToDTO(impression.ProductList),
};
});
}
}
else if (event.EventDataType === MessageType.Profile) {
} else if (event.EventDataType === MessageType.Profile) {
dto.pet = event.ProfileMessageType;

@@ -311,3 +325,3 @@ }

convertToConsentStateDTO: convertToConsentStateDTO,
appendUserInfo: appendUserInfo
};
appendUserInfo: appendUserInfo,
};

@@ -14,5 +14,12 @@ import Helpers from './helpers';

if (mParticle.Store.sessionId) {
var sessionTimeoutInMilliseconds = mParticle.Store.SDKConfig.sessionTimeout * 60000;
var sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;
if (new Date() > new Date(mParticle.Store.dateLastEventSent.getTime() + sessionTimeoutInMilliseconds)) {
if (
new Date() >
new Date(
mParticle.Store.dateLastEventSent.getTime() +
sessionTimeoutInMilliseconds
)
) {
endSession();

@@ -23,3 +30,6 @@ startNewSession();

if (cookies && !cookies.cu) {
IdentityAPI.identify(mParticle.Store.SDKConfig.identifyRequest, mParticle.Store.SDKConfig.identityCallback);
IdentityAPI.identify(
mParticle.Store.SDKConfig.identifyRequest,
mParticle.Store.SDKConfig.identityCallback
);
mParticle.Store.identifyCalled = true;

@@ -58,3 +68,6 @@ mParticle.Store.SDKConfig.identityCallback = null;

if (!mParticle.Store.identifyCalled) {
IdentityAPI.identify(mParticle.Store.SDKConfig.identifyRequest, mParticle.Store.SDKConfig.identityCallback);
IdentityAPI.identify(
mParticle.Store.SDKConfig.identifyRequest,
mParticle.Store.SDKConfig.identityCallback
);
mParticle.Store.identifyCalled = true;

@@ -65,6 +78,7 @@ mParticle.Store.SDKConfig.identityCallback = null;

logEvent({ messageType: Types.MessageType.SessionStart });
} else {
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonStartSession
);
}
else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonStartSession);
}
}

@@ -83,5 +97,3 @@

} else if (Helpers.canLog()) {
var sessionTimeoutInMilliseconds,
cookies,
timeSinceLastEventSent;
var sessionTimeoutInMilliseconds, cookies, timeSinceLastEventSent;

@@ -95,3 +107,5 @@ cookies = Persistence.getCookie() || Persistence.getLocalStorage();

if (cookies.gs && !cookies.gs.sid) {
mParticle.Logger.verbose(Messages.InformationMessages.NoSessionToEnd);
mParticle.Logger.verbose(
Messages.InformationMessages.NoSessionToEnd
);
return;

@@ -106,3 +120,4 @@ }

if (cookies.gs && cookies.gs.les) {
sessionTimeoutInMilliseconds = mParticle.Store.SDKConfig.sessionTimeout * 60000;
sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;
var newDate = new Date().getTime();

@@ -124,3 +139,5 @@ timeSinceLastEventSent = newDate - cookies.gs.les;

} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonEndSession);
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonEndSession
);
}

@@ -130,3 +147,4 @@ }

function setSessionTimer() {
var sessionTimeoutInMilliseconds = mParticle.Store.SDKConfig.sessionTimeout * 60000;
var sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;

@@ -174,3 +192,3 @@ mParticle.Store.globalTimer = window.setTimeout(function() {

resetSessionTimer: resetSessionTimer,
clearSessionTimeout: clearSessionTimeout
};
clearSessionTimeout: clearSessionTimeout,
};

@@ -68,3 +68,3 @@ import Constants from './constants';

configuredForwarders: [],
pixelConfigurations: []
pixelConfigurations: [],
};

@@ -77,3 +77,5 @@

this.storageName = Helpers.createMainStorageName(config.workspaceToken);
this.prodStorageName = Helpers.createProductStorageName(config.workspaceToken);
this.prodStorageName = Helpers.createProductStorageName(
config.workspaceToken
);
this.integrationDelayTimeoutStart = Date.now();

@@ -85,7 +87,9 @@

if (config.hasOwnProperty('isDevelopmentMode')) {
this.SDKConfig.isDevelopmentMode = Helpers.returnConvertedBoolean(config.isDevelopmentMode);
this.SDKConfig.isDevelopmentMode = Helpers.returnConvertedBoolean(
config.isDevelopmentMode
);
} else {
this.SDKConfig.isDevelopmentMode = false;
}
if (config.hasOwnProperty('serviceUrl')) {

@@ -153,3 +157,4 @@ this.SDKConfig.serviceUrl = config.serviceUrl;

} else {
this.SDKConfig.maxCookieSize = Constants.DefaultConfig.maxCookieSize;
this.SDKConfig.maxCookieSize =
Constants.DefaultConfig.maxCookieSize;
}

@@ -162,5 +167,7 @@

if (config.hasOwnProperty('integrationDelayTimeout')) {
this.SDKConfig.integrationDelayTimeout = config.integrationDelayTimeout;
this.SDKConfig.integrationDelayTimeout =
config.integrationDelayTimeout;
} else {
this.SDKConfig.integrationDelayTimeout = Constants.DefaultConfig.integrationDelayTimeout;
this.SDKConfig.integrationDelayTimeout =
Constants.DefaultConfig.integrationDelayTimeout;
}

@@ -177,3 +184,7 @@

} else {
logger.warning('The optional callback must be a function. You tried entering a(n) ' + typeof callback, ' . Callback not set. Please set your callback again.');
logger.warning(
'The optional callback must be a function. You tried entering a(n) ' +
typeof callback,
' . Callback not set. Please set your callback again.'
);
}

@@ -204,7 +215,10 @@ }

} else {
logger.warning('You should have a workspaceToken on your mParticle.config object for security purposes.');
logger.warning(
'You should have a workspaceToken on your mParticle.config object for security purposes.'
);
}
if (config.hasOwnProperty('requiredWebviewBridgeName')) {
this.SDKConfig.requiredWebviewBridgeName = config.requiredWebviewBridgeName;
this.SDKConfig.requiredWebviewBridgeName =
config.requiredWebviewBridgeName;
} else if (config.hasOwnProperty('workspaceToken')) {

@@ -215,3 +229,4 @@ this.SDKConfig.requiredWebviewBridgeName = config.workspaceToken;

if (config.hasOwnProperty('minWebviewBridgeVersion')) {
this.SDKConfig.minWebviewBridgeVersion = config.minWebviewBridgeVersion;
this.SDKConfig.minWebviewBridgeVersion =
config.minWebviewBridgeVersion;
} else {

@@ -224,18 +239,33 @@ this.SDKConfig.minWebviewBridgeVersion = 1;

} else {
this.SDKConfig.aliasMaxWindow = Constants.DefaultConfig.aliasMaxWindow;
this.SDKConfig.aliasMaxWindow =
Constants.DefaultConfig.aliasMaxWindow;
}
if (!config.hasOwnProperty('flags')) {
this.SDKConfig.flags = {};
}
if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)) {
if (
!this.SDKConfig.flags.hasOwnProperty(
Constants.FeatureFlags.EventsV3
)
) {
this.SDKConfig.flags[Constants.FeatureFlags.EventsV3] = 0;
}
if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)) {
this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis] = Constants.DefaultConfig.uploadInterval;
if (
!this.SDKConfig.flags.hasOwnProperty(
Constants.FeatureFlags.EventBatchingIntervalMillis
)
) {
this.SDKConfig.flags[
Constants.FeatureFlags.EventBatchingIntervalMillis
] = Constants.DefaultConfig.uploadInterval;
}
if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)) {
if (
!this.SDKConfig.flags.hasOwnProperty(
Constants.FeatureFlags.ReportBatching
)
) {
this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching] = false;
}
}
}
}

@@ -41,7 +41,7 @@ let mParticle = {

setCurrencyCode: voidFunction,
Cart: new Cart()
Cart: new Cart(),
},
Consent: {
createConsentState: createConsentState,
createGDPRConsent: returnGDPRConsent
createGDPRConsent: returnGDPRConsent,
},

@@ -57,15 +57,21 @@ Identity: {

logout: voidFunction,
modify: voidFunction
}
modify: voidFunction,
},
};
function voidFunction() {}
function returnString() { return ''; }
function returnObject() { return {}; }
function returnThis() { return this; }
function returnString() {
return '';
}
function returnObject() {
return {};
}
function returnThis() {
return this;
}
function returnUser() {
return {
getUserIdentities: function () {
getUserIdentities: function() {
return {
userIdentities: {}
userIdentities: {},
};

@@ -85,3 +91,3 @@ },

getConsentState: createConsentState,
setConsentState: voidFunction
setConsentState: voidFunction,
};

@@ -101,3 +107,3 @@ }

return [returnProduct()];
}
},
};

@@ -109,3 +115,3 @@ }

Name: 'name',
Product: returnProduct()
Product: returnProduct(),
};

@@ -126,3 +132,3 @@ }

TotalAmount: 0,
Attributes: {}
Attributes: {},
};

@@ -136,3 +142,3 @@ }

Name: 'name',
Position: 0
Position: 0,
};

@@ -148,3 +154,3 @@ }

Shipping: 'shipping',
Tax: 0
Tax: 0,
};

@@ -159,3 +165,3 @@ }

Location: 'location',
Timestamp: 1568648478988
Timestamp: 1568648478988,
};

@@ -168,4 +174,4 @@ }

destinationMpid: 'b',
startTime: (new Date()).getTime(),
endTime: (new Date()).getTime()
startTime: new Date().getTime(),
endTime: new Date().getTime(),
};

@@ -179,6 +185,6 @@ }

getGDPRConsentState: returnGDPRConsent,
removeGDPRConsentState: returnThis
removeGDPRConsentState: returnThis,
};
}
export default mParticle;
export default mParticle;

@@ -11,3 +11,3 @@ var MessageType = {

Commerce: 16,
Media: 20
Media: 20,
};

@@ -70,3 +70,3 @@

}
}
},
};

@@ -88,3 +88,3 @@

ProductRemoveFromWishlist: 21,
ProductImpression: 22
ProductImpression: 22,
};

@@ -104,3 +104,3 @@

Other3: 11,
Other4: 12
Other4: 12,
};

@@ -216,3 +216,3 @@

AddToWishlist: 9,
RemoveFromWishlist: 10
RemoveFromWishlist: 10,
};

@@ -278,3 +278,3 @@

PromotionView: 1,
PromotionClick: 2
PromotionClick: 2,
};

@@ -306,6 +306,6 @@

var ProfileMessageType = {
Logout: 3
Logout: 3,
};
var ApplicationTransitionType = {
AppInit: 1
AppInit: 1,
};

@@ -321,3 +321,3 @@

ProductActionType: ProductActionType,
PromotionActionType: PromotionActionType
};
PromotionActionType: PromotionActionType,
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc