Comparing version 0.0.7 to 0.0.8
@@ -1,1 +0,1067 @@ | ||
"use strict";var $jscomp=$jscomp||{};$jscomp.scope={},$jscomp.owns=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},$jscomp.assign="function"==typeof Object.assign?Object.assign:function(t,e){for(var n=1;n<arguments.length;n++){var r=arguments[n];if(r)for(var o in r)$jscomp.owns(r,o)&&(t[o]=r[o])}return t},$jscomp.ASSUME_ES5=!1,$jscomp.ASSUME_NO_NATIVE_MAP=!1,$jscomp.ASSUME_NO_NATIVE_SET=!1,$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,n){t!=Array.prototype&&t!=Object.prototype&&(t[e]=n.value)},$jscomp.getGlobal=function(t){return"undefined"!=typeof window&&window===t?t:"undefined"!=typeof global&&null!=global?global:t},$jscomp.global=$jscomp.getGlobal(this),$jscomp.polyfill=function(t,e,n,r){if(e){for(n=$jscomp.global,t=t.split("."),r=0;r<t.length-1;r++){var o=t[r];o in n||(n[o]={}),n=n[o]}(e=e(r=n[t=t[t.length-1]]))!=r&&null!=e&&$jscomp.defineProperty(n,t,{configurable:!0,writable:!0,value:e})}},$jscomp.polyfill("Object.assign",function(t){return t||$jscomp.assign},"es6","es3"),$jscomp.SYMBOL_PREFIX="jscomp_symbol_",$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){},$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)},$jscomp.Symbol=function(){var e=0;return function(t){return $jscomp.SYMBOL_PREFIX+(t||"")+e++}}(),$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var t=$jscomp.global.Symbol.iterator;t||(t=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator")),"function"!=typeof Array.prototype[t]&&$jscomp.defineProperty(Array.prototype,t,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}}),$jscomp.initSymbolIterator=function(){}},$jscomp.arrayIterator=function(t){var e=0;return $jscomp.iteratorPrototype(function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}})},$jscomp.iteratorPrototype=function(t){return $jscomp.initSymbolIterator(),(t={next:t})[$jscomp.global.Symbol.iterator]=function(){return this},t},$jscomp.polyfill("Array.from",function(t){return t||function(t,e,n){$jscomp.initSymbolIterator(),e=null!=e?e:function(t){return t};var r=[],o=t[Symbol.iterator];if("function"==typeof o){t=o.call(t);for(var i=0;!(o=t.next()).done;)r.push(e.call(n,o.value,i++))}else for(o=t.length,i=0;i<o;i++)r.push(e.call(n,t[i],i));return r}},"es6","es3"),$jscomp.findInternal=function(t,e,n){t instanceof String&&(t=String(t));for(var r=t.length,o=0;o<r;o++){var i=t[o];if(e.call(n,i,o,t))return{i:o,v:i}}return{i:-1,v:void 0}},$jscomp.polyfill("Array.prototype.findIndex",function(t){return t||function(t,e){return $jscomp.findInternal(this,t,e).i}},"es6","es3"),$jscomp.iteratorFromArray=function(e,n){$jscomp.initSymbolIterator(),e instanceof String&&(e+="");var r=0,o={next:function(){if(r<e.length){var t=r++;return{value:n(t,e[t]),done:!1}}return o.next=function(){return{done:!0,value:void 0}},o.next()}};return o[Symbol.iterator]=function(){return o},o},$jscomp.polyfill("Array.prototype.keys",function(t){return t||function(){return $jscomp.iteratorFromArray(this,function(t){return t})}},"es6","es3"),$jscomp.makeIterator=function(t){$jscomp.initSymbolIterator();var e=t[Symbol.iterator];return e?e.call(t):$jscomp.arrayIterator(t)},$jscomp.FORCE_POLYFILL_PROMISE=!1,$jscomp.polyfill("Promise",function(t){function e(){this.batch_=null}function c(n){return n instanceof u?n:new u(function(t,e){t(n)})}if(t&&!$jscomp.FORCE_POLYFILL_PROMISE)return t;e.prototype.asyncExecute=function(t){return null==this.batch_&&(this.batch_=[],this.asyncExecuteBatch_()),this.batch_.push(t),this},e.prototype.asyncExecuteBatch_=function(){var t=this;this.asyncExecuteFunction(function(){t.executeBatch_()})};var n=$jscomp.global.setTimeout;e.prototype.asyncExecuteFunction=function(t){n(t,0)},e.prototype.executeBatch_=function(){for(;this.batch_&&this.batch_.length;){var t=this.batch_;this.batch_=[];for(var e=0;e<t.length;++e){var n=t[e];t[e]=null;try{n()}catch(t){this.asyncThrow_(t)}}}this.batch_=null},e.prototype.asyncThrow_=function(t){this.asyncExecuteFunction(function(){throw t})};var u=function(t){this.state_=0,this.result_=void 0,this.onSettledCallbacks_=[];var e=this.createResolveAndReject_();try{t(e.resolve,e.reject)}catch(t){e.reject(t)}};u.prototype.createResolveAndReject_=function(){function t(e){return function(t){r||(r=!0,e.call(n,t))}}var n=this,r=!1;return{resolve:t(this.resolveTo_),reject:t(this.reject_)}},u.prototype.resolveTo_=function(t){if(t===this)this.reject_(new TypeError("A Promise cannot resolve to itself"));else if(t instanceof u)this.settleSameAsPromise_(t);else{t:switch(typeof t){case"object":var e=null!=t;break t;case"function":e=!0;break t;default:e=!1}e?this.resolveToNonPromiseObj_(t):this.fulfill_(t)}},u.prototype.resolveToNonPromiseObj_=function(t){var e=void 0;try{e=t.then}catch(t){return void this.reject_(t)}"function"==typeof e?this.settleSameAsThenable_(e,t):this.fulfill_(t)},u.prototype.reject_=function(t){this.settle_(2,t)},u.prototype.fulfill_=function(t){this.settle_(1,t)},u.prototype.settle_=function(t,e){if(0!=this.state_)throw Error("Cannot settle("+t+", "+e+"): Promise already settled in state"+this.state_);this.state_=t,this.result_=e,this.executeOnSettledCallbacks_()},u.prototype.executeOnSettledCallbacks_=function(){if(null!=this.onSettledCallbacks_){for(var t=0;t<this.onSettledCallbacks_.length;++t)o.asyncExecute(this.onSettledCallbacks_[t]);this.onSettledCallbacks_=null}};var o=new e;return u.prototype.settleSameAsPromise_=function(t){var e=this.createResolveAndReject_();t.callWhenSettled_(e.resolve,e.reject)},u.prototype.settleSameAsThenable_=function(t,e){var n=this.createResolveAndReject_();try{t.call(e,n.resolve,n.reject)}catch(t){n.reject(t)}},u.prototype.then=function(t,e){function n(e,t){return"function"==typeof e?function(t){try{r(e(t))}catch(t){o(t)}}:t}var r,o,i=new u(function(t,e){r=t,o=e});return this.callWhenSettled_(n(t,r),n(e,o)),i},u.prototype.catch=function(t){return this.then(void 0,t)},u.prototype.callWhenSettled_=function(t,e){function n(){switch(r.state_){case 1:t(r.result_);break;case 2:e(r.result_);break;default:throw Error("Unexpected state: "+r.state_)}}var r=this;null==this.onSettledCallbacks_?o.asyncExecute(n):this.onSettledCallbacks_.push(n)},u.resolve=c,u.reject=function(n){return new u(function(t,e){e(n)})},u.race=function(o){return new u(function(t,e){for(var n=$jscomp.makeIterator(o),r=n.next();!r.done;r=n.next())c(r.value).callWhenSettled_(t,e)})},u.all=function(t){var i=$jscomp.makeIterator(t),a=i.next();return a.done?c([]):new u(function(n,t){function e(e){return function(t){r[e]=t,0==--o&&n(r)}}for(var r=[],o=0;r.push(void 0),o++,c(a.value).callWhenSettled_(e(r.length-1),t),!(a=i.next()).done;);})},u},"es6","es3");var redux=require("redux"),_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_extends=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,r=arguments[e];for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},toConsumableArray=function(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)},dynamic=[],dynamicMiddlewares=function(o){return function(r){return function(t){var e={getState:o.getState,dispatch:function(t){return o.dispatch(t)}},n=dynamic.map(function(t){return t(e)});return redux.compose.apply(void 0,toConsumableArray(n))(r)(t)}}},addMiddleware=function(){var t;dynamic=(t=dynamic).concat.apply(t,arguments)},removeMiddleware=function(e){var t=dynamic.findIndex(function(t){return t===e});-1!==t&&(dynamic=[].concat(toConsumableArray(dynamic.slice(0,t)),toConsumableArray(dynamic.slice(t+1))))},EVENTS={INITIALIZE:"analyticsInit",HANDLE_PARAMS:"params",SET_CAMPAIGN:"campaign",READY:"ready",REGISTER_INTEGRATION:"integration_init",INTEGRATION_LOADED:"integration_ready",INTEGRATION_FAILED:"integration_failed",ENABLE_INTEGRATION:"enable_integration",DISABLE_INTEGRATION:"disable_integration",PAGE_START:"page_init",PAGE:"page",PAGE_COMPLETE:"page_complete",PAGE_ABORT:"page_abort",TRACK_START:"track_init",TRACK:"track",TRACK_COMPLETE:"track_complete",TRACK_ABORT:"track_abort",IDENTIFY_START:"identify_init",IDENTIFY:"identify",IDENTIFY_COMPLETE:"identify_complete",IDENTIFY_ABORTED:"identify_abort"};function getUrlParams(t){if("undefined"==typeof window)return{};var e,n={},r=/([^&=]+)=?([^&]*)/g;if(!(t=t?(t=t.match(/\?(.*)/))&&t[1]?t[1].split("#")[0]:"":window.location.search.substring(1)))return!1;for(;e=r.exec(t);)if("-1"==e[1].indexOf("["))n[decode(e[1])]=decode(e[2]);else{var o=e[1].indexOf("["),i=e[1].slice(o+1,e[1].indexOf("]",o));o=decode(e[1].slice(0,o)),"object"!==_typeof(n[o])&&(n[decode(o)]={},n[decode(o)].length=0),i?n[decode(o)][decode(i)]=decode(e[2]):Array.prototype.push.call(n[decode(o)],decode(e[2]))}return n}function decode(t){return decodeURIComponent(t).replace(/\+/g," ")}var initialize=function(o){return function(r){return function(t){if(t.type===EVENTS.INITIALIZE){var n=getUrlParams();if(n){o.dispatch({type:EVENTS.HANDLE_PARAMS,params:n});var e=Object.keys(n).reduce(function(t,e){return e.match(/utm_/)&&(t[e]=n[e]),t},{});Object.keys(e).length&&o.dispatch({type:EVENTS.SET_CAMPAIGN,campaign:e})}}return r(t)}}};function formatPayload(t,e){var n={};return"object"===(void 0===t?"undefined":_typeof(t))?n=t:"object"===(void 0===e?"undefined":_typeof(e))&&(n=e),n}function getIntegrationWithMethod(n,r){return Object.keys(n).reduce(function(t,e){return(e=n[e])[r]?t.concat(e):t},[])}function getCallback(){for(var t=0;t<arguments.length;++t)if("function"==typeof arguments[t])return arguments[t];return!1}function trackMiddleware(r){return function(E){return function(e){return function(t){var n=t.type,a=t.eventName,c=t.data,u=t.options,s=t.callback;if(n===EVENTS.TRACK_START){var l=formatPayload(a,c),d={eventName:a,payload:l,options:u};if(t.abort)return E.dispatch(_extends({type:EVENTS.TRACK_ABORT},d)),e(t);var f=getIntegrationWithMethod(r(),"track");if(!f.length)return E.dispatch(_extends({type:EVENTS.TRACK},d)),E.dispatch(_extends({type:EVENTS.TRACK_COMPLETE},d));var p=0,y=!1;f.filter(function(t){var e=u&&u.integrations;return(e=e&&!1===e[t.NAMESPACE])&&console.log("ABORT TRACK>>>>>",t.NAMESPACE,n),!e}).forEach(function(r){var o=r.NAMESPACE,i=0;!function t(){var e=E.getState(),n=_extends({},e,{options:u});if(!e.integrations[o].loaded)return 1e4<i?E.dispatch(_extends({},d,{type:"trackingTimeout"})):(i+=10,setTimeout(t,10)),!1;r.track(a,l,n),y||(E.dispatch(_extends({type:EVENTS.TRACK},d)),y=!0),E.dispatch(_extends({type:"track:"+o,integration:o},d)),(p+=1)===f.length&&((n=getCallback(c,u,s))&&n(e),E.dispatch(_extends({type:EVENTS.TRACK_COMPLETE},d)))}()})}return e(t)}}}}var inBrowser="undefined"!=typeof window,getPageData=function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return inBrowser&&(t=_extends({title:document.title,url:window.location.href,path:window.location.pathname,hash:window.location.hash,search:window.location.search,width:window.innerWidth,height:window.innerHeight},t),document.referrer&&""!==document.referrer&&(t.referrer=document.referrer)),t},initialState=getPageData();function page(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState,e=arguments[1];switch(e.type){case EVENTS.PAGE:return Object.assign({},t,e.data);default:return t}}var pageView=function(t,e,n){return{type:EVENTS.PAGE_START,data:t,options:e,callback:n}};function pageMiddleware(r){return function(p){return function(e){return function(t){var n=t.type,c=t.data,u=t.options,s=t.callback;if(n===EVENTS.PAGE_START){var l=getIntegrationWithMethod(r(),"page");if(!l.length)return p.dispatch({type:EVENTS.PAGE,data:getPageData(),options:u}),p.dispatch({type:EVENTS.PAGE_COMPLETE});var d=0,f=!1;l.filter(function(t){var e=u&&u.integrations;return(e=e&&!1===e[t.NAMESPACE])&&console.log("ABORT PageView>>>>>",t.NAMESPACE,n),!e}).forEach(function(o){var i=o.NAMESPACE,a=0;!function t(){var e=p.getState(),n=getPageData(),r=_extends({},e,{options:u});if(!e.integrations[i].loaded)return console.log("try again",i),1e4<a?p.dispatch({type:"pageTimeout",name:i}):(a+=10,setTimeout(t,10)),!1;f||(p.dispatch({type:EVENTS.PAGE,data:n,options:u}),f=!0),o.page(n,r),p.dispatch({type:"page:"+i,data:n}),(d+=1)===l.length&&((e=getCallback(c,u,s))&&e(p),p.dispatch({type:EVENTS.PAGE_COMPLETE}))}()})}return e(t)}}}}function identifyMiddleware(r){return function(p){return function(e){return function(t){var n=t.type,a=t.userId,c=t.traits,u=t.options,s=t.callback;if(n===EVENTS.IDENTIFY_START){var l=getIntegrationWithMethod(r(),"identify");if(!l.length)return p.dispatch({type:EVENTS.IDENTIFY,userId:a,traits:c,options:u}),p.dispatch(_extends({type:EVENTS.IDENTIFY_COMPLETE}));var d=0,f=!1;l.filter(function(t){var e=u&&u.integrations;return(e=e&&!1===e[t.NAMESPACE])&&console.log("ABORT Identify >>>>>",t.NAMESPACE,n),!e}).forEach(function(r){var o=r.NAMESPACE,i=0;!function t(){var e=p.getState();if(!e.integrations[o].loaded)return 1e4<i?p.dispatch({type:"identifyTimeout",name:o}):(i+=10,setTimeout(t,10)),!1;if(f||(f=!0,p.dispatch({type:EVENTS.IDENTIFY,userId:a,traits:c,options:u})),r.identify(a,c,u),p.dispatch({type:"identify:"+o}),(d+=1)===l.length){var n=getCallback(c,u,s);n&&n(e),p.dispatch({type:EVENTS.IDENTIFY_COMPLETE})}}()})}return e(t)}}}}function getBrowserOS(){if("undefined"==typeof navigator)return!1;var t=navigator.appVersion;return-1!==t.indexOf("Win")?"Windows":-1!==t.indexOf("Mac")?"MacOS":-1!==t.indexOf("X11")?"UNIX":-1!==t.indexOf("Linux")?"Linux":"Unknown OS"}var osName=void 0,initialState$1={initialized:!1,app:null,version:null,os:{name:osName=getBrowserOS()},userAgent:"undefined"!=typeof navigator?navigator.userAgent:"node",library:{name:"analytics",version:"0.0.6"},campaign:{}};function context(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState$1,e=arguments[1],n=t.initialized,r=e.campaign;switch(e.type){case EVENTS.SET_CAMPAIGN:return _extends({},t,{campaign:r});default:return n?t:_extends({},initialState$1,t,{initialized:!0})}}function makeContext(n){return Object.keys(n).reduce(function(t,e){return"plugins"===e||"reducers"===e||(t[e]=n[e]),t},{})}var initialState$2={};function integrations(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState$2,e=arguments[1],n={};switch(e.type){case EVENTS.REGISTER_INTEGRATION:return n[e.name]={enabled:!0,loaded:!1,config:e.integration.config},_extends({},t,n);case EVENTS.INTEGRATION_LOADED:return(n={})[e.name]=_extends({},t[e.name],{loaded:!0}),_extends({},t,n);case EVENTS.INTEGRATION_FAILED:return n[e.name]=_extends({},t[e.name],{loaded:!1}),_extends({},t,n);case EVENTS.DISABLE_INTEGRATION:return n[e.name]=_extends({},t[e.name],{enabled:!1}),_extends({},t,n);default:return t}}var initialState$3={event:{},lastEvent:null,history:[]};function trackReducer(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState$3,e=arguments[1],n=e.data;switch(e.type){case EVENTS.TRACK:return e=t.lastEvent?t.event:n,console.log(">>>>>>>>>>>> state.lastEvent",t.lastEvent),_extends({},t,{event:n,lastEvent:e});default:return t}}var trackEvent=function(t,e,n,r){return{type:EVENTS.TRACK_START,eventName:t,data:e,options:n,callback:r}},uuid=function(){for(var t=[],e=0;e<256;e++)t[e]=(e<16?"0":"")+e.toString(16);e=4294967295*Math.random()|0;var n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,o=4294967295*Math.random()|0;return t[255&e]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[255&n]+t[n>>8&255]+"-"+t[n>>16&15|64]+t[n>>24&255]+"-"+t[63&r|128]+t[r>>8&255]+"-"+t[r>>16&255]+t[r>>24&255]+t[255&o]+t[o>>8&255]+t[o>>16&255]+t[o>>24&255]},ANALYTICS_ID="analytics_id",inBrowser$1="undefined"!=typeof window,setId=function(){var t=uuid();return inBrowser$1&&localStorage.setItem(ANALYTICS_ID,t),t},getId=function(){return inBrowser$1?localStorage.getItem(ANALYTICS_ID):null},initializeId=function(){return getId()||setId()},initialState$4={userId:null,anonymousId:initializeId(),traits:{}};function user(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState$4,e=arguments[1];switch(e.type){case EVENTS.IDENTIFY:return Object.assign({},t,{userId:e.userId,traits:_extends({},t.traits,e.traits)});default:return t}}var identify=function(t,e,n,r){return console.log("identify",t,e,n),{type:EVENTS.IDENTIFY_START,userId:t,traits:e,options:n,callback:r}};function analytics(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},e=t.plugins||[],n=t.reducers||{},o=e.reduce(function(t,e){return"function"!=typeof e&&e.NAMESPACE&&(t[e.NAMESPACE]=e),t},{}),r=function(){return o};e=e.reduce(function(t,e){return"function"==typeof e?t.concat(e):t},[]).concat([initialize,identifyMiddleware(r),trackMiddleware(r),pageMiddleware(r),dynamicMiddlewares]),r={context:context,user:user,page:page,track:trackReducer,integrations:integrations};var i=redux.compose;"undefined"!=typeof window&&(i=redux.compose);var a=redux.createStore(redux.combineReducers(_extends({},r,n)),{context:makeContext(t)},i(redux.applyMiddleware.apply(void 0,toConsumableArray(e))));a.dispatch({type:EVENTS.INITIALIZE});var c=Object.keys(o),u=0;return c.forEach(function(t,e){var n=o[t];if(a.dispatch({type:EVENTS.REGISTER_INTEGRATION,name:n.NAMESPACE,integration:n}),n&&n.initialize&&(n.initialize(n.config),n.loaded&&"function"==typeof n.loaded)){var r=0;!function t(){return 1e3<r?(a.dispatch({type:EVENTS.INTEGRATION_FAILED,name:n.NAMESPACE}),a.dispatch({type:"integration_failed:"+n.NAMESPACE}),!1):n.loaded()?(a.dispatch({type:EVENTS.INTEGRATION_LOADED,name:n.NAMESPACE}),a.dispatch({type:"integration_ready:"+n.NAMESPACE}),void((u+=1)===c.length&&a.dispatch({type:EVENTS.READY}))):(r++,setTimeout(t,10),!1)}()}}),c.length||setTimeout(function(){a.dispatch({type:EVENTS.READY})},0),{getState:function(t){var e=a.getState();return t?e[t]:e},dispatch:a.dispatch,subscribe:a.subscribe,replaceReducer:a.replaceReducer,track:function(t,e,n,r){return a.dispatch(trackEvent(t,e,n,r)),Promise.resolve()},page:function(t,e,n){return a.dispatch(pageView(t,e,n)),Promise.resolve()},identify:function(t,e,n,r){return a.dispatch(identify(t,e,n,r)),Promise.resolve()},user:function(){return a.getState().user},ready:function(t){var r="function"==typeof t&&t;if(!r)return!1;var e=function(n){return function(e){return function(t){return t.type===EVENTS.READY&&r(t,n),e(t)}}};return addMiddleware(e),function(){return removeMiddleware(e)}},on:function(r,t){var o="function"==typeof t&&t;if(!o)return!1;if("*"===r){var e=function(n){return function(e){return function(t){return o(t,n),e(t)}}};return addMiddleware(e),function(){removeMiddleware(e)}}var n=function(n){return function(e){return function(t){return t.type===r&&o(t,n),e(t)}}};return addMiddleware(n),function(){removeMiddleware(n)}},addIntegration:function(t){if("object"===(void 0===t?"undefined":_typeof(t))){var e={};e[t.NAMESPACE]=t,o=_extends({},o,e),console.log("add new integration dynamically",o)}a.dispatch({type:EVENTS.REGISTER_INTEGRATION,name:t.NAMESPACE,integration:t})}}}module.exports=function(t){return analytics(t)}; | ||
'use strict'; | ||
var redux = require('redux'); | ||
var analyticsUtils = require('analytics-utils'); | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
return typeof obj; | ||
} : function (obj) { | ||
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; | ||
}; | ||
var _extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
var toConsumableArray = function (arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
return arr2; | ||
} else { | ||
return Array.from(arr); | ||
} | ||
}; | ||
var dynamic = []; | ||
var dynamicMiddlewares = function dynamicMiddlewares(store) { | ||
return function (next) { | ||
return function (action) { | ||
var middlewareAPI = { | ||
getState: store.getState, | ||
dispatch: function dispatch(act) { | ||
return store.dispatch(act); | ||
} | ||
}; | ||
var chain = dynamic.map(function (middleware) { | ||
return middleware(middlewareAPI); | ||
}); | ||
return redux.compose.apply(undefined, toConsumableArray(chain))(next)(action); | ||
}; | ||
}; | ||
}; | ||
var addMiddleware = function addMiddleware() { | ||
var _dynamic; | ||
dynamic = (_dynamic = dynamic).concat.apply(_dynamic, arguments); | ||
}; | ||
var removeMiddleware = function removeMiddleware(middleware) { | ||
var index = dynamic.findIndex(function (d) { | ||
return d === middleware; | ||
}); | ||
if (index === -1) return; | ||
dynamic = [].concat(toConsumableArray(dynamic.slice(0, index)), toConsumableArray(dynamic.slice(index + 1))); | ||
}; | ||
var EVENTS = { | ||
INITIALIZE: 'analyticsInit', // 'analyticsInit' | ||
HANDLE_PARAMS: 'params', | ||
SET_CAMPAIGN: 'campaign', | ||
READY: 'ready', // 'analyticsReady' | ||
/* Integration actions */ | ||
REGISTER_INTEGRATION: 'integration_init', // 'integrationInit' | ||
INTEGRATION_LOADED: 'integration_ready', // 'integrationLoaded' | ||
INTEGRATION_FAILED: 'integration_failed', // 'integrationFailed' | ||
ENABLE_INTEGRATION: 'enable_integration', // 'integrationEnabled' | ||
DISABLE_INTEGRATION: 'disable_integration', // 'integrationDisabled' | ||
/* Page actions */ | ||
PAGE_START: 'page_init', // 'pageInit' | ||
PAGE: 'page', // 'page' | ||
PAGE_COMPLETE: 'page_complete', // 'pageCompleted' | ||
PAGE_ABORT: 'page_abort', // 'pageAborted' // TODO add this | ||
/* Track actions */ | ||
TRACK_START: 'track_init', // 'trackInit' | ||
TRACK: 'track', // 'track' | ||
TRACK_COMPLETE: 'track_complete', // 'trackCompleted' | ||
TRACK_ABORT: 'track_abort', // 'trackAborted' | ||
/* Identify actions */ | ||
IDENTIFY_START: 'identify_init', // 'identifyInit' | ||
IDENTIFY: 'identify', // 'identify' | ||
IDENTIFY_COMPLETE: 'identify_complete', // 'identifyCompleted' | ||
IDENTIFY_ABORTED: 'identify_abort' // 'identifyAborted' // TODO add this | ||
}; | ||
// Middleware runs during EVENTS.INITIALIZE | ||
var initialize = function initialize(store) { | ||
return function (next) { | ||
return function (action) { | ||
if (action.type === EVENTS.INITIALIZE) { | ||
var params = analyticsUtils.paramsParse(); | ||
if (params) { | ||
store.dispatch({ | ||
type: EVENTS.HANDLE_PARAMS, | ||
params: params | ||
}); | ||
var utmParams = Object.keys(params).reduce(function (arr, key) { | ||
if (key.match(/utm_/)) arr[key] = params[key]; | ||
return arr; | ||
}, {}); | ||
// if url has utm params | ||
if (Object.keys(utmParams).length) { | ||
store.dispatch({ | ||
type: EVENTS.SET_CAMPAIGN, | ||
campaign: utmParams | ||
}); | ||
} | ||
} | ||
// handle user indenfication here | ||
// handle initial visitor source here | ||
} | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
function formatPayload(eventName, payload) { | ||
var data = {}; | ||
if ((typeof eventName === 'undefined' ? 'undefined' : _typeof(eventName)) === 'object') { | ||
data = eventName; | ||
} else if ((typeof payload === 'undefined' ? 'undefined' : _typeof(payload)) === 'object') { | ||
data = payload; | ||
} | ||
// why did I do this? | ||
// if (typeof eventName === 'string') { | ||
// data.eventName = eventName | ||
// } | ||
return data; | ||
} | ||
function getIntegrationWithMethod(integrations, method) { | ||
return Object.keys(integrations).reduce(function (arr, plugin) { | ||
var int = integrations[plugin]; | ||
// console.log('int', int) | ||
return int[method] ? arr.concat(int) : arr; | ||
}, []); | ||
} | ||
function getCallback() { | ||
for (var i = 0; i < arguments.length; ++i) { | ||
if (typeof arguments[i] === 'function') { | ||
return arguments[i]; | ||
} | ||
} | ||
return false; | ||
} | ||
function trackMiddleware(getIntegrations) { | ||
return function (store) { | ||
return function (next) { | ||
return function (action) { | ||
var type = action.type, | ||
eventName = action.eventName, | ||
data = action.data, | ||
options = action.options, | ||
callback = action.callback; | ||
if (type === EVENTS.TRACK_START) { | ||
// format data payload | ||
var payload = formatPayload(eventName, data); | ||
// setup data | ||
var dispatchData = { | ||
eventName: eventName, | ||
payload: payload, | ||
options: options | ||
// if abort === true stop the rest | ||
};if (action.abort) { | ||
store.dispatch(_extends({ type: EVENTS.TRACK_ABORT }, dispatchData)); | ||
return next(action); | ||
} | ||
var trackCalls = getIntegrationWithMethod(getIntegrations(), 'track'); | ||
// No tracking middleware attached | ||
if (!trackCalls.length) { | ||
store.dispatch(_extends({ type: EVENTS.TRACK }, dispatchData)); | ||
return store.dispatch(_extends({ type: EVENTS.TRACK_COMPLETE }, dispatchData)); | ||
} | ||
var trackCount = 0; | ||
var hasRan = false; | ||
/* Filter out disabled integrations */ | ||
trackCalls.filter(function (provider) { | ||
var integrations = options && options.integrations; | ||
var disabled = integrations && integrations[provider.NAMESPACE] === false; | ||
if (disabled) { | ||
console.log('ABORT TRACK>>>>>', provider.NAMESPACE, type); | ||
} | ||
return !disabled; | ||
/* Handle all .track calls */ | ||
}).forEach(function (provider) { | ||
var NAMESPACE = provider.NAMESPACE; | ||
// check for ready state on integration and recursively call til rdy | ||
var timeoutMax = 10000; | ||
var timer = 0; | ||
var runTrackWhenLibraryLoaded = function runTrackWhenLibraryLoaded() { | ||
var state = store.getState(); | ||
// enrich options | ||
var enrichedOptions = _extends({}, state, { options: options }); | ||
var integrationLoaded = state.integrations[NAMESPACE].loaded; | ||
if (!integrationLoaded) { | ||
// TODO: set max try limit and add calls to local queue on fail | ||
if (timer > timeoutMax) { | ||
store.dispatch(_extends({}, dispatchData, { type: 'trackingTimeout' })); | ||
// TODO: save to queue | ||
return false; | ||
} | ||
timer = timer + 10; | ||
setTimeout(runTrackWhenLibraryLoaded, 10); | ||
return false; | ||
} | ||
/* run integration[x] .track function */ | ||
provider.track(eventName, payload, enrichedOptions, state); | ||
if (state.context.debug) { | ||
console.log('DEBUG IS ONNNNNNNNNN'); | ||
} | ||
if (!hasRan) { | ||
store.dispatch(_extends({ type: EVENTS.TRACK }, dispatchData)); | ||
hasRan = true; | ||
} | ||
// dispatch call for middlewares | ||
store.dispatch(_extends({ | ||
type: 'track:' + NAMESPACE, | ||
integration: NAMESPACE | ||
}, dispatchData)); | ||
// increment success counter | ||
trackCount = trackCount + 1; | ||
// all track calls complete | ||
if (trackCount === trackCalls.length) { | ||
var cb = getCallback(data, options, callback); | ||
if (cb) cb(state); | ||
// dispatch completion event for middlewares | ||
store.dispatch(_extends({ type: EVENTS.TRACK_COMPLETE }, dispatchData)); | ||
} | ||
}; | ||
runTrackWhenLibraryLoaded(); | ||
}); | ||
} | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
} | ||
var getPageData = function getPageData() { | ||
var pageData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
if (!analyticsUtils.inBrowser) { | ||
return pageData; | ||
} | ||
var _document = document, | ||
title = _document.title, | ||
referrer = _document.referrer; | ||
var _window = window, | ||
location = _window.location, | ||
innerWidth = _window.innerWidth, | ||
innerHeight = _window.innerHeight; | ||
var hash = location.hash, | ||
search = location.search, | ||
pathname = location.pathname, | ||
href = location.href; | ||
var page = _extends({ | ||
title: title, | ||
url: href, | ||
path: pathname, | ||
hash: hash, | ||
search: search, | ||
width: innerWidth, | ||
height: innerHeight | ||
}, pageData); | ||
if (referrer && referrer !== '') { | ||
page.referrer = referrer; | ||
} | ||
return page; | ||
}; | ||
// initialState Page Data | ||
var initialState = getPageData(); | ||
// page reducer | ||
function page() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; | ||
var action = arguments[1]; | ||
switch (action.type) { | ||
case EVENTS.PAGE: | ||
return Object.assign({}, state, action.data); | ||
default: | ||
return state; | ||
} | ||
} | ||
var pageView = function pageView(data, options, callback) { | ||
return { | ||
type: EVENTS.PAGE_START, | ||
data: data, | ||
options: options, | ||
callback: callback | ||
}; | ||
}; | ||
function pageMiddleware(getIntegrations) { | ||
return function (store) { | ||
return function (next) { | ||
return function (action) { | ||
var type = action.type, | ||
data = action.data, | ||
options = action.options, | ||
callback = action.callback; | ||
if (type === EVENTS.PAGE_START) { | ||
var pageCalls = getIntegrationWithMethod(getIntegrations(), 'page'); | ||
// No page middleware attached | ||
if (!pageCalls.length) { | ||
store.dispatch({ | ||
type: EVENTS.PAGE, | ||
data: _extends({}, getPageData(), data), | ||
options: options | ||
}); | ||
return store.dispatch({ | ||
type: EVENTS.PAGE_COMPLETE | ||
}); | ||
} | ||
var count = 0; | ||
var hasRan = false; | ||
/* Handle all .page calls syncronously */ | ||
pageCalls.filter(function (provider) { | ||
var integrations = options && options.integrations; | ||
var disabled = integrations && integrations[provider.NAMESPACE] === false; | ||
if (disabled) { | ||
console.log('ABORT PageView>>>>>', provider.NAMESPACE, type); | ||
} | ||
return !disabled; | ||
}).forEach(function (provider) { | ||
var NAMESPACE = provider.NAMESPACE; | ||
var timeoutMax = 10000; | ||
var timer = 0; | ||
// TODO refactor with wait until | ||
// https://github.com/mozilla/gecko-dev/blob/master/devtools/client/shared/redux/middleware/wait-service.js | ||
// https://jlongster.com/Two-Weird-Tricks-with-Redux | ||
var runWhenScriptLoaded = function runWhenScriptLoaded() { | ||
var state = store.getState(); | ||
var pageData = _extends({}, getPageData(), data); | ||
var enrichedOptions = _extends({}, state, { options: options }); | ||
if (!state.integrations[NAMESPACE].loaded) { | ||
console.log('try again page', NAMESPACE); | ||
// TODO: set max try limit and add calls to local queue on fail | ||
if (timer > timeoutMax) { | ||
store.dispatch({ | ||
type: 'pageTimeout', | ||
name: NAMESPACE | ||
}); | ||
// TODO: save to queue | ||
return false; | ||
} | ||
timer = timer + 10; | ||
// TODO: set max try limit and add calls to local queue on fail | ||
setTimeout(runWhenScriptLoaded, 10); | ||
return false; | ||
} | ||
/* Run .page dispatch once. Namespaced calls run below */ | ||
if (!hasRan) { | ||
store.dispatch({ | ||
type: EVENTS.PAGE, | ||
data: pageData, | ||
options: options | ||
}); | ||
hasRan = true; | ||
} | ||
/* run integration[x] .page function */ | ||
provider.page(pageData, enrichedOptions); | ||
/* Run Namespaced .page calls */ | ||
store.dispatch({ | ||
type: 'page:' + NAMESPACE, | ||
data: pageData | ||
}); | ||
// increment success counter | ||
count = count + 1; | ||
// all track calls complete | ||
if (count === pageCalls.length) { | ||
// dispatch completion event for middlewares | ||
store.dispatch({ | ||
type: EVENTS.PAGE_COMPLETE | ||
}); | ||
var cb = getCallback(data, options, callback); | ||
if (cb) { | ||
cb(store); | ||
} | ||
} | ||
}; | ||
runWhenScriptLoaded(); | ||
}); | ||
} | ||
// resume | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
} | ||
function identifyMiddleware(getIntegrations) { | ||
return function (store) { | ||
return function (next) { | ||
return function (action) { | ||
var type = action.type, | ||
userId = action.userId, | ||
traits = action.traits, | ||
options = action.options, | ||
callback = action.callback; | ||
if (type === EVENTS.IDENTIFY_START) { | ||
var identifyCalls = getIntegrationWithMethod(getIntegrations(), 'identify'); | ||
// No identify middleware attached | ||
if (!identifyCalls.length) { | ||
store.dispatch({ | ||
type: EVENTS.IDENTIFY, | ||
userId: userId, | ||
traits: traits, | ||
options: options | ||
// callback: callback | ||
}); | ||
return store.dispatch(_extends({ type: EVENTS.IDENTIFY_COMPLETE })); | ||
} | ||
var count = 0; | ||
var hasRan = false; | ||
// console.log('identifyCalls', identifyCalls) | ||
/* Filter out disabled integrations */ | ||
identifyCalls.filter(function (provider) { | ||
var integrations = options && options.integrations; | ||
var disabled = integrations && integrations[provider.NAMESPACE] === false; | ||
if (disabled) { | ||
console.log('ABORT Identify >>>>>', provider.NAMESPACE, type); | ||
} | ||
return !disabled; | ||
/* Handle all .identify calls */ | ||
}).forEach(function (provider) { | ||
var NAMESPACE = provider.NAMESPACE; | ||
// check for ready state on integration and recursively call til rdy | ||
var timeoutMax = 10000; | ||
var timer = 0; | ||
var runWhenScriptLoaded = function runWhenScriptLoaded() { | ||
var state = store.getState(); | ||
var integrationLoaded = state.integrations[NAMESPACE].loaded; | ||
if (!integrationLoaded) { | ||
// TODO: set max try limit and add calls to local queue on fail | ||
if (timer > timeoutMax) { | ||
store.dispatch({ | ||
type: 'identifyTimeout', | ||
name: NAMESPACE | ||
}); | ||
// TODO: save to queue | ||
return false; | ||
} | ||
timer = timer + 10; | ||
setTimeout(runWhenScriptLoaded, 10); | ||
return false; | ||
} | ||
/* Run .identify dispatch once. Each Namespaced calls run below */ | ||
if (!hasRan) { | ||
hasRan = true; | ||
store.dispatch({ | ||
type: EVENTS.IDENTIFY, | ||
userId: userId, | ||
traits: traits, | ||
options: options | ||
// callback: callback | ||
}); | ||
} | ||
/* run integration[x] .identify function */ | ||
provider.identify(userId, traits, options); | ||
/* Run namespaced .identify calls */ | ||
store.dispatch({ type: 'identify:' + NAMESPACE }); | ||
// increment success counter | ||
count = count + 1; | ||
// all identify calls complete | ||
if (count === identifyCalls.length) { | ||
var cb = getCallback(traits, options, callback); | ||
if (cb) cb(state); | ||
// dispatch completion event for middlewares | ||
store.dispatch({ | ||
type: EVENTS.IDENTIFY_COMPLETE | ||
}); | ||
} | ||
}; | ||
runWhenScriptLoaded(); | ||
}); | ||
} | ||
// resume | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
} | ||
/* | ||
The MIT License (MIT) | ||
Copyright (c) 2016 CoderPuppy | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. | ||
*/ | ||
function getBrowserOS() { | ||
if (!analyticsUtils.inBrowser) { | ||
return false; | ||
} | ||
var os = navigator.appVersion; | ||
if (os.indexOf('Win') !== -1) return 'Windows'; | ||
if (os.indexOf('Mac') !== -1) return 'MacOS'; | ||
if (os.indexOf('X11') !== -1) return 'UNIX'; | ||
if (os.indexOf('Linux') !== -1) return 'Linux'; | ||
// default | ||
return 'Unknown OS'; | ||
} | ||
/* global true false */ | ||
var osName = void 0; | ||
{ | ||
osName = getBrowserOS(); | ||
} | ||
var initialState$1 = { | ||
initialized: false, | ||
app: null, | ||
version: null, | ||
debug: false, | ||
os: { | ||
name: osName | ||
}, | ||
userAgent: analyticsUtils.inBrowser ? navigator.userAgent : 'node', // https://github.com/bestiejs/platform.js | ||
library: { | ||
name: 'analytics', | ||
// TODO fix version number. npm run publish:patch has wrong version | ||
version: "0.0.7" | ||
}, | ||
campaign: {} | ||
// context reducer | ||
};function context() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$1; | ||
var action = arguments[1]; | ||
var initialized = state.initialized; | ||
var type = action.type, | ||
campaign = action.campaign; | ||
switch (type) { | ||
case EVENTS.SET_CAMPAIGN: | ||
return _extends({}, state, { campaign: campaign }); | ||
default: | ||
if (!initialized) { | ||
return _extends({}, initialState$1, state, { initialized: true }); | ||
} | ||
return state; | ||
} | ||
} | ||
// Pull plugins and reducers off intital config | ||
function makeContext(config) { | ||
return Object.keys(config).reduce(function (accumulator, current) { | ||
if (current === 'plugins' || current === 'reducers') { | ||
return accumulator; | ||
} | ||
accumulator[current] = config[current]; | ||
return accumulator; | ||
}, {}); | ||
} | ||
var initialState$2 = {}; | ||
function integrations() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$2; | ||
var action = arguments[1]; | ||
var newState = {}; | ||
switch (action.type) { | ||
case EVENTS.REGISTER_INTEGRATION: | ||
// console.log('REGISTER_INTEGRATION', action.name) | ||
// console.log('action.integration', action.integration) | ||
newState[action.name] = { | ||
enabled: true, | ||
loaded: false, // script loaded = false | ||
config: action.integration.config | ||
}; | ||
return _extends({}, state, newState); | ||
case EVENTS.INTEGRATION_LOADED: | ||
// console.log('INTEGRATION_LOADED', action.name) | ||
// TODO clean up | ||
var loaded = {}; | ||
loaded[action.name] = _extends({}, state[action.name], { loaded: true }); | ||
// console.log('LOADED OBJECT', loaded) | ||
return _extends({}, state, loaded); | ||
case EVENTS.INTEGRATION_FAILED: | ||
// console.log('INTEGRATION_FAILED', action.name) | ||
// TODO clean up | ||
newState[action.name] = _extends({}, state[action.name], { loaded: false }); | ||
return _extends({}, state, newState); | ||
case EVENTS.DISABLE_INTEGRATION: | ||
// console.log('DISABLE_INTEGRATION', action.name) | ||
newState[action.name] = _extends({}, state[action.name], { enabled: false }); | ||
return _extends({}, state, newState); | ||
default: | ||
return state; | ||
} | ||
} | ||
// Track State | ||
var initialState$3 = { | ||
event: {}, | ||
lastEvent: null, | ||
history: [] | ||
// track reducer | ||
};function trackReducer() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$3; | ||
var action = arguments[1]; | ||
var type = action.type, | ||
data = action.data, | ||
eventName = action.eventName; | ||
switch (type) { | ||
case EVENTS.TRACK: | ||
var l = !state.lastEvent ? data : state.event; | ||
console.log('>>>>>>>>>>>> state.lastEvent', state.lastEvent); | ||
// TODO fix last event. 9/25 Still need to fix | ||
return _extends({}, state, { | ||
event: data, | ||
lastEvent: l | ||
}); | ||
// todo push events to history | ||
default: | ||
return state; | ||
} | ||
} | ||
// // Set tracking data for third party plugins | ||
var trackEvent = function trackEvent(eventName, data, options, callback) { | ||
return { | ||
type: EVENTS.TRACK_START, | ||
eventName: eventName, | ||
data: data, | ||
options: options, | ||
callback: callback | ||
}; | ||
}; | ||
// TODO come up with ls keys | ||
var ANALYTICS_ID = 'analytics_id'; | ||
var setId = function setId() { | ||
var id = analyticsUtils.uuid(); | ||
if (!analyticsUtils.inBrowser) { | ||
return id; | ||
} | ||
// TODO refactor with persistance options https://github.com/harrysolovay/state-mint/tree/master/src/persistence/methods | ||
localStorage.setItem(ANALYTICS_ID, id); | ||
return id; | ||
}; | ||
var getId = function getId() { | ||
if (!analyticsUtils.inBrowser) { | ||
return null; | ||
} | ||
return localStorage.getItem(ANALYTICS_ID); | ||
}; | ||
var initializeId = function initializeId() { | ||
var id = getId(); | ||
return id || setId(); | ||
}; | ||
// user state | ||
var initialState$4 = { | ||
userId: null, | ||
anonymousId: initializeId(), | ||
traits: {} | ||
// Suggested Traits | ||
/* | ||
{ | ||
address: { | ||
city: null, | ||
country: null, | ||
postalCode: null, | ||
state: null, | ||
street: null | ||
}, | ||
age: 20 | ||
avatar: 'http://url.com/thumbnail.jpg' | ||
birthday: 122321212, | ||
createdAt: 1111111, | ||
description: 'Description of the user', | ||
email: 'email@email.com', | ||
firstName: 'david', | ||
lastName: 'wells', | ||
name: 'david wells', | ||
gender: 'male', | ||
id: 'String Unique ID in your database for a user', | ||
phone: '727-777-8888', | ||
title: 'boss ceo', | ||
username: 'davidwells', | ||
} | ||
*/ | ||
// user reducer | ||
};function user() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$4; | ||
var action = arguments[1]; | ||
switch (action.type) { | ||
case EVENTS.IDENTIFY: | ||
return Object.assign({}, state, { | ||
userId: action.userId, | ||
traits: _extends({}, state.traits, action.traits) | ||
}); | ||
default: | ||
return state; | ||
} | ||
} | ||
// Set tracking data for third party plugins | ||
var identify = function identify(userId, traits, options, callback) { | ||
console.log('identify', userId, traits, options); | ||
return { | ||
type: EVENTS.IDENTIFY_START, | ||
userId: userId, | ||
traits: traits, | ||
options: options, | ||
callback: callback | ||
}; | ||
}; | ||
// Only way commonJS will work | ||
module.exports = function (config) { | ||
return analytics(config); | ||
}; | ||
function analytics() { | ||
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var plugins = config.plugins || []; | ||
var customReducers = config.reducers || {}; | ||
/* Custom analytic integrations */ | ||
var customIntegrations = plugins.reduce(function (obj, p) { | ||
if (typeof p !== 'function' && p.NAMESPACE) { | ||
obj[p.NAMESPACE] = p; | ||
return obj; | ||
} | ||
return obj; | ||
}, {}); | ||
/* Custom redux middleware */ | ||
var customMiddlewares = plugins.reduce(function (arr, p) { | ||
if (typeof p === 'function') { | ||
return arr.concat(p); | ||
} | ||
return arr; | ||
}, []); | ||
{ | ||
console.log('customIntegrations', customIntegrations); | ||
console.log('customMiddlewares', customMiddlewares); | ||
} | ||
/* plugin methods(functions) must be kept out of state. thus they live here */ | ||
var getIntegrations = function getIntegrations() { | ||
return customIntegrations; | ||
}; | ||
var middlewares = customMiddlewares.concat([ | ||
// core middlewares | ||
initialize, identifyMiddleware(getIntegrations), trackMiddleware(getIntegrations), pageMiddleware(getIntegrations), dynamicMiddlewares]); | ||
// initial analytics state keys | ||
var coreReducers = { | ||
context: context, | ||
user: user, | ||
page: page, | ||
track: trackReducer, | ||
integrations: integrations | ||
}; | ||
var composeEnhancers = redux.compose; | ||
if (analyticsUtils.inBrowser) { | ||
var withDevTools = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || redux.compose; | ||
composeEnhancers = withDevTools; | ||
} | ||
/* Create analytics store! */ | ||
var store = redux.createStore(redux.combineReducers(_extends({}, coreReducers, customReducers)), | ||
// optional default config overides by user | ||
{ | ||
context: makeContext(config) | ||
}, | ||
// register middleware & plugins used | ||
composeEnhancers(redux.applyMiddleware.apply(undefined, toConsumableArray(middlewares)))); | ||
// Init analytics | ||
store.dispatch({ | ||
type: EVENTS.INITIALIZE | ||
}); | ||
// Register, load, and onReady custom integrations | ||
var providers = Object.keys(customIntegrations); | ||
providers.forEach(function (int, i) { | ||
var provider = customIntegrations[int]; | ||
store.dispatch({ | ||
type: EVENTS.REGISTER_INTEGRATION, | ||
name: provider.NAMESPACE, | ||
integration: provider | ||
}); | ||
// initialize integrations | ||
if (provider && provider.initialize) { | ||
// load scripts etc. | ||
provider.initialize(provider.config); | ||
// run check for loaded here and then dispatch loaded events | ||
if (provider.loaded && typeof provider.loaded === 'function') { | ||
checkForScriptReady({ maxRetries: 1000 }, store, provider); | ||
} | ||
} | ||
}); | ||
// No providers found. Trigger ready listeners | ||
if (!providers.length) { | ||
setTimeout(function () { | ||
store.dispatch({ | ||
type: EVENTS.READY | ||
}); | ||
}, 0); | ||
} | ||
{ | ||
console.log('intialize state', store.getState()); | ||
} | ||
return { | ||
// Get all state or state by key | ||
getState: function getState(key) { | ||
var state = store.getState(); | ||
if (key) { | ||
// TODO add dot notation and grab deeper values | ||
return state[key]; | ||
} | ||
return state; | ||
}, | ||
dispatch: store.dispatch, | ||
subscribe: store.subscribe, | ||
replaceReducer: store.replaceReducer, | ||
// track custom event | ||
track: function track(eventName, payload, options, callback) { | ||
store.dispatch(trackEvent(eventName, payload, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
return Promise.resolve(); | ||
}, | ||
// trigger page view | ||
page: function page$$1(data, options, callback) { | ||
store.dispatch(pageView(data, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
return Promise.resolve(); | ||
}, | ||
// set user data | ||
identify: function identify$$1(userId, data, options, callback) { | ||
store.dispatch(identify(userId, data, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
return Promise.resolve(); | ||
}, | ||
// get user data | ||
user: function user$$1() { | ||
// TODO add key to input and allow for pulling back specific values | ||
return store.getState().user; | ||
}, | ||
// analtyics.ready all integrations ready | ||
ready: function ready(cb) { | ||
var callback = typeof cb === 'function' ? cb : false; | ||
if (!callback) return false; | ||
var readyMiddleware = function readyMiddleware(store) { | ||
return function (next) { | ||
return function (action) { | ||
if (action.type === EVENTS.READY) { | ||
callback(action, store); | ||
} | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
addMiddleware(readyMiddleware); | ||
return function () { | ||
return removeMiddleware(readyMiddleware); | ||
}; | ||
}, | ||
/* USE .on WITH GREAT CAUTION */ | ||
on: function on(name, cb) { | ||
var callback = typeof cb === 'function' ? cb : false; | ||
if (!callback) return false; | ||
// Subscribe to EVERYTHING | ||
if (name === '*') { | ||
/* // store subscribe works but won't give current action context | ||
return store.subscribe(() => { | ||
callback(action, store) | ||
}) | ||
*/ | ||
var globalListener = function globalListener(store) { | ||
return function (next) { | ||
return function (action) { | ||
// do something on every action * | ||
callback(action, store); | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
// will add middleware to existing chain | ||
addMiddleware(globalListener); | ||
// calling this will destroy listener & remove middleware | ||
return function () { | ||
removeMiddleware(globalListener); | ||
}; | ||
} | ||
var listener = function listener(store) { | ||
return function (next) { | ||
return function (action) { | ||
if (action.type === name) { | ||
// TODO finalize values passed back | ||
callback(action, store); | ||
} | ||
return next(action); | ||
}; | ||
}; | ||
}; | ||
// will add middleware to existing chain | ||
addMiddleware(listener); | ||
// calling this will destroy listener & remove middleware | ||
return function () { | ||
removeMiddleware(listener); | ||
}; | ||
}, | ||
// TODO decide if this is good or bad ⊂◉‿◉つ. Exposing publicly could be bad | ||
addIntegration: function addIntegration(t) { | ||
// TODO if it stays, state loaded needs to be set. Re REGISTER_INTEGRATION above | ||
// validate integration | ||
if ((typeof t === 'undefined' ? 'undefined' : _typeof(t)) === 'object') { | ||
var newIntergration = {}; | ||
newIntergration[t.NAMESPACE] = t; | ||
customIntegrations = _extends({}, customIntegrations, newIntergration); | ||
console.log('add new integration dynamically', customIntegrations); | ||
} | ||
// then add it, and init state key | ||
store.dispatch({ | ||
type: EVENTS.REGISTER_INTEGRATION, | ||
name: t.NAMESPACE, | ||
integration: t | ||
}); | ||
} | ||
}; | ||
} | ||
// Check for script loaded on page then dispatch actions | ||
function checkForScriptReady(config, store, provider, retryCount) { | ||
retryCount = retryCount || 0; | ||
var maxRetries = config.maxRetries; | ||
if (retryCount > maxRetries) { | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_FAILED, | ||
name: provider.NAMESPACE | ||
}); | ||
store.dispatch({ | ||
type: 'integration_failed:' + provider.NAMESPACE | ||
}); | ||
return false; | ||
} | ||
// check if loaded | ||
if (!provider.loaded() && retryCount <= maxRetries) { | ||
setTimeout(function () { | ||
checkForScriptReady(config, store, provider, ++retryCount); | ||
}, 10); | ||
return false; | ||
} | ||
// script isLoaded, dispatch generic event | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_LOADED, | ||
name: provider.NAMESPACE | ||
}); | ||
// dispatch namespaced event | ||
store.dispatch({ | ||
type: 'integration_ready:' + provider.NAMESPACE | ||
}); | ||
// dispatch ready when all integrations load | ||
var _store$getState = store.getState(), | ||
integrations$$1 = _store$getState.integrations; | ||
var everythingLoaded = Object.keys(integrations$$1).reduce(function (acc, curr) { | ||
if (!integrations$$1[curr].loaded) { | ||
return false; | ||
} | ||
return acc; | ||
}, true); | ||
if (everythingLoaded) { | ||
// all integrations loaded. do stuff | ||
store.dispatch({ | ||
type: EVENTS.READY | ||
}); | ||
} | ||
} |
import { compose, createStore, combineReducers, applyMiddleware } from 'redux'; | ||
import { paramsParse, inBrowser, uuid } from 'analytics-utils'; | ||
@@ -95,46 +96,2 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { | ||
function getUrlParams(url) { | ||
if (typeof window === 'undefined') { | ||
return {}; | ||
} | ||
var urlParams = {}; | ||
var pattern = /([^&=]+)=?([^&]*)/g; | ||
var params = void 0; | ||
var matches = void 0; | ||
if (url) { | ||
var p = url.match(/\?(.*)/ // query | ||
);params = p && p[1] ? p[1].split('#')[0] : ''; | ||
} else { | ||
params = window.location.search.substring(1); | ||
} | ||
if (!params) return false; | ||
while (matches = pattern.exec(params)) { | ||
// eslint-disable-line | ||
if (matches[1].indexOf('[') == '-1') { | ||
// eslint-disable-line | ||
urlParams[decode(matches[1])] = decode(matches[2]); | ||
} else { | ||
var start = matches[1].indexOf('['); | ||
var nested = matches[1].slice(start + 1, matches[1].indexOf(']', start)); | ||
var key = decode(matches[1].slice(0, start)); | ||
if (_typeof(urlParams[key]) !== 'object') { | ||
urlParams[decode(key)] = {}; | ||
urlParams[decode(key)].length = 0; | ||
} | ||
if (nested) { | ||
urlParams[decode(key)][decode(nested)] = decode(matches[2]); | ||
} else { | ||
Array.prototype.push.call(urlParams[decode(key)], decode(matches[2])); | ||
} | ||
} | ||
} | ||
return urlParams; | ||
} | ||
function decode(s) { | ||
return decodeURIComponent(s).replace(/\+/g, ' '); | ||
} | ||
// Middleware runs during EVENTS.INITIALIZE | ||
@@ -145,3 +102,3 @@ var initialize = function initialize(store) { | ||
if (action.type === EVENTS.INITIALIZE) { | ||
var params = getUrlParams(); | ||
var params = paramsParse(); | ||
if (params) { | ||
@@ -156,6 +113,6 @@ store.dispatch({ | ||
return arr; | ||
}, {} | ||
}, {}); | ||
// if url has utm params | ||
);if (Object.keys(utmParams).length) { | ||
if (Object.keys(utmParams).length) { | ||
store.dispatch({ | ||
@@ -219,5 +176,5 @@ type: EVENTS.SET_CAMPAIGN, | ||
// format data payload | ||
var payload = formatPayload(eventName, data | ||
var payload = formatPayload(eventName, data); | ||
// setup data | ||
);var dispatchData = { | ||
var dispatchData = { | ||
eventName: eventName, | ||
@@ -233,5 +190,5 @@ payload: payload, | ||
var trackCalls = getIntegrationWithMethod(getIntegrations(), 'track' | ||
var trackCalls = getIntegrationWithMethod(getIntegrations(), 'track'); | ||
// No tracking middleware attached | ||
);if (!trackCalls.length) { | ||
if (!trackCalls.length) { | ||
store.dispatch(_extends({ type: EVENTS.TRACK }, dispatchData)); | ||
@@ -260,5 +217,5 @@ return store.dispatch(_extends({ type: EVENTS.TRACK_COMPLETE }, dispatchData)); | ||
var runTrackWhenLibraryLoaded = function runTrackWhenLibraryLoaded() { | ||
var state = store.getState | ||
var state = store.getState(); | ||
// enrich options | ||
();var enrichedOptions = _extends({}, state, { options: options }); | ||
var enrichedOptions = _extends({}, state, { options: options }); | ||
@@ -269,5 +226,5 @@ var integrationLoaded = state.integrations[NAMESPACE].loaded; | ||
if (timer > timeoutMax) { | ||
store.dispatch(_extends({}, dispatchData, { type: 'trackingTimeout' }) | ||
store.dispatch(_extends({}, dispatchData, { type: 'trackingTimeout' })); | ||
// TODO: save to queue | ||
);return false; | ||
return false; | ||
} | ||
@@ -280,4 +237,8 @@ timer = timer + 10; | ||
/* run integration[x] .track function */ | ||
provider.track(eventName, payload, enrichedOptions); | ||
provider.track(eventName, payload, enrichedOptions, state); | ||
if (state.context.debug) { | ||
console.log('DEBUG IS ONNNNNNNNNN'); | ||
} | ||
if (!hasRan) { | ||
@@ -291,11 +252,11 @@ store.dispatch(_extends({ type: EVENTS.TRACK }, dispatchData)); | ||
integration: NAMESPACE | ||
}, dispatchData) | ||
}, dispatchData)); | ||
// increment success counter | ||
);trackCount = trackCount + 1; | ||
trackCount = trackCount + 1; | ||
// all track calls complete | ||
if (trackCount === trackCalls.length) { | ||
var cb = getCallback(data, options, callback); | ||
if (cb) cb(state | ||
if (cb) cb(state); | ||
// dispatch completion event for middlewares | ||
);store.dispatch(_extends({ type: EVENTS.TRACK_COMPLETE }, dispatchData)); | ||
store.dispatch(_extends({ type: EVENTS.TRACK_COMPLETE }, dispatchData)); | ||
} | ||
@@ -312,4 +273,2 @@ }; | ||
var inBrowser = typeof window !== 'undefined'; | ||
var getPageData = function getPageData() { | ||
@@ -319,16 +278,27 @@ var pageData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
if (!inBrowser) { | ||
// in node, return | ||
return pageData; | ||
} | ||
var _document = document, | ||
title = _document.title, | ||
referrer = _document.referrer; | ||
var _window = window, | ||
location = _window.location, | ||
innerWidth = _window.innerWidth, | ||
innerHeight = _window.innerHeight; | ||
var hash = location.hash, | ||
search = location.search, | ||
pathname = location.pathname, | ||
href = location.href; | ||
var page = _extends({ | ||
title: document.title, | ||
url: window.location.href, | ||
path: window.location.pathname, | ||
hash: window.location.hash, | ||
search: window.location.search, | ||
width: window.innerWidth, | ||
height: window.innerHeight | ||
title: title, | ||
url: href, | ||
path: pathname, | ||
hash: hash, | ||
search: search, | ||
width: innerWidth, | ||
height: innerHeight | ||
}, pageData); | ||
if (document.referrer && document.referrer !== '') { | ||
page.referrer = document.referrer; | ||
if (referrer && referrer !== '') { | ||
page.referrer = referrer; | ||
} | ||
@@ -339,6 +309,6 @@ return page; | ||
// initialState Page Data | ||
var initialState = getPageData | ||
var initialState = getPageData(); | ||
// page reducer | ||
();function page() { | ||
function page() { | ||
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; | ||
@@ -374,8 +344,8 @@ var action = arguments[1]; | ||
if (type === EVENTS.PAGE_START) { | ||
var pageCalls = getIntegrationWithMethod(getIntegrations(), 'page' | ||
var pageCalls = getIntegrationWithMethod(getIntegrations(), 'page'); | ||
// No page middleware attached | ||
);if (!pageCalls.length) { | ||
if (!pageCalls.length) { | ||
store.dispatch({ | ||
type: EVENTS.PAGE, | ||
data: getPageData(), | ||
data: _extends({}, getPageData(), data), | ||
options: options | ||
@@ -403,17 +373,20 @@ }); | ||
var timer = 0; | ||
// TODO refactor with wait until | ||
// https://github.com/mozilla/gecko-dev/blob/master/devtools/client/shared/redux/middleware/wait-service.js | ||
// https://jlongster.com/Two-Weird-Tricks-with-Redux | ||
var runWhenScriptLoaded = function runWhenScriptLoaded() { | ||
var state = store.getState(); | ||
var pageData = getPageData(); | ||
var pageData = _extends({}, getPageData(), data); | ||
var enrichedOptions = _extends({}, state, { options: options }); | ||
if (!state.integrations[NAMESPACE].loaded) { | ||
console.log('try again', NAMESPACE | ||
console.log('try again page', NAMESPACE); | ||
// TODO: set max try limit and add calls to local queue on fail | ||
);if (timer > timeoutMax) { | ||
if (timer > timeoutMax) { | ||
store.dispatch({ | ||
type: 'pageTimeout', | ||
name: NAMESPACE | ||
} | ||
}); | ||
// TODO: save to queue | ||
);return false; | ||
return false; | ||
} | ||
@@ -437,20 +410,22 @@ timer = timer + 10; | ||
/* run integration[x] .page function */ | ||
provider.page(pageData, enrichedOptions | ||
provider.page(pageData, enrichedOptions); | ||
/* Run Namespaced .page calls */ | ||
);store.dispatch({ | ||
store.dispatch({ | ||
type: 'page:' + NAMESPACE, | ||
data: pageData | ||
} | ||
}); | ||
// increment success counter | ||
);count = count + 1; | ||
count = count + 1; | ||
// all track calls complete | ||
if (count === pageCalls.length) { | ||
var cb = getCallback(data, options, callback); | ||
if (cb) cb(store | ||
// dispatch completion event for middlewares | ||
);store.dispatch({ | ||
store.dispatch({ | ||
type: EVENTS.PAGE_COMPLETE | ||
}); | ||
var cb = getCallback(data, options, callback); | ||
if (cb) { | ||
cb(store); | ||
} | ||
} | ||
@@ -479,5 +454,5 @@ }; | ||
if (type === EVENTS.IDENTIFY_START) { | ||
var identifyCalls = getIntegrationWithMethod(getIntegrations(), 'identify' | ||
var identifyCalls = getIntegrationWithMethod(getIntegrations(), 'identify'); | ||
// No identify middleware attached | ||
);if (!identifyCalls.length) { | ||
if (!identifyCalls.length) { | ||
store.dispatch({ | ||
@@ -520,5 +495,5 @@ type: EVENTS.IDENTIFY, | ||
name: NAMESPACE | ||
} | ||
}); | ||
// TODO: save to queue | ||
);return false; | ||
return false; | ||
} | ||
@@ -543,15 +518,15 @@ timer = timer + 10; | ||
/* run integration[x] .identify function */ | ||
provider.identify(userId, traits, options | ||
provider.identify(userId, traits, options); | ||
/* Run namespaced .identify calls */ | ||
);store.dispatch({ type: 'identify:' + NAMESPACE } | ||
store.dispatch({ type: 'identify:' + NAMESPACE }); | ||
// increment success counter | ||
);count = count + 1; | ||
count = count + 1; | ||
// all identify calls complete | ||
if (count === identifyCalls.length) { | ||
var cb = getCallback(traits, options, callback); | ||
if (cb) cb(state | ||
if (cb) cb(state); | ||
// dispatch completion event for middlewares | ||
);store.dispatch({ | ||
store.dispatch({ | ||
type: EVENTS.IDENTIFY_COMPLETE | ||
@@ -597,14 +572,16 @@ }); | ||
function getBrowserOS() { | ||
if (typeof navigator === 'undefined') { | ||
if (!inBrowser) { | ||
return false; | ||
} | ||
var os = navigator.appVersion; | ||
if (os.indexOf("Win") !== -1) return "Windows"; | ||
if (os.indexOf("Mac") !== -1) return "MacOS"; | ||
if (os.indexOf("X11") !== -1) return "UNIX"; | ||
if (os.indexOf("Linux") !== -1) return "Linux"; | ||
if (os.indexOf('Win') !== -1) return 'Windows'; | ||
if (os.indexOf('Mac') !== -1) return 'MacOS'; | ||
if (os.indexOf('X11') !== -1) return 'UNIX'; | ||
if (os.indexOf('Linux') !== -1) return 'Linux'; | ||
// default | ||
return "Unknown OS"; | ||
return 'Unknown OS'; | ||
} | ||
/* global true false */ | ||
var osName = void 0; | ||
@@ -619,9 +596,11 @@ { | ||
version: null, | ||
debug: false, | ||
os: { | ||
name: osName | ||
}, | ||
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'node', // https://github.com/bestiejs/platform.js | ||
userAgent: inBrowser ? navigator.userAgent : 'node', // https://github.com/bestiejs/platform.js | ||
library: { | ||
name: 'analytics', | ||
version: "0.0.6" | ||
// TODO fix version number. npm run publish:patch has wrong version | ||
version: "0.0.7" | ||
}, | ||
@@ -671,3 +650,2 @@ campaign: {} | ||
// console.log('action.integration', action.integration) | ||
newState[action.name] = { | ||
@@ -718,5 +696,5 @@ enabled: true, | ||
var l = !state.lastEvent ? data : state.event; | ||
console.log('>>>>>>>>>>>> state.lastEvent', state.lastEvent | ||
console.log('>>>>>>>>>>>> state.lastEvent', state.lastEvent); | ||
// TODO fix last event. 9/25 Still need to fix | ||
);return _extends({}, state, { | ||
return _extends({}, state, { | ||
event: data, | ||
@@ -742,23 +720,8 @@ lastEvent: l | ||
var uuid = function uuid() { | ||
var lut = []; | ||
for (var i = 0; i < 256; i++) { | ||
lut[i] = (i < 16 ? '0' : '') + i.toString(16); | ||
} | ||
return function () { | ||
var d0 = Math.random() * 0xffffffff | 0; | ||
var d1 = Math.random() * 0xffffffff | 0; | ||
var d2 = Math.random() * 0xffffffff | 0; | ||
var d3 = Math.random() * 0xffffffff | 0; | ||
return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' + lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' + lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] + lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff]; | ||
}(); | ||
}; | ||
// TODO come up with ls keys | ||
var ANALYTICS_ID = 'analytics_id'; | ||
var inBrowser$1 = typeof window !== 'undefined'; | ||
var setId = function setId() { | ||
var id = uuid(); | ||
if (!inBrowser$1) { | ||
if (!inBrowser) { | ||
return id; | ||
@@ -772,3 +735,3 @@ } | ||
var getId = function getId() { | ||
if (!inBrowser$1) { | ||
if (!inBrowser) { | ||
return null; | ||
@@ -787,4 +750,3 @@ } | ||
userId: null, | ||
anonymousId: initializeId(), // uuidv4 | ||
// fingerprint: '', // exstension? | ||
anonymousId: initializeId(), | ||
traits: {} | ||
@@ -847,9 +809,3 @@ | ||
/* export initialize function. Wont work with commonjs | ||
export default (config) => { | ||
return analytics(config) | ||
} | ||
*/ | ||
// Only way commonJS will work ¯\_(ツ)_/¯ | ||
// Only way commonJS will work | ||
module.exports = function (config) { | ||
@@ -872,6 +828,6 @@ return analytics(config); | ||
return obj; | ||
}, {} | ||
}, {}); | ||
/* Custom redux middleware */ | ||
);var customMiddlewares = plugins.reduce(function (arr, p) { | ||
var customMiddlewares = plugins.reduce(function (arr, p) { | ||
if (typeof p === 'function') { | ||
@@ -883,2 +839,7 @@ return arr.concat(p); | ||
{ | ||
console.log('customIntegrations', customIntegrations); | ||
console.log('customMiddlewares', customMiddlewares); | ||
} | ||
/* plugin methods(functions) must be kept out of state. thus they live here */ | ||
@@ -891,6 +852,6 @@ var getIntegrations = function getIntegrations() { | ||
// core middlewares | ||
initialize, identifyMiddleware(getIntegrations), trackMiddleware(getIntegrations), pageMiddleware(getIntegrations), dynamicMiddlewares] | ||
initialize, identifyMiddleware(getIntegrations), trackMiddleware(getIntegrations), pageMiddleware(getIntegrations), dynamicMiddlewares]); | ||
// initial analytics state keys | ||
);var coreReducers = { | ||
var coreReducers = { | ||
context: context, | ||
@@ -904,5 +865,5 @@ user: user, | ||
var composeEnhancers = compose; | ||
if (typeof window !== 'undefined') { | ||
if (inBrowser) { | ||
var withDevTools = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; | ||
composeEnhancers = compose; | ||
composeEnhancers = withDevTools; | ||
} | ||
@@ -917,12 +878,12 @@ | ||
// register middleware & plugins used | ||
composeEnhancers(applyMiddleware.apply(undefined, toConsumableArray(middlewares))) | ||
composeEnhancers(applyMiddleware.apply(undefined, toConsumableArray(middlewares)))); | ||
// Init analytics | ||
);store.dispatch({ | ||
store.dispatch({ | ||
type: EVENTS.INITIALIZE | ||
} | ||
}); | ||
// Register, load, and onReady custom integrations | ||
);var providers = Object.keys(customIntegrations); | ||
var loadedCount = 0; | ||
var providers = Object.keys(customIntegrations); | ||
providers.forEach(function (int, i) { | ||
@@ -935,59 +896,18 @@ var provider = customIntegrations[int]; | ||
integration: provider | ||
} | ||
}); | ||
// initialize integrations | ||
);if (provider && provider.initialize) { | ||
if (provider && provider.initialize) { | ||
// load scripts etc. | ||
provider.initialize(provider.config | ||
provider.initialize(provider.config); | ||
// run check for loaded here and then dispatch loaded events | ||
);if (provider.loaded && typeof provider.loaded === 'function') { | ||
var checkForScriptReady = function checkForScriptReady() { | ||
if (tries > maxTries) { | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_FAILED, | ||
name: provider.NAMESPACE | ||
}); | ||
store.dispatch({ | ||
type: 'integration_failed:' + provider.NAMESPACE | ||
}); | ||
return false; | ||
} | ||
// check if loaded | ||
if (!provider.loaded()) { | ||
tries++; | ||
setTimeout(checkForScriptReady, 10); | ||
return false; | ||
} | ||
// script isLoaded, dispatch generic event | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_LOADED, | ||
name: provider.NAMESPACE | ||
} | ||
// dispatch namespaced event | ||
);store.dispatch({ | ||
type: 'integration_ready:' + provider.NAMESPACE | ||
}); | ||
loadedCount = loadedCount + 1; | ||
if (loadedCount === providers.length) { | ||
// all integrations loaded. do stuff | ||
store.dispatch({ | ||
type: EVENTS.READY | ||
}); | ||
} | ||
}; | ||
var maxTries = 1000; | ||
var tries = 0; | ||
checkForScriptReady(); | ||
if (provider.loaded && typeof provider.loaded === 'function') { | ||
checkForScriptReady({ maxRetries: 1000 }, store, provider); | ||
} | ||
} | ||
} | ||
}); | ||
// No providers found. Trigger ready listeners | ||
);if (!providers.length) { | ||
if (!providers.length) { | ||
setTimeout(function () { | ||
@@ -1000,2 +920,6 @@ store.dispatch({ | ||
{ | ||
console.log('intialize state', store.getState()); | ||
} | ||
return { | ||
@@ -1016,17 +940,17 @@ // Get all state or state by key | ||
track: function track(eventName, payload, options, callback) { | ||
store.dispatch(trackEvent(eventName, payload, options, callback) | ||
store.dispatch(trackEvent(eventName, payload, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
);return Promise.resolve(); | ||
return Promise.resolve(); | ||
}, | ||
// trigger page view | ||
page: function page$$1(data, options, callback) { | ||
store.dispatch(pageView(data, options, callback) | ||
store.dispatch(pageView(data, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
);return Promise.resolve(); | ||
return Promise.resolve(); | ||
}, | ||
// set user data | ||
identify: function identify$$1(userId, data, options, callback) { | ||
store.dispatch(identify(userId, data, options, callback) | ||
store.dispatch(identify(userId, data, options, callback)); | ||
/* Note promise will return before tracking complete. */ | ||
);return Promise.resolve(); | ||
return Promise.resolve(); | ||
}, | ||
@@ -1078,5 +1002,5 @@ // get user data | ||
// will add middleware to existing chain | ||
addMiddleware(globalListener | ||
addMiddleware(globalListener); | ||
// calling this will destroy listener & remove middleware | ||
);return function () { | ||
return function () { | ||
removeMiddleware(globalListener); | ||
@@ -1097,5 +1021,5 @@ }; | ||
// will add middleware to existing chain | ||
addMiddleware(listener | ||
addMiddleware(listener); | ||
// calling this will destroy listener & remove middleware | ||
);return function () { | ||
return function () { | ||
removeMiddleware(listener); | ||
@@ -1123,1 +1047,56 @@ }; | ||
} | ||
// Check for script loaded on page then dispatch actions | ||
function checkForScriptReady(config, store, provider, retryCount) { | ||
retryCount = retryCount || 0; | ||
var maxRetries = config.maxRetries; | ||
if (retryCount > maxRetries) { | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_FAILED, | ||
name: provider.NAMESPACE | ||
}); | ||
store.dispatch({ | ||
type: 'integration_failed:' + provider.NAMESPACE | ||
}); | ||
return false; | ||
} | ||
// check if loaded | ||
if (!provider.loaded() && retryCount <= maxRetries) { | ||
setTimeout(function () { | ||
checkForScriptReady(config, store, provider, ++retryCount); | ||
}, 10); | ||
return false; | ||
} | ||
// script isLoaded, dispatch generic event | ||
store.dispatch({ | ||
type: EVENTS.INTEGRATION_LOADED, | ||
name: provider.NAMESPACE | ||
}); | ||
// dispatch namespaced event | ||
store.dispatch({ | ||
type: 'integration_ready:' + provider.NAMESPACE | ||
}); | ||
// dispatch ready when all integrations load | ||
var _store$getState = store.getState(), | ||
integrations$$1 = _store$getState.integrations; | ||
var everythingLoaded = Object.keys(integrations$$1).reduce(function (acc, curr) { | ||
if (!integrations$$1[curr].loaded) { | ||
return false; | ||
} | ||
return acc; | ||
}, true); | ||
if (everythingLoaded) { | ||
// all integrations loaded. do stuff | ||
store.dispatch({ | ||
type: EVENTS.READY | ||
}); | ||
} | ||
} |
{ | ||
"name": "analytics", | ||
"version": "0.0.7", | ||
"version": "0.0.8", | ||
"description": "Pluggable analytics library", | ||
@@ -9,5 +9,5 @@ "author": "David Wells", | ||
"module": "dist/analytics.esm.js", | ||
"browser": "dist/analytics.js", | ||
"browser": "dist/analytics.cjs.js", | ||
"scripts": { | ||
"dev": "rollup -c -w", | ||
"watch": "rollup -c -w", | ||
"prebuild": "rimraf ./dist", | ||
@@ -27,4 +27,7 @@ "build": "rollup -c", | ||
"dist", | ||
"core", | ||
"plugins", | ||
"middleware", | ||
"modules", | ||
"utils", | ||
"events.js", | ||
"index.js", | ||
"package.json", | ||
@@ -35,2 +38,3 @@ "package-lock.json", | ||
"dependencies": { | ||
"analytics-utils": "^0.0.6", | ||
"redux": "^3.6.0" | ||
@@ -85,3 +89,4 @@ }, | ||
} | ||
] | ||
], | ||
"gitHead": "4340ab5efff41e0d54e46d2d3a0c6f051dabd783" | ||
} |
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
0
2
2
104138
2
23
2983
1
+ Addedanalytics-utils@^0.0.6
+ Addedanalytics-utils@0.0.6(transitive)