@aicore/core-analytics-client-lib
Advanced tools
Comparing version 1.0.6 to 1.0.7
@@ -1,4 +0,4 @@ | ||
function initAnalyticsSession(e,t,n,a,o,i){let r,s,l,u,c,f,v,y,d={};const m=30,p="aicore.analytics.userID",g=1e4;let h=null;var w,C="undefined"==typeof window;let b="https://analytics.core.ai",I,S,D=0,E=!1,T=!1;function A(...e){T&&console.log(...e)}if(C)throw new Error("Node environment is not currently supported");function N(){return{schemaVersion:1,accountID:r,appName:s,uuid:l,sessionID:u,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function $(){if(!h)throw new Error("Please call initSession before using any analytics event")}function k(e){e.backoffCount=(e.backoffCount||0)+1,A(`Failed to call core analytics server. Will retry in ${m*e.backoffCount}s: `),setTimeout(()=>{U(e)},1e3*m*e.backoffCount)}function U(t){var e;E||(t||(t=h,D=0,R(),h=N()),0!==t.numEventsTotal&&((e=JSON.stringify(t)).length>g&&console.warn(`Analytics event generated is very large at greater than ${e.length}B. This | ||
typically means that you may be sending too many value events? .`),A("Sending Analytics data of length: ",e.length,"B"),window.fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(e=>{200!==e.status&&(400!==e.status?k(t):console.error("Analytics client: Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{e=[e],T&&console.error(...e),k(t)})))}function R(e){I&&(clearInterval(I),I=null),e||(I=setInterval(()=>{D+=f},1e3*f))}function _(e){R(e),S&&(clearInterval(S),S=null),e||(S=setInterval(U,1e3*c))}function B(n,a,o,i=1,r=0){if(!E){var s=n,l=a,u=o,c=i,f=r;if($(),!s||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof f)throw new Error("invalid value, value should be a number");{s=n;l=a;u=o;let e=h.events;e[s]=e[s]||{},e[s][l]=e[s][l]||{},e[s][l][u]=e[s][l][u]||{time:[],valueCount:[]}}let t=h.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===D){f=t[n][a][o].valueCount.length-1;{var s=f,l=n,u=a,c=o,f=i,v=r;let t=h.events;var e="number"==typeof t[l][u][c].valueCount[s];if(e&&0===v)t[l][u][c].valueCount[s]+=f;else if(e&&0!==v){let e={};e[v]=f,e[0]=t[l][u][c].valueCount[s],t[l][u][c].valueCount[s]=e}else if(!e){let e=t[l][u][c].valueCount[s];e[v]=(e[v]||0)+f}h.numEventsTotal+=1}}else{if(t[n][a][o].time.push(D),0===r)t[n][a][o].valueCount.push(i);else{let e={};e[r]=i,t[n][a][o].valueCount.push(e)}h.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");v=n?n.replace(/\/$/,""):b,r=e,s=t,T=i||!1,c=a||600,f=o||3,y=v+"/ingest",l=function(){let e=localStorage.getItem(p);return e||(e=crypto.randomUUID(),localStorage.setItem(p,e)),e}(),u=function(){let e=sessionStorage.getItem(p);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(p,e)),e}(),h=N(),_(),async function(e,t){(d=await new Promise((n,a)=>{var e=v+(`/getAppConfig?accountID=${r}&appName=`+s);window.fetch(e).then(async e=>{switch(e.status){case 200:var t=await e.json();return void n(t);case 400:a("Bad Request, check library version compatible?",e);break;default:a("analytics client: Could not update from remote config. Continuing with defaults.",e)}}).catch(e=>{a("analytics client: Could not update from remote config. Continuing with defaults.",e)})}))!=={}&&(c=e||d.postIntervalSecondsInit||600,f=t||d.granularitySecInit||3,v=d.analyticsURLInit||v||b,_(E=!0===d.disabled),A(`Init analytics Config from remote. disabled: ${E} | ||
postIntervalSeconds:${c}, granularitySec: ${f} ,URL: `+v),E&&console.warn(`Core Analytics is disabled from the server for app: ${r}:`+s))}(a,o);for(w of analytics._initData)B(...w);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return $(),JSON.parse(JSON.stringify(h))},analytics._getAppConfig=function(){return{accountID:r,appName:s,disabled:E,uuid:l,sessionID:u,postIntervalSeconds:c,granularitySec:f,analyticsURL:v,serverConfig:d}},analytics.event=B}window.analytics||(window.analytics={_initData:[]}); | ||
function initAnalyticsSession(e,t,n,a,o,i){let s,r,l,u,c,f,y,v,d={};const m=30,p="aicore.analytics.userID",g="aicore.analytics.sessionID",h=1e4;let w=null;var C,b="undefined"==typeof window;let I="https://analytics.core.ai",S,D,E=0,T=!1,A=!1;function N(...e){A&&console.log(...e)}if(b)throw new Error("Node environment is not currently supported");function $(){return{schemaVersion:1,accountID:s,appName:r,uuid:l,sessionID:u,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function k(){if(!w)throw new Error("Please call initSession before using any analytics event")}function U(e){e.backoffCount=(e.backoffCount||0)+1,N(`Failed to call core analytics server. Will retry in ${m*e.backoffCount}s: `),setTimeout(()=>{R(e)},1e3*m*e.backoffCount)}function R(t){var e;T||(t||(t=w,E=0,_(),w=$()),0!==t.numEventsTotal&&((e=JSON.stringify(t)).length>h&&console.warn(`Analytics event generated is very large at greater than ${e.length}B. This | ||
typically means that you may be sending too many value events? .`),N("Sending Analytics data of length: ",e.length,"B"),window.fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(e=>{200!==e.status&&(400!==e.status?U(t):console.error("Analytics client: Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{e=[e],A&&console.error(...e),U(t)})))}function _(e){S&&(clearInterval(S),S=null),e||(S=setInterval(()=>{E+=f},1e3*f))}function B(e){_(e),D&&(clearInterval(D),D=null),e||(D=setInterval(R,1e3*c))}function O(n,a,o,i=1,s=0){if(!T){var r=n,l=a,u=o,c=i,f=s;if(k(),!r||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof f)throw new Error("invalid value, value should be a number");{r=n;l=a;u=o;let e=w.events;e[r]=e[r]||{},e[r][l]=e[r][l]||{},e[r][l][u]=e[r][l][u]||{time:[],valueCount:[]}}let t=w.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===E){f=t[n][a][o].valueCount.length-1;{var r=f,l=n,u=a,c=o,f=i,y=s;let t=w.events;var e="number"==typeof t[l][u][c].valueCount[r];if(e&&0===y)t[l][u][c].valueCount[r]+=f;else if(e&&0!==y){let e={};e[y]=f,e[0]=t[l][u][c].valueCount[r],t[l][u][c].valueCount[r]=e}else if(!e){let e=t[l][u][c].valueCount[r];e[y]=(e[y]||0)+f}w.numEventsTotal+=1}}else{if(t[n][a][o].time.push(E),0===s)t[n][a][o].valueCount.push(i);else{let e={};e[s]=i,t[n][a][o].valueCount.push(e)}w.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");y=n?n.replace(/\/$/,""):I,s=e,r=t,A=i||!1,c=a||600,f=o||3,v=y+"/ingest",l=function(){let e=localStorage.getItem(p);return e||(e=crypto.randomUUID(),localStorage.setItem(p,e)),e}(),u=function(){let e=sessionStorage.getItem(g);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(g,e)),e}(),w=$(),B(),async function(e,t){(d=await new Promise((n,a)=>{var e=y+(`/getAppConfig?accountID=${s}&appName=`+r);window.fetch(e).then(async e=>{switch(e.status){case 200:var t=await e.json();return void n(t);case 400:a("Bad Request, check library version compatible?",e);break;default:a("analytics client: Could not update from remote config. Continuing with defaults.",e)}}).catch(e=>{a("analytics client: Could not update from remote config. Continuing with defaults.",e)})}))!=={}&&(c=e||d.postIntervalSecondsInit||600,f=t||d.granularitySecInit||3,y=d.analyticsURLInit||y||I,B(T=!0===d.disabled),N(`Init analytics Config from remote. disabled: ${T} | ||
postIntervalSeconds:${c}, granularitySec: ${f} ,URL: `+y),T&&console.warn(`Core Analytics is disabled from the server for app: ${s}:`+r))}(a,o);for(C of analytics._initData)O(...C);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return k(),JSON.parse(JSON.stringify(w))},analytics._getAppConfig=function(){return{accountID:s,appName:r,disabled:T,uuid:l,sessionID:u,postIntervalSeconds:c,granularitySec:f,analyticsURL:y,serverConfig:d}},analytics.event=O}window.analytics||(window.analytics={_initData:[]}); | ||
//# sourceMappingURL=analytics.min.js.map |
{ | ||
"name": "@aicore/core-analytics-client-lib", | ||
"version": "1.0.6", | ||
"version": "1.0.7", | ||
"description": "Analytics client library for https://github.com/aicore/Core-Analytics-Server", | ||
@@ -5,0 +5,0 @@ "main": "dist/analytics.min.js", |
@@ -42,2 +42,4 @@ # Core Analytics Client Lib - JS | ||
NB: The script is loaded async, so it will not block other js scripts. `analytics.event` api can be called anytime | ||
after the above code and need not wait for the script load to complete. | ||
@@ -76,2 +78,33 @@ ## Raising analytics events | ||
## Advanced Usages | ||
### Pure JS loading instead of HTML scripts | ||
There may be cases where you would want to load the script from JS alone. For Eg. you | ||
may want to delay library loading till user consents GDPR. For such use cases, use the below code. | ||
```js | ||
function _initCoreAnalytics() { | ||
// Load core analytics scripts | ||
if(!window.analytics){ window.analytics = { | ||
_initData: [], loadStartTime: new Date().getTime(), | ||
event: function (){window.analytics._initData.push(arguments);} | ||
};} | ||
let script = document.createElement('script'); | ||
script.type = 'text/javascript'; | ||
script.async = true; | ||
script.onload = function(){ | ||
// replace `your_analytics_account_ID` and `appName` below with your values | ||
window.initAnalyticsSession('your_analytics_account_ID', 'appName'); // if you have a custom analytics server | ||
window.analytics.event("core-analytics", "client-lib", "loadTime", 1, | ||
(new Date().getTime())- window.analytics.loadStartTime); | ||
}; | ||
script.src = 'https://unpkg.com/@aicore/core-analytics-client-lib/dist/analytics.min.js'; | ||
document.getElementsByTagName('head')[0].appendChild(script); | ||
} | ||
_initCoreAnalytics(); | ||
``` | ||
To load the library, just call `_initCoreAnalytics()` from JS. Note that you may not be able | ||
to use `analytics.event()` APIs before `_initCoreAnalytics()` call is made. | ||
### initAnalyticsSession: modify when, where and how analytics lib sends events | ||
If you want to modify how analytics library collects and sends information, it is recommended to do so | ||
@@ -78,0 +111,0 @@ with analytics server [accountConfig](https://github.com/aicore/Core-Analytics-Server#accountconfig-configuration). |
@@ -33,2 +33,3 @@ // GNU AGPL-3.0 License Copyright (c) 2021 - present core.ai . All rights reserved. | ||
const USERID_LOCAL_STORAGE_KEY = 'aicore.analytics.userID'; | ||
const SESSION_ID_LOCAL_STORAGE_KEY = 'aicore.analytics.sessionID'; | ||
const POST_LARGE_DATA_THRESHOLD_BYTES = 10000; | ||
@@ -99,6 +100,6 @@ let currentAnalyticsEvent = null; | ||
function _getOrCreateSessionID() { | ||
let localSessionID = sessionStorage.getItem(USERID_LOCAL_STORAGE_KEY); | ||
let localSessionID = sessionStorage.getItem(SESSION_ID_LOCAL_STORAGE_KEY); | ||
if(!localSessionID){ | ||
localSessionID = Math.random().toString(36).substr(2, 10); | ||
sessionStorage.setItem(USERID_LOCAL_STORAGE_KEY, localSessionID); | ||
sessionStorage.setItem(SESSION_ID_LOCAL_STORAGE_KEY, localSessionID); | ||
} | ||
@@ -105,0 +106,0 @@ return localSessionID; |
Sorry, the diff of this file is not supported yet
74236
331
199