@shopgate/tracking-core
Version:
Tracking core library for the Shopgate Connect PWA.
75 lines • 8.31 kB
JavaScript
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import DataRequest from'@shopgate/pwa-core/classes/DataRequest';import{logger}from'@shopgate/pwa-core/helpers';import*as _SGAction from'@shopgate/pwa-core/commands/unifiedTracking';export{_SGAction as SGAction};/**
* Decodes a hexadecimal encoded binary string
* @param {string} str The string that shall be decoded
* @see http://locutus.io/php/strings/hex2bin/
* @returns {string|boolean} Hexadecimal representation of data. FALSE if decoding failed.
*/export var hex2bin=function hex2bin(str){var s="".concat(str);var ret=[];var i=0;var l;for(l=s.length;i<l;i+=2){var c=parseInt(s.substr(i,1),16);var k=parseInt(s.substr(i+1,1),16);// eslint-disable-next-line no-restricted-globals
if(isNaN(c)||isNaN(k)){return false;}// eslint-disable-next-line no-bitwise
ret.push(c<<4|k);}// eslint-disable-next-line prefer-spread
return String.fromCharCode.apply(String,ret);};/**
* Sends a DataRequest
* @param {string} url Url for the request
*/export function sendDataRequest(url){new DataRequest(url).dispatch().then(function(result){return logger.info(url,result);})["catch"](function(err){return err&&logger.error(err);});}/**
* Object representation of URI(RFC2396) string
* Made for general purpose. Feel free to extend it for your needs.
*/export var SGLink=/*#__PURE__*/function(){/**
* Constructor
* @param {string} url Url to creating SGLink from
*/function SGLink(url){var _this=this;_classCallCheck(this,SGLink);// Complete url string
_defineProperty(this,"url",'');// Any scheme we support (ex. https|shopgate-{$number}|sgapi)
_defineProperty(this,"scheme",'');_defineProperty(this,"authority",'');_defineProperty(this,"path",'');_defineProperty(this,"splittedPath",[]);_defineProperty(this,"query",'');// Endpoint - safe for shopgate (ex. no endpoint is converted to "index")
_defineProperty(this,"action",'');_defineProperty(this,"params",{});_defineProperty(this,"isDeepLink",false);/**
* Converts the object to relative url
* @param {boolean} [leadingSlash=true] Tells if the url shall start with a leading slash
* @return {string}
*/_defineProperty(this,"toRelativeString",function(){var leadingSlash=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var outputUrl='';if(leadingSlash&&_this.path[0]!=='/'){outputUrl='/';}if(_this.path){outputUrl+=SGLink.encodeURISafe(_this.path);}if(_this.query){// .query is always encoded
outputUrl+="?".concat(_this.query);}return outputUrl;});this.url=url;this.parseUrl(url);}/**
* Encode the url with encodeURIComponent and
* takes care of double encoding
*
* @param {string} string - string to be encoded
* @return {string}
*/return _createClass(SGLink,[{key:"parseUrl",value:/**
* Parses url and extracts path, query, action, splittedPath, ...
*
* @param {string} incomingUrl The url that shall be parsed.
*/function parseUrl(incomingUrl){var urlToSanitize=incomingUrl;if(!urlToSanitize){urlToSanitize='';}var commonSchemas=['http','https','tel','mailto'];// Based on the regex in RFC2396 Appendix B.
var parser=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/;var result=urlToSanitize.match(parser);if(!this.isDeepLink&&result[1]&&commonSchemas.indexOf(result[1])===-1){this.isDeepLink=true;var scheme="".concat(result[1],"://");/**
* Add slash so that we can parse the attributes properly
* (for shopgate-standalone://cart we would get e.g. "authority: cart" which is wrong)
*/urlToSanitize=urlToSanitize.replace(scheme,"".concat(scheme,"/"));this.parseUrl(urlToSanitize);return;}this.scheme=result[1]||'';this.authority=result[2]||'';this.path=result[3]||'';this.query=result[4]||'';this.action='';// Endpoint - safe for shopgate (ex. no endpoint is converted to "index")
if(this.query){var queryParts=this.query.split('&');var queryPartsLength=queryParts.length;// Clearing params
this.setParams({});for(var i=0;i<queryPartsLength;i+=1){var queryPair=queryParts[i].split('=');this.setParam(queryPair[0],queryPair[1]);}}if(this.path){var pathSplitted=this.path.replace('/php/shopgate','').split('/');this.action=pathSplitted[0]||'';this.splittedPath=pathSplitted;if(pathSplitted[0]==='/'||pathSplitted[0]===''){this.action=pathSplitted[1]||'';this.splittedPath.shift();}}}/**
* Gets a param
* @param {string} name name of param
* @return {string|undefined}
*/},{key:"getParam",value:function getParam(name){if(!(name in this.params)){return undefined;}return this.params[name];}/**
* Sets param.
* @param {string} name Name of param
* @param {string} [value] Value of param - if empty, the parameter will be deleted from the query
*/},{key:"setParam",value:function setParam(name,value){if(typeof value==='undefined'){this.deleteParam(name);}else{this.params[name]=value;this.setParams();}}/**
* Sets params array
*
* @param {Object} [newParams] New Params to be set
*/},{key:"setParams",value:function setParams(newParams){var _this2=this;var newQueryArr=[];if(typeof newParams!=='undefined'){this.params=newParams;}Object.keys(this.params).forEach(function(keyName){newQueryArr.push("".concat(keyName,"=").concat(SGLink.encodeURIComponentSafe(_this2.params[keyName])));});this.query=newQueryArr.join('&');}/**
* Safely deletes the param.
*
* @param {string} name name of param
* @returns {boolean}
*/},{key:"deleteParam",value:function deleteParam(name){if(!(name in this.params)){return false;}delete this.params[name];this.setParams(this.params);return true;}/**
* Converts the object to string
*
* @return {string}
*/},{key:"toString",value:function toString(){var outputUrl='';var notNavigatorSchema=['mailto','tel'].indexOf(this.scheme)>-1;if(this.scheme){outputUrl+=this.scheme;// The sgapi-links don't need further scheme parsing since the scheme is 'sgapi:'
if(this.scheme!=='sgapi'){if(notNavigatorSchema){if(this.scheme.indexOf(':')===-1){outputUrl+=':';}}else{if(this.scheme.indexOf(':/')===-1){// If the scheme already contains :/ we don't want to add it again
outputUrl+=':/';this.scheme=outputUrl;}if(!this.isDeepLink){outputUrl+='/';}}}else if(this.scheme.indexOf(':')===-1){outputUrl+=':';}}if(this.authority){outputUrl+=this.authority;}outputUrl+=this.toRelativeString(false);return outputUrl;}},{key:"setUtmParams",value:/**
* Sets utm param from event.
* @param {Object} data event data
* @param {Object} raw event raw data
*/function setUtmParams(data,raw){// Add fake params, only if it didn't come from branch.io
if(raw.type!=='branchio'){this.setParam('utm_source','shopgate');this.setParam('utm_medium',raw.type);}if(raw.type==='push_message'){var campaigns=['cart_reminder','inactive_app_user'];var notificationId=raw.notificationId||'not-provided';var campaignName=this.getParam('utm_campaign');if(campaigns.indexOf(campaignName)!==-1){// Set utm_content to distinguish the cart reminders from "normal" push messages
this.setParam('utm_content',campaignName);}this.setParam('utm_campaign',"push-".concat(notificationId));}}}],[{key:"encodeURIComponentSafe",value:function encodeURIComponentSafe(string){var decoded=decodeURIComponent(string);if(decoded!==string){return string;}return encodeURIComponent(string);}/**
* Encode the url and takes care of double encoding
* @param {string} string String to be encoded
* @returns {string} encoded string
*/},{key:"encodeURISafe",value:function encodeURISafe(string){var decoded=decodeURI(string);if(decoded!==string){return string;}return encodeURI(string);}}]);}();