UNPKG

@aicore/core-analytics-client-lib

Version:

Analytics client library for https://github.com/aicore/Core-Analytics-Server

4 lines 4.61 kB
function initAnalyticsSession(n,t,e,a,o){let i,r,s,l,u,c,d,f,y={};const v="aicore.analytics.userID",g="aicore.analytics.sessionID",p=1e4;let m=null;var w,h,b,C="undefined"==typeof window;let I="https://analytics.core.ai",S,D,E=0,U=!1;function T(...n){window.analytics.debugMode&&console.log("analytics client: ",...n)}function A(...n){window.analytics.debugMode&&console.error("analytics client: ",...n)}if(C)throw new Error("Node environment is not currently supported");function N(){return{schemaVersion:1,accountID:i,appName:r,uuid:s,sessionID:l,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function $(){if(!m)throw new Error("Please call initSession before using any analytics event")}function k(n){n.backoffCount=(n.backoffCount||0)+1,T(`Failed to call core analytics server. Will retry in ${30*n.backoffCount}s: `),setTimeout(()=>{R(n)},3e4*n.backoffCount)}function B(t){var n,e=JSON.stringify(t);e.length>p&&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? .`),T("Sending Analytics data of length: ",e.length,"B"),n=["Sending data:",t],window.analytics.debugMode&&console.info("analytics client: ",...n),window.navigator.onLine?window.fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(n=>{200!==n.status&&(400!==n.status?k(t):console.error("Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(n=>{A(n),k(t)}):k(t)}function R(n){U||(n||(n=m,E=0,L(),m=N()),0!==n.numEventsTotal&&B(n))}function L(n){S&&(clearInterval(S),S=null),n||(S=setInterval(()=>{E+=c},1e3*c))}function M(n){L(n),D&&(clearInterval(D),D=null),n||(D=setInterval(R,1e3*u))}function _(n,t,e,a=1,o=0){if(!U){var i=n,r=t,s=e,l=a,u=o;if($(),!i||!r||!s)throw new Error("missing eventType or category or subCategory");if("number"!=typeof l||l<0)throw new Error("invalid count, count should be a positive number");if("number"!=typeof u)throw new Error("invalid value, value should be a number");i=n,r=t,s=e,(l=m.events)[i]=l[i]||{},l[i][r]=l[i][r]||{},l[i][r][s]=l[i][r][s]||{time:[],valueCount:[]};var u=m.events,l=u[n][t][e],i=l.time;(0<i.length?i[i.length-1]:null)!==E?(i.push(E),0===o?l.valueCount.push(a):((r={})[o]=a,l.valueCount.push(r))):(s=l.valueCount.length-1,u=s,i=n,r=t,l=e,s=a,n=o,i=m.events[i][r][l],(r="number"==typeof i.valueCount[u])&&0===n?i.valueCount[u]+=s:r&&0!==n?((l={})[n]=s,l[0]=i.valueCount[u],i.valueCount[u]=l):r||((l=i.valueCount[u])[n]=(l[n]||0)+s)),m.numEventsTotal+=1}}if(!n||!t)throw new Error("accountID and appName must exist for init");d=e?e.toString().replace(/\/$/,""):I,i=n,r=t,u=a||60,c=o||3,f=d+"/ingest",s=function(){let n=localStorage.getItem(v);return n||(n=crypto.randomUUID(),localStorage.setItem(v,n)),n}(),l=function(){let n=sessionStorage.getItem(g);return n||(n=Math.random().toString(36).substr(2,10),sessionStorage.setItem(g,n)),n}(),m=N(),M(),w=a,h=o,new Promise(t=>{var n;window.navigator.onLine?(n=d+(`/getAppConfig?accountID=${i}&appName=`+r),window.fetch(n).then(n=>{switch(n.status){case 200:return void n.json().then(n=>{t(n)}).catch(n=>{A("remote response invalid. Continuing with defaults.",n),t({})});case 400:A("Bad Request, check library version compatible?",n),t({});break;default:A("Could not update from remote config. Continuing with defaults.",n),t({})}}).catch(n=>{A("Could not update from remote config. Continuing with defaults.",n),t({})})):t({})}).then(n=>{y!=={}&&(y=n,u=w||y.postIntervalSecondsInit||60,c=h||y.granularitySecInit||3,d=y.analyticsURLInit||d||I,M(U=!0===y.disabled),T(`Init analytics Config from remote. disabled: ${U} postIntervalSeconds:${u}, granularitySec: ${c} ,URL: `+d),U)&&console.warn(`Core Analytics is disabled from the server for app: ${i}:`+r)});for(b of analytics._initData)_(...b);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return $(),JSON.parse(JSON.stringify(m))},analytics._getAppConfig=function(){return{accountID:i,appName:r,disabled:U,uuid:s,sessionID:l,postIntervalSeconds:u,granularitySec:c,analyticsURL:d,serverConfig:y}},analytics.event=_,analytics.countEvent=function(n,t,e,a=1){return _(n,t,e,a,0)},analytics.valueEvent=function(n,t,e,a=0,o=1){return _(n,t,e,o,a)}}window.analytics||(window.analytics={_initData:[],debugMode:!1}),void 0===window.crypto&&(window.crypto={}),"randomUUID"in crypto||(crypto.randomUUID=function(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,n=>(n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16))}); //# sourceMappingURL=analytics.min.js.map