@aicore/core-analytics-client-lib 1.0.7 → 1.0.8

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
@@ -113,14 +113,14 @@ during the `initAnalyticsSession` call. `initAnalyticsSession()` takes the follo
113
113
 
114
114
  * `accountID`: Your analytics account id as configured in the server or core.ai analytics
115
115
  * `appName`: The app name to log the events against. Eg: "phoenixCode"
116
- * `postIntervalSeconds` (_Optional_): This defines the interval between sending analytics events to the server. Default is 10 minutes
116
+ * `analyticsURL` (_Optional_): Provide your own analytics server address if you self-hosted the server.
117
+ * `postIntervalSeconds` (_Optional_): This defines the interval between sending analytics events to the server. Default is 1 minutes or server controlled.
117
118
  * `granularitySec` (_Optional_): The smallest time period under which the events can be distinguished. Multiple
118
- events happening during this time period is aggregated to a count. The default granularity is 3 Seconds, which means
119
- that any events that happen within 3 seconds cannot be distinguished in ordering.
120
- * `analyticsURL` (_Optional_): Provide your own analytics server address if you self-hosted the server
119
+ events happening during this time period is aggregated to a count. The default granularity is 3 Seconds or server controlled,
120
+ which means that any events that happen within 3 seconds cannot be distinguished in ordering.
121
121
  * `debug` (_Optional_): set to true if you want to see detailed debug logs.
122
122
 
123
- ### usageExample
123
+ #### usageExample
124
124
  ```javascript
125
125
  // Init with default values and server controlled config. use the following `analyticsLibLoaded` function
126
126
  function analyticsLibLoaded() {
@@ -134,12 +134,22 @@ function analyticsLibLoaded() {
134
134
  // is posted to custom server https://localhost:3000 every 600 secs
135
135
  // with a granularity(resolution) of 5 seconds.
136
136
  initAnalyticsSession("accountID", "appName", "https://localhost:3000", 600, 5);
137
+ ```
137
138
 
139
+ ### Debug logs
140
+ If you want to see detailed logs on what is happening inside analytics lib, use the below code:
141
+ ```js
138
142
  // To initSession in debug mode set debug arg in init to true. In debug mode, details logs
139
143
  // about analytics library events will be emitted.
140
144
  initAnalyticsSession("accountID", "appName", "https://localhost:3000", 600, 5, true);
141
145
  ```
142
146
 
147
+ To see info level logs that shows actual analytics data being sent to server, set the below property:
148
+ ```js
149
+ window.analytics.debugInfoLogsEnable = true;
150
+ ```
151
+
152
+
143
153
  # Contribute to core-analytics-client-lib
144
154
 
145
155
  ## Building
@@ -1,4 +1,4 @@
1
- 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
2
- 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}
3
- 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:[]});
1
+ function initAnalyticsSession(e,t,n,a,o,i){let s,r,l,u,c,f,d,v,y={};const g="aicore.analytics.userID",m="aicore.analytics.sessionID",p=1e4;let h=null;var w,b="undefined"==typeof window;let C="https://analytics.core.ai",I,S,D=0,E=!1,T=!1;function N(...e){T&&console.log("analytics client: ",...e)}function $(...e){T&&console.error("analytics client: ",...e)}if(b)throw new Error("Node environment is not currently supported");function k(){return{schemaVersion:1,accountID:s,appName:r,uuid:l,sessionID:u,unixTimestampUTC:+new Date,numEventsTotal:0,events:{}}}function A(){if(!h)throw new Error("Please call initSession before using any analytics event")}function L(e){e.backoffCount=(e.backoffCount||0)+1,N(`Failed to call core analytics server. Will retry in ${30*e.backoffCount}s: `),setTimeout(()=>{U(e)},3e4*e.backoffCount)}function O(t){var e,n=JSON.stringify(t);n.length>p&&console.warn(`Analytics event generated is very large at greater than ${n.length}B. This
2
+ typically means that you may be sending too many value events? .`),N("Sending Analytics data of length: ",n.length,"B"),e=["Sending data:",n],T&&window.analytics.debugInfoLogsEnable&&console.info("analytics client: ",...e),window.navigator.onLine?window.fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:n}).then(e=>{200!==e.status&&(400!==e.status?L(t):console.error("Bad Request, this is most likely a problem with the library, update to latest version."))}).catch(e=>{$(e),L(t)}):L(t)}function U(e){E||(e||(e=h,D=0,R(),h=k()),0!==e.numEventsTotal&&O(e))}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,s=0){if(!E){var r=n,l=a,u=o,c=i,f=s;if(A(),!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=h.events;e[r]=e[r]||{},e[r][l]=e[r][l]||{},e[r][l][u]=e[r][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 r=f,l=n,u=a,c=o,f=i,d=s;let t=h.events;var e="number"==typeof t[l][u][c].valueCount[r];if(e&&0===d)t[l][u][c].valueCount[r]+=f;else if(e&&0!==d){let e={};e[d]=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[d]=(e[d]||0)+f}h.numEventsTotal+=1}}else{if(t[n][a][o].time.push(D),0===s)t[n][a][o].valueCount.push(i);else{let e={};e[s]=i,t[n][a][o].valueCount.push(e)}h.numEventsTotal+=1}}}if(!e||!t)throw new Error("accountID and appName must exist for init");d=n?n.replace(/\/$/,""):C,s=e,r=t,T=i||!1,c=a||60,f=o||3,v=d+"/ingest",l=function(){let e=localStorage.getItem(g);return e||(e=crypto.randomUUID(),localStorage.setItem(g,e)),e}(),u=function(){let e=sessionStorage.getItem(m);return e||(e=Math.random().toString(36).substr(2,10),sessionStorage.setItem(m,e)),e}(),h=k(),_(),async function(e,t){(y=await new Promise(n=>{var e;window.navigator.onLine?(e=d+(`/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:$("Bad Request, check library version compatible?",e),n({});break;default:$("Could not update from remote config. Continuing with defaults.",e),n({})}}).catch(e=>{$("Could not update from remote config. Continuing with defaults.",e),n({})})):n({})}))!=={}&&(c=e||y.postIntervalSecondsInit||60,f=t||y.granularitySecInit||3,d=y.analyticsURLInit||d||C,_(E=!0===y.disabled),N(`Init analytics Config from remote. disabled: ${E}
3
+ postIntervalSeconds:${c}, granularitySec: ${f} ,URL: `+d),E&&console.warn(`Core Analytics is disabled from the server for app: ${s}:`+r))}(a,o);for(w of analytics._initData)B(...w);analytics._initData=[],analytics._getCurrentAnalyticsEvent=function(){return A(),JSON.parse(JSON.stringify(h))},analytics._getAppConfig=function(){return{accountID:s,appName:r,disabled:E,uuid:l,sessionID:u,postIntervalSeconds:c,granularitySec:f,analyticsURL:d,serverConfig:y}},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":["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","SESSION_ID_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","_getCurrentAnaly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,aAAAA,EAAcE,aAAAA,IAmI3DsG,UAAUhD,MAAQA,EAlVlB9C,OAAO8F,YACP9F,OAAO8F,UAAY,CACfC,UAAW"}
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","USERID_LOCAL_STORAGE_KEY","SESSION_ID_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","debugError","error","Error","_createAnalyticsEvent","schemaVersion","uuid","unixTimestampUTC","Date","numEventsTotal","events","_validateCurrentState","_retryPost","eventToSend","backoffCount","setTimeout","_postCurrentAnalyticsEvent","DEFAULT_RETRY_TIME_IN_SECONDS","_postEventWithRetry","textToSend","JSON","stringify","length","warn","debugInfo","analytics","debugInfoLogsEnable","info","navigator","onLine","fetch","method","headers","Content-Type","body","then","res","status","catch","_resetGranularityTimer","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","configURL","serverResponse","json","resolve","err","_initFromRemoteConfig","_initData","_getCurrentAnalyticsEvent","parse","_getAppConfig"],"mappings":"AAwBA,SAASA,qBAAqBC,EAAeC,EAAaC,EACtDC,EAAyBC,EAAoBC,GAC7CC,IAAIC,EAAWC,EAASC,EAAQC,EAAWC,EACvCC,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UlC,KAmRrCsC,UAAUqE,cApIV,WACI,MAAO,CACHvH,UAAAA,EAAWC,QAAAA,EAASmB,SAAAA,EACpBW,KAAM7B,EAAQC,UAAAA,EACdC,oBAAAA,EAAqBC,eAAAA,EAAgBC,aAAAA,EAAcE,aAAAA,IAmI3D0C,UAAUmB,MAAQA,EA3WlBtD,OAAOmC,YACPnC,OAAOmC,UAAY,CACfkE,UAAW"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicore/core-analytics-client-lib",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
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
@@ -14,12 +14,12 @@ if(!window.analytics){
14
14
  * Initialize the analytics session
15
15
  * @param accountIDInit Your analytics account id as configured in the server or core.ai analytics
16
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
17
+ * @param analyticsURLInit Optional: Provide your own analytics server address if you self-hosted the server.
18
18
  * @param postIntervalSecondsInit Optional: This defines the interval between sending analytics events to the server.
19
- * Default is 10 minutes
19
+ * Default is 1 minutes or server controlled.
20
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.
21
+ * events happening during this time period is aggregated to a count. The default granularity is 3 Seconds or server
22
+ * controlled, which means that any events that happen within 3 seconds cannot be distinguished in ordering.
23
23
  * @param debug set to true if you want to see detailed debug logs.
24
24
  */
25
25
  function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
@@ -28,7 +28,7 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
28
28
  granularitySec, analyticsURL, postURL, serverConfig={};
29
29
  const DEFAULT_GRANULARITY_IN_SECONDS = 3;
30
30
  const DEFAULT_RETRY_TIME_IN_SECONDS = 30;
31
- const DEFAULT_POST_INTERVAL_SECONDS = 600; // 10 minutes
31
+ const DEFAULT_POST_INTERVAL_SECONDS = 60; // 1 minutes
32
32
  const USERID_LOCAL_STORAGE_KEY = 'aicore.analytics.userID';
33
33
  const SESSION_ID_LOCAL_STORAGE_KEY = 'aicore.analytics.sessionID';
34
34
  const POST_LARGE_DATA_THRESHOLD_BYTES = 10000;
@@ -46,14 +46,20 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
46
46
  if(!debugMode){
47
47
  return;
48
48
  }
49
- console.log(...args);
49
+ console.log("analytics client: ", ...args);
50
+ }
51
+
52
+ function debugInfo(...args) {
53
+ if(debugMode && window.analytics.debugInfoLogsEnable){
54
+ console.info("analytics client: ", ...args);
55
+ }
50
56
  }
51
57
 
52
58
  function debugError(...args) {
53
59
  if(!debugMode){
54
60
  return;
55
61
  }
56
- console.error(...args);
62
+ console.error("analytics client: ", ...args);
57
63
  }
58
64
 
59
65
 
@@ -118,25 +124,20 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
118
124
  }, DEFAULT_RETRY_TIME_IN_SECONDS * 1000 * eventToSend.backoffCount);
119
125
  }
120
126
 
121
- function _postCurrentAnalyticsEvent(eventToSend) {
122
- if(disabled){
123
- return;
124
- }
125
- if(!eventToSend){
126
- eventToSend = currentAnalyticsEvent;
127
- currentQuantisedTime = 0;
128
- _resetGranularityTimer();
129
- currentAnalyticsEvent = _createAnalyticsEvent();
130
- }
131
- if(eventToSend.numEventsTotal === 0 ){
132
- return;
133
- }
127
+ function _postEventWithRetry(eventToSend) {
134
128
  let textToSend = JSON.stringify(eventToSend);
135
129
  if(textToSend.length > POST_LARGE_DATA_THRESHOLD_BYTES){
136
130
  console.warn(`Analytics event generated is very large at greater than ${textToSend.length}B. This
137
131
  typically means that you may be sending too many value events? .`);
138
132
  }
139
133
  debugLog("Sending Analytics data of length: ", textToSend.length, "B");
134
+ debugInfo("Sending data:", textToSend);
135
+ if(!window.navigator.onLine){
136
+ _retryPost(eventToSend);
137
+ // chrome shows all network failure requests in console. In offline mode, we don't want to bomb debug
138
+ // console with network failure messages for analytics. So we prevent network requests when offline.
139
+ return;
140
+ }
140
141
  window.fetch(postURL, {
141
142
  method: "POST",
142
143
  headers: {'Content-Type': 'application/json'},
@@ -148,8 +149,7 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
148
149
  if(res.status !== 400){ // we don't retry bad requests
149
150
  _retryPost(eventToSend);
150
151
  } else {
151
- console.error("Analytics client: " +
152
- "Bad Request, this is most likely a problem with the library, update to latest version.");
152
+ console.error("Bad Request, this is most likely a problem with the library, update to latest version.");
153
153
  }
154
154
  }).catch(res => {
155
155
  debugError(res);
@@ -157,6 +157,22 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
157
157
  });
158
158
  }
159
159
 
160
+ function _postCurrentAnalyticsEvent(eventToSend) {
161
+ if(disabled){
162
+ return;
163
+ }
164
+ if(!eventToSend){
165
+ eventToSend = currentAnalyticsEvent;
166
+ currentQuantisedTime = 0;
167
+ _resetGranularityTimer();
168
+ currentAnalyticsEvent = _createAnalyticsEvent();
169
+ }
170
+ if(eventToSend.numEventsTotal === 0 ){
171
+ return;
172
+ }
173
+ _postEventWithRetry(eventToSend);
174
+ }
175
+
160
176
  function _resetGranularityTimer(disable) {
161
177
  if(granularityTimer){
162
178
  clearInterval(granularityTimer);
@@ -183,7 +199,13 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
183
199
  }
184
200
 
185
201
  async function _getServerConfig() {
186
- return new Promise((resolve, reject)=>{
202
+ return new Promise((resolve)=>{
203
+ if(!window.navigator.onLine){
204
+ resolve({});
205
+ // chrome shows all network failure requests in console. In offline mode, we don't want to bomb debug
206
+ // console with network failure messages for analytics. So we prevent network requests when offline.
207
+ return;
208
+ }
187
209
  let configURL = analyticsURL + `/getAppConfig?accountID=${accountID}&appName=${appName}`;
188
210
  window.fetch(configURL).then(async res=>{
189
211
  switch (res.status) {
@@ -192,13 +214,16 @@ function initAnalyticsSession(accountIDInit, appNameInit, analyticsURLInit,
192
214
  resolve(serverResponse);
193
215
  return;
194
216
  case 400:
195
- reject("Bad Request, check library version compatible?", res);
217
+ debugError("Bad Request, check library version compatible?", res);
218
+ resolve({});
196
219
  break;
197
220
  default:
198
- reject("analytics client: Could not update from remote config. Continuing with defaults.", res);
221
+ debugError("Could not update from remote config. Continuing with defaults.", res);
222
+ resolve({});
199
223
  }
200
224
  }).catch(err => {
201
- reject("analytics client: Could not update from remote config. Continuing with defaults.", err);
225
+ debugError("Could not update from remote config. Continuing with defaults.", err);
226
+ resolve({});
202
227
  });
203
228
  });
204
229
  }