@aicore/core-analytics-client-lib 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,41 +20,29 @@ events for [Core-Analytics-Server](https://github.com/aicore/Core-Analytics-Serv
20
20
  # Usage
21
21
 
22
22
  ## Load the Library
23
- Embed the script in your HTML file :
23
+ Embed the script in your HTML file and replace `your_analytics_account_ID` and `appName`
24
+ in the `initAnalyticsSession` call below:
24
25
  ```html
25
- <script src="https://unpkg.com/@aicore/core-analytics-client-lib/src/analytics.js"></script>
26
+ <!-- Global window.analytics object - core.ai analytics services -->
27
+ <script async src="https://unpkg.com/@aicore/core-analytics-client-lib/src/analytics.js"
28
+ onload="analyticsLibLoaded()"></script>
29
+ <script>
30
+ if(!window.analytics){ window.analytics = {
31
+ _initData : [], loadStartTime: new Date().getTime(),
32
+ event: function (){window.analytics._initData.push(arguments);}
33
+ };}
34
+ function analyticsLibLoaded() {
35
+ initAnalyticsSession('your_analytics_account_ID', 'appName');
36
+ analytics.event("core-analytics", "client-lib", "loadTime", 1, (new Date().getTime())-analytics.loadStartTime);
37
+ }
38
+ </script>
26
39
  ```
27
40
  This will create a global `analytics` variable which can be used to access the analytics APIs.
28
41
 
29
- ## Initialize the analytics session.
30
- Call `analytics.initSession()` after loading the library. It takes the following parameters:
31
-
32
- * `accountID`: Your analytics account id as configured in the server or core.ai analytics
33
- * `appName`: The app name to log the events against. Eg: "phoenixCode"
34
- * `postIntervalSeconds` (_Optional_): This defines the interval between sending analytics events to the server. Default is 10 minutes
35
- * `granularitySec` (_Optional_): The smallest time period under which the events can be distinguished. Multiple
36
- events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
37
- that any events that happen within 3 seconds cannot be distinguished in ordering.
38
- * `analyticsURL` (_Optional_): Provide your own analytics server address if you self-hosted the server
39
- * `debug` (_Optional_): set to true if you want to see detailed debug logs.
40
-
41
- ### usageExample
42
- ```javascript
43
- // Init with default values.
44
- analytics.initSession("accountID", "appName");
45
-
46
- // Example for custom initSession where the analytics aggregated data
47
- // is posted to custom server https://localhost:3000 every 600 secs
48
- // with a granularity(resolution) of 5 seconds.
49
- analytics.initSession("accountID", "appName", "https://localhost:3000", 600, 5);
50
-
51
- // To initSession in debug mode set debug arg in init to true:
52
- analytics.initSession("accountID", "appName", "https://localhost:3000", 600, 5, true);
53
- ```
54
42
 
55
43
  ## Raising analytics events
56
- Once `initSession` is called, we can now start logging analytics events by calling `analytics.event` API.
57
- The API registers an analytics event. The events will be aggregated and send to the analytics server periodically.
44
+ We can now start logging analytics events by calling `analytics.event` API.
45
+ The events will be aggregated and send to the analytics server periodically.
58
46
 
59
47
  ```javascript
60
48
  // analyticsEvent(eventType, eventCategory, subCategory, eventCount, eventValue);
@@ -79,9 +67,46 @@ analytics.event("platform", "CPU", "coreCountsAndFrequencyMhz", 8, 2300);
79
67
  * `eventCategory` - A string, required
80
68
  * `subCategory` - A string, required
81
69
  * `eventCount` (_Optional_) : A non-negative number indicating the number of times the event (or an event with a
82
- particular value if a value is specified) happened. defaults to 1.
70
+ particular value if a value is specified) happened. defaults to 1.
83
71
  * `eventValue` (_Optional_) : A number value associated with the event. defaults to 0
84
72
 
73
+
74
+ ## Advanced Usages
75
+ If you want to modify how analytics library collects and sends information, it is recommended to do so
76
+ with analytics server [accountConfig](https://github.com/aicore/Core-Analytics-Server#accountconfig-configuration).
77
+
78
+ Alternatively for one off development time uses, the behavior of the library can be configured
79
+ during the `initAnalyticsSession` call. `initAnalyticsSession()` takes the following parameters:
80
+
81
+ * `accountID`: Your analytics account id as configured in the server or core.ai analytics
82
+ * `appName`: The app name to log the events against. Eg: "phoenixCode"
83
+ * `postIntervalSeconds` (_Optional_): This defines the interval between sending analytics events to the server. Default is 10 minutes
84
+ * `granularitySec` (_Optional_): The smallest time period under which the events can be distinguished. Multiple
85
+ events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
86
+ that any events that happen within 3 seconds cannot be distinguished in ordering.
87
+ * `analyticsURL` (_Optional_): Provide your own analytics server address if you self-hosted the server
88
+ * `debug` (_Optional_): set to true if you want to see detailed debug logs.
89
+
90
+ ### usageExample
91
+ ```javascript
92
+ // Init with default values and server controlled config. use the following `analyticsLibLoaded` function
93
+ function analyticsLibLoaded() {
94
+ initAnalyticsSession('your_analytics_account_ID', 'appName');
95
+ analytics.event("core-analytics", "client-lib", "loadTime", 1, (new Date().getTime())-analytics.loadStartTime);
96
+ }
97
+
98
+ //Replace initAnalyticsSession in analyticsLibLoaded function for the below use cases.
99
+
100
+ // Example for custom initSession where the analytics aggregated data
101
+ // is posted to custom server https://localhost:3000 every 600 secs
102
+ // with a granularity(resolution) of 5 seconds.
103
+ initAnalyticsSession("accountID", "appName", "https://localhost:3000", 600, 5);
104
+
105
+ // To initSession in debug mode set debug arg in init to true. In debug mode, details logs
106
+ // about analytics library events will be emitted.
107
+ initAnalyticsSession("accountID", "appName", "https://localhost:3000", 600, 5, true);
108
+ ```
109
+
85
110
  # Contribute to core-analytics-client-lib
86
111
 
87
112
  ## Building
@@ -1,4 +1,4 @@
1
- var analytics={};function init(){let r,s,e,t,l,u,c,f,n;const v=3,a=30,y=600,o="aicore.analytics.userID",i=1e4;let d=null;var m="undefined"==typeof window;let g="https://analytics.core.ai",p,h,w=0,C=!1,I=!1;function b(...e){I&&console.log(...e)}if(m)throw new Error("Node environment is not currently supported");function S(){return{schemaVersion:1,accountID:r,appName:s,uuid:e,sessionID:t,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function E(){if(!d)throw new Error("Please call initSession before using any analytics event")}function T(){e=function(){let e=localStorage.getItem(o);return e||(e=crypto.randomUUID(),localStorage.setItem(o,e)),e}(),t=function(){let e=sessionStorage.getItem(o);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(o,e)),e}()}function D(e){e.backoffCount=(e.backoffCount||0)+1,b(`Failed to call core analytics server. Will retry in ${a*e.backoffCount}s: `),setTimeout(()=>{N(e)},1e3*a*e.backoffCount)}function N(t){var e;C||(t||(t=d,w=0,$(),d=S()),0!==t.numEventsTotal&&((e=JSON.stringify(t)).length>i&&console.warn(`Analytics event generated is very large at greater than ${e.length}B. This
2
- typically means that you may be sending too many value events? .`),b("Sending Analytics data of length: ",e.length,"B"),window.fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(e=>{200!==e.status&&(400!==e.status?D(t):console.error("Analytics client: Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{e=[e],I&&console.error(...e),D(t)})))}function $(e){p&&(clearInterval(p),p=null),e||(p=setInterval(()=>{w+=u},1e3*u))}function k(e){$(e),h&&(clearInterval(h),h=null),e||(h=setInterval(N,1e3*l))}async function A(e,t){(n=await new Promise((n,a)=>{var e=c+(`/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)})}))!=={}&&(l=e||n.postIntervalSecondsInit||y,u=t||n.granularitySecInit||v,c=n.analyticsURLInit||c||g,k(C=!0===n.disabled),b(`Init analytics Config from remote. disabled: ${C}
3
- postIntervalSeconds:${l}, granularitySec: ${u} ,URL: `+c),C&&console.warn(`Core Analytics is disabled from the server for app: ${r}:`+s))}analytics.initSession=function(e,t,n,a,o,i){if(!e||!t)throw new Error("accountID and appName must exist for init");c=n?n.replace(/\/$/,""):g,r=e,s=t,I=i||!1,l=a||y,u=o||v,f=c+"/ingest",T(),d=S(),k(),A(a,o)},analytics.getCurrentAnalyticsEvent=function(){return E(),JSON.parse(JSON.stringify(d))},analytics.event=function(n,a,o,i=1,r=0){if(!C){var s=n,l=a,u=o,c=i,f=r;if(E(),!s||!l||!u)throw new Error("missing eventType or category or subCategory");if("number"!=typeof c||c<0)throw new Error("invalid count");if("number"!=typeof f)throw new Error("invalid value");{s=n;l=a;u=o;let e=d.events;e[s]=e[s]||{},e[s][l]=e[s][l]||{},e[s][l][u]=e[s][l][u]||{time:[],valueCount:[]}}let t=d.events;c=t[n][a][o].time;if((0<c.length?c[c.length-1]:null)===w){f=t[n][a][o].valueCount.length-1;{var s=f,l=n,u=a,c=o,f=i,v=r;let t=d.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}d.numEventsTotal+=1}}else{if(t[n][a][o].time.push(w),0===r)t[n][a][o].valueCount.push(i);else{let e={};e[r]=i,t[n][a][o].valueCount.push(e)}d.numEventsTotal+=1}}},analytics.getAppConfig=function(){return{accountID:r,appName:s,disabled:C,uuid:e,sessionID:t,postIntervalSeconds:l,granularitySec:u,analyticsURL:c,serverConfig:n}}}init();
1
+ 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
2
+ 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}
3
+ 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:[]});
4
4
  //# sourceMappingURL=analytics.min.js.map
@@ -1 +1 @@
1
- {"version":3,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["analytics","init","let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","DEFAULT_GRANULARITY_IN_SECONDS","DEFAULT_RETRY_TIME_IN_SECONDS","DEFAULT_POST_INTERVAL_SECONDS","USERID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugMode","debugLog","args","console","log","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_setupIDs","localUserID","localStorage","getItem","crypto","randomUUID","setItem","_getOrCreateUserID","localSessionID","sessionStorage","Math","random","toString","substr","_getOrCreateSessionID","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","textToSend","_resetGranularityTimer","JSON","stringify","length","warn","fetch","method","headers","Content-Type","body","then","res","status","error","catch","debugError","disable","clearInterval","setInterval","_setupTimers","async","_initFromRemoteConfig","postIntervalSecondsInit","granularitySecInit","Promise","resolve","reject","configURL","serverResponse","json","err","initSession","accountIDInit","appNameInit","analyticsURLInit","debug","replace","getCurrentAnalyticsEvent","parse","event","eventType","eventCategory","subCategory","eventCount","eventValue","_validateEvent","category","count","value","_ensureAnalyticsEventExists","time","valueCount","timeArray","modificationIndex","_updateExistingAnalyticsEvent","index","newValue","storedValueIsCount","newValueCount","storedValueObject","push","getAppConfig"],"mappings":"AAKA,IAAIA,UAAY,GAEhB,SAASC,OACLC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EAAqBC,EAAgBC,EAAcC,EAASC,EACvG,MAAMC,EAAiC,EACjCC,EAAgC,GAChCC,EAAgC,IAChCC,EAA2B,0BAC3BC,EAAkC,IACxCd,IAAIe,EAAwB,KAC5B,IAAMC,EAAiC,oBAAXC,OAC5BjB,IAAIkB,EAAmB,4BAEnBC,EACAC,EACAC,EAAuB,EACvBC,GAAW,EACXC,GAAY,EAEhB,SAASC,KAAYC,GACbF,GAGJG,QAAQC,OAAOF,GAWnB,GAAGT,EACC,MAAM,IAAIY,MAAM,+CAGpB,SAASC,IACL,MAAO,CACHC,cAAe,EACf7B,UAAWA,EACXC,QAASA,EACT6B,KAAM5B,EACNC,UAAWA,EACX4B,kBAAmB,IAAIC,KACvBC,eAAgB,EAChBC,OAAQ,IAIhB,SAASC,IACL,IAAIrB,EACA,MAAM,IAAIa,MAAM,4DA4BxB,SAASS,IACLlC,EAnBJ,WACIH,IAAIsC,EAAcC,aAAaC,QAAQ3B,GAKvC,OAJIyB,IACAA,EAAcG,OAAOC,aACrBH,aAAaI,QAAQ9B,EAA0ByB,IAE5CA,EAaEM,GACTxC,EAXJ,WACIJ,IAAI6C,EAAiBC,eAAeN,QAAQ3B,GAK5C,OAJIgC,IACAA,EAAiBE,KAAKC,SAASC,SAAS,IAAIC,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jG,GAC3C,IAAbiF,EACCnE,EAAO+D,GAAWC,GAAeC,GAAyB,WAAEkB,KAAKjB,OAC9D,CACHrG,IAAI6G,EAAa,GACjBA,EAAWP,GAAcD,EACzBlE,EAAO+D,GAAWC,GAAeC,GAAyB,WAAEkB,KAAKT,GAErE9F,EAAsBmB,gBAAkB,KAUhDpC,UAAUyH,aAzIV,WACI,MAAO,CACHtH,UAAAA,EAAWC,QAAAA,EAASoB,SAAAA,EACpBS,KAAM5B,EAAQC,UAAAA,EACdC,oBAAAA,EAAqBC,eAAAA,EAAgBC,aAAAA,EAAcE,aAAAA,IAwI/DV"}
1
+ {"version":3,"sourceRoot":"src/analytics.js","sources":["src/analytics.js"],"names":["initAnalyticsSession","accountIDInit","appNameInit","analyticsURLInit","postIntervalSecondsInit","granularitySecInit","debug","let","accountID","appName","userID","sessionID","postIntervalSeconds","granularitySec","analyticsURL","postURL","serverConfig","DEFAULT_RETRY_TIME_IN_SECONDS","USERID_LOCAL_STORAGE_KEY","POST_LARGE_DATA_THRESHOLD_BYTES","currentAnalyticsEvent","eventData","IS_NODE_ENV","window","DEFAULT_BASE_URL","granularityTimer","postTimer","currentQuantisedTime","disabled","debugMode","debugLog","args","console","log","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","textToSend","_resetGranularityTimer","JSON","stringify","length","warn","fetch","method","headers","Content-Type","body","then","res","status","error","catch","debugError","disable","clearInterval","setInterval","_setupTimers","event","eventType","eventCategory","subCategory","eventCount","eventValue","_validateEvent","category","count","value","_ensureAnalyticsEventExists","time","valueCount","timeArray","modificationIndex","_updateExistingAnalyticsEvent","index","newValue","storedValueIsCount","newValueCount","storedValueObject","push","replace","localUserID","localStorage","getItem","crypto","randomUUID","setItem","_getOrCreateUserID","localSessionID","sessionStorage","Math","random","toString","substr","_getOrCreateSessionID","async","postIntervalSecondsInitial","granularitySecInitial","Promise","resolve","reject","configURL","serverResponse","json","err","_initFromRemoteConfig","analytics","_initData","_getCurrentAnalyticsEvent","parse","_getAppConfig"],"mappings":"AAwBA,SAASA,qBAAqBC,EAAeC,EAAaC,EACtDC,EAAyBC,EAAoBC,GAC7CC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EACvCC,EAAgBC,EAAcC,EAASC,EAAa,GACxD,MACMC,EAAgC,GAEhCC,EAA2B,0BAC3BC,EAAkC,IACxCZ,IAAIa,EAAwB,KAC5B,IA2SQC,EA3SFC,EAAiC,oBAAXC,OAC5BhB,IAAIiB,EAAmB,4BAEnBC,EACAC,EACAC,EAAuB,EACvBC,GAAW,EACXC,GAAY,EAEhB,SAASC,KAAYC,GACbF,GAGJG,QAAQC,OAAOF,GAWnB,GAAGT,EACC,MAAM,IAAIY,MAAM,+CAGpB,SAASC,IACL,MAAO,CACHC,cAAe,EACf5B,UAAWA,EACXC,QAASA,EACT4B,KAAM3B,EACNC,UAAWA,EACX2B,kBAAmB,IAAIC,KACvBC,eAAgB,EAChBC,OAAQ,IAIhB,SAASC,IACL,IAAItB,EACA,MAAM,IAAIc,MAAM,4DAiCxB,SAASS,EAAWC,GAChBA,EAAYC,cAAgBD,EAAYC,cAAgB,GAAK,EAC7Df,yDACIb,EAAgC2B,EAAYC,mBAChDC,WAAW,KACPC,EAA2BH,IACI,IAAhC3B,EAAuC2B,EAAYC,cAG1D,SAASE,EAA2BH,GAChC,IAYII,EAZDpB,IAGCgB,IACAA,EAAcxB,EACdO,EAAuB,EACvBsB,IACA7B,EAAwBe,KAEM,IAA/BS,EAAYJ,kBAGXQ,EAAaE,KAAKC,UAAUP,IAClBQ,OAASjC,GACnBa,QAAQqB,gEAAgEL,EAAWI;2EAGvFtB,EAAS,qCAAsCkB,EAAWI,OAAQ,KAClE7B,OAAO+B,MAAMvC,EAAS,CAClBwC,OAAQ,OACRC,QAAS,CAACC,eAAgB,oBAC1BC,KAAMV,IACPW,KAAKC,IACc,MAAfA,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S,KAAM3B,EAAQC,UAAAA,EACdC,oBAAAA,EAAqBC,eAAAA,EAAgBC,aAAAA,EAAcE,aAAAA,IAmI3DqG,UAAUhD,MAAQA,EAjVlB9C,OAAO8F,YACP9F,OAAO8F,UAAY,CACfC,UAAW"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicore/core-analytics-client-lib",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Analytics client library for https://github.com/aicore/Core-Analytics-Server",
5
5
  "main": "dist/analytics.min.js",
6
6
  "type": "module",
package/src/analytics.js CHANGED
@@ -1,12 +1,31 @@
1
1
  // GNU AGPL-3.0 License Copyright (c) 2021 - present core.ai . All rights reserved.
2
2
 
3
3
  // jshint ignore: start
4
- /*global localStorage, sessionStorage, crypto*/
4
+ /*global localStorage, sessionStorage, crypto, analytics*/
5
5
 
6
- var analytics = {};
7
6
 
8
- function init() {
9
- let accountID, appName, userID, sessionID, postIntervalSeconds, granularitySec, analyticsURL, postURL, serverConfig;
7
+ if(!window.analytics){
8
+ window.analytics = {
9
+ _initData: []
10
+ };
11
+ }
12
+
13
+ /**
14
+ * Initialize the analytics session
15
+ * @param accountIDInit Your analytics account id as configured in the server or core.ai analytics
16
+ * @param appNameInit The app name to log the events against.
17
+ * @param analyticsURLInit Optional: Provide your own analytics server address if you self-hosted the server
18
+ * @param postIntervalSecondsInit Optional: This defines the interval between sending analytics events to the server.
19
+ * Default is 10 minutes
20
+ * @param granularitySecInit Optional: The smallest time period under which the events can be distinguished. Multiple
21
+ * events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
22
+ * that any events that happen within 3 seconds cannot be distinguished in ordering.
23
+ * @param debug set to true if you want to see detailed debug logs.
24
+ */
25
+ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
26
+ postIntervalSecondsInit, granularitySecInit, debug) {
27
+ let accountID, appName, userID, sessionID, postIntervalSeconds,
28
+ granularitySec, analyticsURL, postURL, serverConfig={};
10
29
  const DEFAULT_GRANULARITY_IN_SECONDS = 3;
11
30
  const DEFAULT_RETRY_TIME_IN_SECONDS = 30;
12
31
  const DEFAULT_POST_INTERVAL_SECONDS = 600; // 10 minutes
@@ -60,7 +79,7 @@ function init() {
60
79
  }
61
80
  }
62
81
 
63
- function getCurrentAnalyticsEvent() {
82
+ function _getCurrentAnalyticsEvent() {
64
83
  _validateCurrentState();
65
84
  // return a clone
66
85
  return JSON.parse(JSON.stringify(currentAnalyticsEvent));
@@ -187,7 +206,7 @@ function init() {
187
206
  * Returns the analytics config for the app
188
207
  * @returns {Object}
189
208
  */
190
- function getAppConfig() {
209
+ function _getAppConfig() {
191
210
  return {
192
211
  accountID, appName, disabled,
193
212
  uuid: userID, sessionID,
@@ -195,13 +214,13 @@ function init() {
195
214
  };
196
215
  }
197
216
 
198
- async function _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit) {
217
+ async function _initFromRemoteConfig(postIntervalSecondsInitial, granularitySecInitial) {
199
218
  serverConfig = await _getServerConfig();
200
219
  if(serverConfig !== {}){
201
220
  // User init overrides takes precedence over server overrides
202
- postIntervalSeconds = postIntervalSecondsInit ||
221
+ postIntervalSeconds = postIntervalSecondsInitial ||
203
222
  serverConfig["postIntervalSecondsInit"] || DEFAULT_POST_INTERVAL_SECONDS;
204
- granularitySec = granularitySecInit || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS;
223
+ granularitySec = granularitySecInitial || serverConfig["granularitySecInit"] || DEFAULT_GRANULARITY_IN_SECONDS;
205
224
  // For URLs, the server suggested URL takes precedence over user init values
206
225
  analyticsURL = serverConfig["analyticsURLInit"] || analyticsURL || DEFAULT_BASE_URL;
207
226
  disabled = serverConfig["disabled"] === true;
@@ -218,35 +237,6 @@ function init() {
218
237
  return url.replace(/\/$/, "");
219
238
  }
220
239
 
221
- /**
222
- * Initialize the analytics session
223
- * @param accountIDInit Your analytics account id as configured in the server or core.ai analytics
224
- * @param appNameInit The app name to log the events against.
225
- * @param analyticsURLInit Optional: Provide your own analytics server address if you self-hosted the server
226
- * @param postIntervalSecondsInit Optional: This defines the interval between sending analytics events to the server.
227
- * Default is 10 minutes
228
- * @param granularitySecInit Optional: The smallest time period under which the events can be distinguished. Multiple
229
- * events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
230
- * that any events that happen within 3 seconds cannot be distinguished in ordering.
231
- * @param debug set to true if you want to see detailed debug logs.
232
- */
233
- function initSession(accountIDInit, appNameInit, analyticsURLInit, postIntervalSecondsInit, granularitySecInit, debug) {
234
- if(!accountIDInit || !appNameInit){
235
- throw new Error("accountID and appName must exist for init");
236
- }
237
- analyticsURL = analyticsURLInit? _stripTrailingSlash(analyticsURLInit) : DEFAULT_BASE_URL;
238
- accountID = accountIDInit;
239
- appName = appNameInit;
240
- debugMode = debug || false;
241
- postIntervalSeconds = postIntervalSecondsInit || DEFAULT_POST_INTERVAL_SECONDS;
242
- granularitySec = granularitySecInit || DEFAULT_GRANULARITY_IN_SECONDS;
243
- postURL = analyticsURL + "/ingest";
244
- _setupIDs();
245
- currentAnalyticsEvent = _createAnalyticsEvent();
246
- _setupTimers();
247
- _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit);
248
- }
249
-
250
240
  function _ensureAnalyticsEventExists(eventType, category, subCategory) {
251
241
  let events = currentAnalyticsEvent.events;
252
242
  events[eventType] = events[eventType] || {};
@@ -263,10 +253,10 @@ function init() {
263
253
  throw new Error("missing eventType or category or subCategory");
264
254
  }
265
255
  if(typeof(count)!== 'number' || count <0){
266
- throw new Error("invalid count");
256
+ throw new Error("invalid count, count should be a positive number");
267
257
  }
268
258
  if(typeof(value)!== 'number'){
269
- throw new Error("invalid value");
259
+ throw new Error("invalid value, value should be a number");
270
260
  }
271
261
  }
272
262
 
@@ -321,10 +311,35 @@ function init() {
321
311
  _updateExistingAnalyticsEvent(modificationIndex, eventType, eventCategory, subCategory, eventCount, eventValue);
322
312
  }
323
313
 
324
- analytics.initSession = initSession;
325
- analytics.getCurrentAnalyticsEvent = getCurrentAnalyticsEvent;
314
+ // Init Analytics
315
+ if(!accountIDInit || !appNameInit){
316
+ throw new Error("accountID and appName must exist for init");
317
+ }
318
+ analyticsURL = analyticsURLInit? _stripTrailingSlash(analyticsURLInit) : DEFAULT_BASE_URL;
319
+ accountID = accountIDInit;
320
+ appName = appNameInit;
321
+ debugMode = debug || false;
322
+ postIntervalSeconds = postIntervalSecondsInit || DEFAULT_POST_INTERVAL_SECONDS;
323
+ granularitySec = granularitySecInit || DEFAULT_GRANULARITY_IN_SECONDS;
324
+ postURL = analyticsURL + "/ingest";
325
+ _setupIDs();
326
+ currentAnalyticsEvent = _createAnalyticsEvent();
327
+ _setupTimers();
328
+ _initFromRemoteConfig(postIntervalSecondsInit, granularitySecInit);
329
+
330
+ // As analytics lib load is async, our loading scripts will push event data into initData array till the lib load
331
+ // is complete. Now as load is done, we need to push these pending analytics events. Assuming that the async load of
332
+ // the lib should mostly happen under a second, we should not lose any accuracy of event times within the initial
333
+ // 3-second granularity. For more precision use cases, load the lib sync.
334
+ for(let eventData of analytics._initData){
335
+ event(...eventData);
336
+ }
337
+ analytics._initData = [];
338
+
339
+ // Private API for tests
340
+ analytics._getCurrentAnalyticsEvent = _getCurrentAnalyticsEvent;
341
+ analytics._getAppConfig = _getAppConfig;
342
+
343
+ // Public API
326
344
  analytics.event = event;
327
- analytics.getAppConfig = getAppConfig;
328
345
  }
329
-
330
- init();