@livechat/customer-sdk 3.1.3 → 3.1.5

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.
@@ -105,125 +105,43 @@
105
105
 
106
106
  var _ref = {},
107
107
  hasOwnProperty = _ref.hasOwnProperty;
108
- /**
109
- * returns true or false depending if the provided property is present inside the provided object
110
- * @example
111
- * hasOwn('a', { a: 1, b: 2 })
112
- * // returns true
113
- */
114
108
  function hasOwn(prop, obj) {
115
109
  return hasOwnProperty.call(obj, prop);
116
110
  }
117
111
 
118
- /**
119
- * returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level
120
- * @example
121
- * const arr = [{ a: [1, 2] }, { a: [3, 4] }, { a: [5, 6] }]
122
- * flatMap(el => el.a, arr)
123
- * // returns [1, 2, 3, 4, 5, 6]
124
- */
125
112
  function flatMap(iteratee, arr) {
126
113
  var _ref;
127
114
  return (_ref = []).concat.apply(_ref, arr.map(iteratee));
128
115
  }
129
116
 
130
- /**
131
- * determines whether provided value is an array
132
- * @example
133
- * isArray([1, 2])
134
- * // returns true
135
- * isArray('hello')
136
- * // returns false
137
- */
138
- function isArray(arr) {
139
- return Array.isArray(arr);
140
- }
117
+ var isArray = Array.isArray;
141
118
 
142
- /**
143
- * returns true or false depending if the provided value is an object
144
- * @example
145
- * isObject({ a: 1 })
146
- * // returns true
147
- * isObject([1, 2])
148
- * // returns false
149
- */
150
119
  // eslint-disable-next-line @typescript-eslint/ban-types
151
120
  function isObject(obj) {
152
121
  return typeof obj === 'object' && obj !== null && !isArray(obj);
153
122
  }
154
123
 
155
- /**
156
- * returns an array of the provided object keys
157
- * @example
158
- * keys({ a: 1, b: 2, c: 3 })
159
- * // returns ['a', 'b', 'c']
160
- */
161
- function keys(obj) {
162
- if ('keys' in Object && typeof Object.keys === 'function') {
163
- return Object.keys(obj);
164
- }
165
- var keysArray = [];
166
- for (var property in obj) {
167
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
168
- keysArray.push(property);
169
- }
170
- }
171
- return keysArray;
172
- }
173
-
174
- /**
175
- * maps values of the provided object
176
- * @example
177
- * mapValues(val => val.toUpperCase(), { a: 'foo', b: 'bar' })
178
- * // returns { a: 'FOO', b: 'BAR' }
179
- */
180
124
  function mapValues(mapper, obj) {
181
- return keys(obj).reduce(function (acc, key) {
125
+ return Object.keys(obj).reduce(function (acc, key) {
182
126
  acc[key] = mapper(obj[key]);
183
127
  return acc;
184
128
  }, {});
185
129
  }
186
130
 
187
- /**
188
- * returns the provided value
189
- * @example
190
- * identity('hello')
191
- * // returns 'hello'
192
- */
193
131
  function identity(value) {
194
132
  return value;
195
133
  }
196
134
 
197
- /**
198
- * generates a random id
199
- * @example
200
- * generateRandomId()
201
- * // returns 'd1rjknhhch8'
202
- */
203
135
  function generateRandomId() {
204
136
  return Math.random().toString(36).substring(2);
205
137
  }
206
138
 
207
- /**
208
- * generates an unique id based on the provided object keys
209
- * @example
210
- * generateUniqueId({ xuvarw8cao: 1, b837g2nba1d: 2 })
211
- * // returns 'd1rjknhhch8'
212
- */
213
139
  function generateUniqueId(map) {
214
140
  var id = generateRandomId();
215
141
  return hasOwn(id, map) ? generateUniqueId(map) : id;
216
142
  }
217
143
 
218
- /**
219
- * returns the value from the specififed path from the provided object
220
- * @example
221
- * const obj = { a: { b: [1, 2, 3] } }
222
- * get('a.b.1', obj)
223
- * // returns 2
224
- * get(['a', 'b', '1'], obj)
225
- * // returns 2
226
- */
144
+ // based on https://github.com/developit/dlv/blob/d7ec976d12665f1c25dec2acf955dfc2e8757a9c/index.js
227
145
  function get(propPath, obj) {
228
146
  var arrPath = typeof propPath === 'string' ? propPath.split('.') : propPath;
229
147
  var pathPartIndex = 0;
@@ -234,40 +152,14 @@
234
152
  return result;
235
153
  }
236
154
 
237
- /**
238
- * returns true or false depending if the provided value is present inside the provided array or string
239
- * @example
240
- * includes('a', ['a', 'b', 'c'])
241
- * // returns true
242
- * includes('d', 'abc')
243
- * // returns false
244
- */
245
-
246
155
  function includes(value, arrOrStr) {
247
156
  return arrOrStr.indexOf(value) !== -1;
248
157
  }
249
158
 
250
- /**
251
- * returns true or false depending if the provided value is an empty object or an empty array
252
- * @example
253
- * isEmpty({})
254
- * // returns true
255
- */
256
159
  function isEmpty(collection) {
257
160
  return (isArray(collection) ? collection : Object.keys(collection)).length === 0;
258
161
  }
259
162
 
260
- /**
261
- * constructs an object from the provided array of objects, grouped by the value of the specified key
262
- * @example
263
- * const arr = [
264
- * { a: 'foo', b: 'bar' },
265
- * { a: 'foo', b: 'baz' },
266
- * { a: 'test', b: 'bab' },
267
- * ]
268
- * keyBy('a', arr)
269
- * // returns { foo: { a: 'foo', b: 'baz' }, test: { a: 'test', b: 'bab' } }
270
- */
271
163
  function keyBy(prop, arr) {
272
164
  return arr.reduce(function (acc, el) {
273
165
  acc[el[prop]] = el;
@@ -275,47 +167,20 @@
275
167
  }, {});
276
168
  }
277
169
 
278
- /**
279
- * returns the last element of the provided array or undefined when array is empty
280
- * @example
281
- * last([1, 2, 3])
282
- * // returns 3
283
- */
170
+ // TODO: this should return `T | undefined` to match native behavior
284
171
  function last(arr) {
285
- return arr.length > 0 ? arr[arr.length - 1] : undefined;
172
+ return arr.length > 0 ? arr[arr.length - 1] : null;
286
173
  }
287
174
 
288
- /**
289
- * does literally nothing
290
- * @example
291
- * somethingAsyncAndDangerous().catch(noop)
292
- */
293
175
  // eslint-disable-next-line @typescript-eslint/no-empty-function
294
176
  function noop() {}
295
177
 
296
- /**
297
- * returns an array of values of the provided object
298
- * @example
299
- * values({ a: 1, b: 2, c: 3 })
300
- * // returns [1, 2, 3]
301
- */
302
178
  function values(obj) {
303
- return keys(obj).map(function (key) {
179
+ return Object.keys(obj).map(function (key) {
304
180
  return obj[key];
305
181
  });
306
182
  }
307
183
 
308
- /**
309
- * sorts values of the provided object or array based on the provided mapping function or the provided prop string
310
- * @example
311
- * const obj = {
312
- * a: { chats: 1 },
313
- * b: { chats: 3 },
314
- * c: { chats: 2 },
315
- * }
316
- * numericSortBy(el => el.chats * -1, obj)
317
- * // returns [{ chats: 3 }, { chats: 2 }, { chats: 1 }]
318
- */
319
184
  function numericSortBy(propOrMapper, collection) {
320
185
  var mapper = typeof propOrMapper === 'function' ? propOrMapper : function (element) {
321
186
  return get(propOrMapper, element);
@@ -325,25 +190,13 @@
325
190
  });
326
191
  }
327
192
 
328
- /**
329
- * picks specified properties from the object
330
- * @example
331
- * pick(['b'], { a: 1, b: 2 })
332
- * // returns { b: 2 }
333
- */
334
- function pick(keys, obj) {
335
- return keys.reduce(function (acc, prop) {
193
+ function pick(props, obj) {
194
+ return props.reduce(function (acc, prop) {
336
195
  acc[prop] = obj[prop];
337
196
  return acc;
338
197
  }, {});
339
198
  }
340
199
 
341
- /**
342
- * picks specified props only if they exist on the provided object
343
- * @example
344
- * pickOwn(['b'], { a: 1, b: 2 })
345
- * // returns { b: 2 }
346
- */
347
200
  function pickOwn(props, obj) {
348
201
  return props.reduce(function (acc, prop) {
349
202
  if (hasOwn(prop, obj)) {
@@ -353,41 +206,19 @@
353
206
  }, {});
354
207
  }
355
208
 
356
- /**
357
- * returns an array of derived from the provided object key-value tuples
358
- * @example
359
- * toPairs({ a: 1, b: 2 })
360
- * // returns [['a', 1], ['b', 2]]
361
- */
362
- function toPairs(obj) {
363
- return keys(obj).map(function (key) {
209
+ var toPairs = function toPairs(obj) {
210
+ return Object.keys(obj).map(function (key) {
364
211
  return [key, obj[key]];
365
212
  });
366
- }
213
+ };
367
214
 
368
- /**
369
- * returns 0 for matching strings
370
- * return -1 for string with lower char code at some position
371
- * return 1 for string with greater char code at some position
372
- * @example
373
- * stringCompare('abc', 'abc')
374
- * // returns 0
375
- * stringCompare('abc', 'abd')
376
- * // returns -1
377
- */
378
- function stringCompare(strA, strB) {
215
+ var stringCompare = function stringCompare(strA, strB) {
379
216
  if (strA === strB) {
380
217
  return 0;
381
218
  }
382
219
  return strA < strB ? -1 : 1;
383
- }
220
+ };
384
221
 
385
- /**
386
- * returns an array with all the duplicates from the provided array removed based on the iteratee function
387
- * @example
388
- * uniqBy(el => el.toString(), [1, '1', 2, '3', 3])
389
- * // returns [1, 2, '3']
390
- */
391
222
  function uniqBy(iteratee, arr) {
392
223
  // with polyfills this could be just: return Array.from(new Set(arr.map(iteratee)))
393
224
  var seen = [];
@@ -478,18 +309,25 @@
478
309
  });
479
310
  }
480
311
 
481
- var ACCOUNTS_URL = "https://accounts.livechatinc.com";
482
- var buildPath = function buildPath(_ref) {
483
- var uniqueGroups = _ref.uniqueGroups,
484
- organizationId = _ref.organizationId,
485
- groupId = _ref.groupId;
486
- return "" + (uniqueGroups ? "/v2/customer/" + organizationId + "/" + groupId + "/token" : '/v2/customer/token');
487
- };
488
- var buildRequestUrl = function buildRequestUrl(config, env) {
489
- var url = env === 'production' ? ACCOUNTS_URL : ACCOUNTS_URL.replace('accounts.', "accounts." + env + ".");
490
- var path = buildPath(config);
491
- return "" + url + path;
492
- };
312
+ function getRoot() {
313
+ return new Promise(function (resolve) {
314
+ var next = function next() {
315
+ if (!document.body) {
316
+ setTimeout(next, 100);
317
+ return;
318
+ }
319
+ resolve(document.body);
320
+ };
321
+ next();
322
+ });
323
+ }
324
+
325
+ function removeNode(node) {
326
+ var parentNode = node.parentNode;
327
+ if (parentNode) {
328
+ parentNode.removeChild(node);
329
+ }
330
+ }
493
331
 
494
332
  var createError = function createError(_ref) {
495
333
  var code = _ref.code,
@@ -499,7 +337,7 @@
499
337
  return err;
500
338
  };
501
339
 
502
- var parseTokenResponse = function parseTokenResponse(token, organizationId) {
340
+ var parseTokenResponse = function parseTokenResponse(token, licenseId) {
503
341
  if ('identity_exception' in token) {
504
342
  throw createError({
505
343
  code: 'SSO_IDENTITY_EXCEPTION',
@@ -518,33 +356,119 @@
518
356
  expiresIn: token.expires_in * 1000,
519
357
  tokenType: token.token_type,
520
358
  creationDate: Date.now(),
521
- organizationId: organizationId
359
+ licenseId: licenseId
360
+ };
361
+ };
362
+
363
+ var ACCOUNTS_URL = "https://accounts.livechatinc.com";
364
+ var buildPath = function buildPath(_ref) {
365
+ var uniqueGroups = _ref.uniqueGroups,
366
+ licenseId = _ref.licenseId,
367
+ groupId = _ref.groupId;
368
+ return (uniqueGroups ? "/licence/g" + licenseId + "_" + groupId : '') + "/customer";
369
+ };
370
+ var buildRequestUrl = function buildRequestUrl(config, env) {
371
+ var url = env === 'production' ? ACCOUNTS_URL : ACCOUNTS_URL.replace('accounts.', "accounts." + env + ".");
372
+ var path = buildPath(config);
373
+ return "" + url + path;
374
+ };
375
+
376
+ var POST_MESSAGE_ORIGIN = 'https://accounts.livechatinc.com';
377
+ var CUSTOMER_AUTH_FOOTPRINT = '@livechat/customer-auth';
378
+ var getPostMessageOrigin = function getPostMessageOrigin(env) {
379
+ return env === 'production' ? POST_MESSAGE_ORIGIN : POST_MESSAGE_ORIGIN.replace('accounts.', "accounts." + env + ".");
380
+ };
381
+ var buildParams = function buildParams(_ref, redirectUri) {
382
+ var clientId = _ref.clientId,
383
+ licenseId = _ref.licenseId;
384
+ return {
385
+ license_id: String(licenseId),
386
+ flow: 'button',
387
+ response_type: 'token',
388
+ client_id: clientId,
389
+ redirect_uri: redirectUri,
390
+ post_message_uri: redirectUri,
391
+ state: CUSTOMER_AUTH_FOOTPRINT
522
392
  };
523
393
  };
394
+ var buildIframe = function buildIframe(config, env) {
395
+ var redirectUri = getOrigin(String(window.location)) + window.location.pathname;
396
+ var params = buildParams(config, redirectUri);
397
+ var iframe = document.createElement('iframe');
398
+ iframe.style.display = 'none';
399
+ iframe.setAttribute('src', buildRequestUrl(config, env) + "?" + buildQueryString(params));
400
+ return iframe;
401
+ };
402
+ var isTokenResponse = function isTokenResponse(data) {
403
+ return data && data.state === CUSTOMER_AUTH_FOOTPRINT;
404
+ };
405
+ function fetchUsingIframe(config, env) {
406
+ var licenseId = config.licenseId;
407
+ var postMessageOrigin = getPostMessageOrigin(env);
408
+ return new Promise(function (resolve, reject) {
409
+ var iframe = buildIframe(config, env);
410
+ var cleanup = function cleanup() {
411
+ removeNode(iframe);
412
+ // eslint-disable-next-line no-use-before-define
413
+ window.removeEventListener('message', listener, false);
414
+ };
415
+ var timeoutId = setTimeout(function () {
416
+ cleanup();
417
+ reject(createError({
418
+ message: 'Request timed out.',
419
+ code: 'REQUEST_TIMEOUT'
420
+ }));
421
+ }, 15 * 1000);
422
+ var listener = function listener(_ref2) {
423
+ var origin = _ref2.origin,
424
+ data = _ref2.data;
425
+ if (origin !== postMessageOrigin) {
426
+ return;
427
+ }
428
+ if (!isTokenResponse(data)) {
429
+ return;
430
+ }
431
+ clearTimeout(timeoutId);
432
+ cleanup();
433
+ try {
434
+ resolve(parseTokenResponse(data, licenseId));
435
+ } catch (err) {
436
+ reject(err);
437
+ }
438
+ };
439
+ window.addEventListener('message', listener, false);
440
+ getRoot().then(function (body) {
441
+ body.appendChild(iframe);
442
+ });
443
+ });
444
+ }
524
445
 
525
446
  var fetchToken = function fetchToken(config, env) {
526
- return unfetch("" + buildRequestUrl(config, env), {
447
+ if (config.uniqueGroups) {
448
+ return fetchUsingIframe(config, env);
449
+ }
450
+ return unfetch(buildRequestUrl(config, env) + "/token", {
527
451
  method: 'POST',
528
452
  credentials: 'include',
529
453
  body: JSON.stringify({
530
454
  response_type: 'token',
531
455
  grant_type: 'cookie',
532
456
  client_id: config.clientId,
533
- organization_id: config.organizationId,
457
+ license_id: config.licenseId,
534
458
  redirect_uri: getOrigin(String(window.location)) + window.location.pathname
535
459
  })
536
460
  }).then(function (res) {
537
461
  return res.json();
538
462
  }).then(function (token) {
539
- return parseTokenResponse(token, config.organizationId);
463
+ return parseTokenResponse(token, config.licenseId);
540
464
  });
541
465
  };
542
466
 
543
467
  var validateConfig = function validateConfig(_ref) {
544
- var organizationId = _ref.organizationId,
468
+ var licenseId = _ref.licenseId,
545
469
  clientId = _ref.clientId;
546
- if (typeof organizationId !== 'string' || typeof clientId !== 'string') {
547
- throw new Error('You need to pass valid configuration object: { organizationId, clientId }.');
470
+ if (typeof licenseId !== 'number' || typeof clientId !== 'string') {
471
+ throw new Error('You need to pass valid configuration object: { licenseId, clientId }.');
548
472
  }
549
473
  };
550
474
 
@@ -553,39 +477,25 @@
553
477
  expiresIn = _ref.expiresIn;
554
478
  return Date.now() >= creationDate + expiresIn;
555
479
  };
556
- var createAuth = function createAuth(config, licenseId, env) {
480
+ var createAuth = function createAuth(config, env) {
557
481
  validateConfig(config);
558
- var tokenStoragePrefix = config.tokenStoragePrefix || "@@lc_auth_token:";
559
- var oldCacheKey = "" + tokenStoragePrefix + licenseId + (config.uniqueGroups ? ":" + config.groupId : '');
560
- var newCacheKey = "" + tokenStoragePrefix + config.organizationId + (config.uniqueGroups ? ":" + config.groupId : '');
482
+ var cacheKey = "" + "@@lc_auth_token:" + config.licenseId + (config.uniqueGroups ? ":" + config.groupId : '');
561
483
  var pendingTokenRequest = null;
562
484
  var cachedToken = null;
563
- var retrievingToken = storage.getItem(oldCacheKey).then(function (token) {
485
+ var retrievingToken = storage.getItem(cacheKey).then(function (token) {
564
486
  if (retrievingToken === null) {
565
487
  return;
566
488
  }
567
489
  retrievingToken = null;
568
490
  if (!token) {
569
- storage.removeItem(oldCacheKey).then(function () {
570
- return storage.getItem(newCacheKey).then(function (newKeyToken) {
571
- if (!newKeyToken) {
572
- return;
573
- }
574
- cachedToken = JSON.parse(newKeyToken);
575
- });
576
- });
577
491
  return;
578
492
  }
579
- storage.setItem(newCacheKey, token).then(function () {
580
- storage.removeItem(oldCacheKey).then(function () {
581
- cachedToken = JSON.parse(token);
582
- });
583
- });
493
+ cachedToken = JSON.parse(token);
584
494
  });
585
495
  var getFreshToken = function getFreshToken() {
586
496
  pendingTokenRequest = fetchToken(config, env).then(function (token) {
587
497
  pendingTokenRequest = null;
588
- storage.setItem(newCacheKey, JSON.stringify(token));
498
+ storage.setItem(cacheKey, JSON.stringify(token));
589
499
  cachedToken = token;
590
500
  return token;
591
501
  }, function (err) {
@@ -615,7 +525,7 @@
615
525
  var invalidate = function invalidate() {
616
526
  cachedToken = null;
617
527
  retrievingToken = null;
618
- return storage.removeItem(newCacheKey);
528
+ return storage.removeItem(cacheKey);
619
529
  };
620
530
  return {
621
531
  getFreshToken: getFreshToken,
@@ -1184,62 +1094,13 @@
1184
1094
  return sideEffectsMiddleware;
1185
1095
  };
1186
1096
 
1187
- var createBackoff = function createBackoff(_ref) {
1188
- var _ref$min = _ref.min,
1189
- min = _ref$min === void 0 ? 1000 : _ref$min,
1190
- _ref$max = _ref.max,
1191
- max = _ref$max === void 0 ? 5000 : _ref$max,
1192
- _ref$jitter = _ref.jitter,
1193
- jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1194
- var attempts = 0;
1195
- return {
1196
- duration: function duration() {
1197
- var ms = min * Math.pow(2, attempts++);
1198
- if (jitter) {
1199
- var rand = Math.random();
1200
- var deviation = Math.floor(rand * jitter * ms);
1201
- ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1202
- }
1203
- return Math.min(ms, max) | 0;
1204
- },
1205
- reset: function reset() {
1206
- attempts = 0;
1207
- }
1208
- };
1209
- };
1210
-
1211
- /**
1212
- * promiseTry allows us to move success / error handling to be promise based so we will handle both synchronous and asynchronous execution failures and success properly.
1213
- * @param anyFunction - function to be called
1214
- * @returns promise that resolves to the return value of the function
1215
- * @example
1216
- * const promise = promiseTry(() => 1)
1217
- * promise.then(value => console.log(value)) // 1
1218
- */
1219
-
1220
- function promiseTry(anyFunction) {
1221
- return new Promise(function (resolve) {
1222
- resolve(anyFunction());
1223
- });
1224
- }
1225
-
1226
- /**
1227
- * Creates a deferred object that can be resolved or rejected later.
1228
- * @returns A deferred object with a promise and resolve and reject functions.
1229
- * @example
1230
- * const def = promiseDeferred()
1231
- * const promise = def.promise
1232
- * def.resolve(1)
1233
- * return promise.then(res => console.log(res)) // 1
1234
- */
1235
-
1236
- function promiseDeferred() {
1237
- var deferred = {};
1238
- deferred.promise = new Promise(function (resolve, reject) {
1239
- deferred.resolve = resolve;
1240
- deferred.reject = reject;
1097
+ function deferred() {
1098
+ var def = {};
1099
+ def.promise = new Promise(function (resolve, reject) {
1100
+ def.resolve = resolve;
1101
+ def.reject = reject;
1241
1102
  });
1242
- return deferred;
1103
+ return def;
1243
1104
  }
1244
1105
 
1245
1106
  var createReducer = function createReducer(initialState, reducersMap) {
@@ -1263,8 +1124,6 @@
1263
1124
  var AGENT = 'agent';
1264
1125
  var CUSTOMER = 'customer';
1265
1126
 
1266
- var LIVECHAT_ORGANIZATION_ID = 'feaf6c0e-9f43-48ff-9ad0-8e24e0350932';
1267
-
1268
1127
  var getAllRequests = function getAllRequests(state) {
1269
1128
  return state.requests;
1270
1129
  };
@@ -1288,9 +1147,9 @@
1288
1147
  return getConnectionStatus(state) === DESTROYED;
1289
1148
  };
1290
1149
  var getEnvPart = function getEnvPart(_ref) {
1291
- var organizationId = _ref.organizationId,
1150
+ var licenseId = _ref.licenseId,
1292
1151
  env = _ref.env;
1293
- if (organizationId === LIVECHAT_ORGANIZATION_ID) {
1152
+ if (licenseId === 1520) {
1294
1153
  return '.staging';
1295
1154
  }
1296
1155
  if (env === 'production') {
@@ -1304,12 +1163,12 @@
1304
1163
  return "https://api" + regionPart + getEnvPart(state) + ".livechatinc.com";
1305
1164
  };
1306
1165
  var getServerUrl = function getServerUrl(state) {
1307
- return getApiOrigin(state) + "/v3.4/customer";
1166
+ return getApiOrigin(state) + "/v3.3/customer";
1308
1167
  };
1309
1168
  var createInitialState = function createInitialState(initialStateData) {
1310
1169
  var _initialStateData$app = initialStateData.application,
1311
1170
  application = _initialStateData$app === void 0 ? {} : _initialStateData$app,
1312
- organizationId = initialStateData.organizationId,
1171
+ licenseId = initialStateData.licenseId,
1313
1172
  _initialStateData$gro = initialStateData.groupId,
1314
1173
  groupId = _initialStateData$gro === void 0 ? null : _initialStateData$gro,
1315
1174
  env = initialStateData.env,
@@ -1326,9 +1185,9 @@
1326
1185
  return {
1327
1186
  application: _extends({}, application, {
1328
1187
  name: "customer_sdk",
1329
- version: "3.1.3"
1188
+ version: "3.1.5"
1330
1189
  }),
1331
- organizationId: organizationId,
1190
+ licenseId: licenseId,
1332
1191
  env: env,
1333
1192
  groupId: groupId,
1334
1193
  chats: {},
@@ -1782,10 +1641,10 @@
1782
1641
  // TODO: this thing is not really well typed and should be improved
1783
1642
  var sendRequestAction = function sendRequestAction(store, action) {
1784
1643
  action.payload.id = generateUniqueId(store.getState().requests);
1785
- var _promiseDeferred = promiseDeferred(),
1786
- resolve = _promiseDeferred.resolve,
1787
- reject = _promiseDeferred.reject,
1788
- promise = _promiseDeferred.promise;
1644
+ var _deferred = deferred(),
1645
+ resolve = _deferred.resolve,
1646
+ reject = _deferred.reject,
1647
+ promise = _deferred.promise;
1789
1648
  action.payload.promise = promise;
1790
1649
  action.payload.resolve = resolve;
1791
1650
  action.payload.reject = reject;
@@ -1793,44 +1652,59 @@
1793
1652
  return promise;
1794
1653
  };
1795
1654
 
1655
+ var promiseTry = (function (fn) {
1656
+ return new Promise(function (resolve) {
1657
+ resolve(fn());
1658
+ });
1659
+ });
1660
+
1661
+ var createBackoff = function createBackoff(_ref) {
1662
+ var _ref$min = _ref.min,
1663
+ min = _ref$min === void 0 ? 1000 : _ref$min,
1664
+ _ref$max = _ref.max,
1665
+ max = _ref$max === void 0 ? 5000 : _ref$max,
1666
+ _ref$jitter = _ref.jitter,
1667
+ jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1668
+ var attempts = 0;
1669
+ return {
1670
+ duration: function duration() {
1671
+ var ms = min * Math.pow(2, attempts++);
1672
+ if (jitter) {
1673
+ var rand = Math.random();
1674
+ var deviation = Math.floor(rand * jitter * ms);
1675
+ ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1676
+ }
1677
+ return Math.min(ms, max) | 0;
1678
+ },
1679
+ reset: function reset() {
1680
+ attempts = 0;
1681
+ }
1682
+ };
1683
+ };
1684
+
1796
1685
  var AUTHENTICATION = 'AUTHENTICATION';
1797
1686
  var CUSTOMER_BANNED$1 = 'CUSTOMER_BANNED';
1798
1687
  var USERS_LIMIT_REACHED = 'USERS_LIMIT_REACHED';
1799
1688
  var WRONG_PRODUCT_VERSION = 'WRONG_PRODUCT_VERSION';
1800
1689
 
1801
- var getSideStorageKeyByLicense = function getSideStorageKeyByLicense(store, licenseId) {
1690
+ var getSideStorageKey = function getSideStorageKey(store) {
1802
1691
  var _store$getState = store.getState(),
1692
+ licenseId = _store$getState.licenseId,
1803
1693
  groupId = _store$getState.groupId,
1804
1694
  uniqueGroups = _store$getState.uniqueGroups;
1805
1695
  return "side_storage_" + licenseId + (uniqueGroups ? ":" + groupId : '');
1806
1696
  };
1807
- var getSideStorageKeyByOrganization = function getSideStorageKeyByOrganization(store) {
1808
- var _store$getState2 = store.getState(),
1809
- organizationId = _store$getState2.organizationId,
1810
- groupId = _store$getState2.groupId,
1811
- uniqueGroups = _store$getState2.uniqueGroups;
1812
- return "side_storage_" + organizationId + (uniqueGroups ? ":" + groupId : '');
1813
- };
1814
- var getSideStorage = function getSideStorage(store, licenseId) {
1815
- var sideStorageLicenseKey = getSideStorageKeyByLicense(store, licenseId);
1816
- var sideStorageOrganizationKey = getSideStorageKeyByOrganization(store);
1817
- return storage.getItem(sideStorageLicenseKey)["catch"](noop).then(function (sideStorage) {
1818
- if (!sideStorage) {
1819
- return storage.getItem(sideStorageOrganizationKey)["catch"](noop).then(function (organizationSideStorage) {
1820
- return JSON.parse(organizationSideStorage || '{}');
1821
- })["catch"](noop);
1822
- }
1823
- return storage.setItem(sideStorageOrganizationKey, sideStorage)["catch"](noop).then(function () {
1824
- return storage.removeItem(sideStorageLicenseKey)["catch"](noop).then(function () {
1825
- return JSON.parse(sideStorage);
1826
- })["catch"](noop);
1827
- });
1697
+ var getSideStorage = function getSideStorage(store) {
1698
+ return storage.getItem(getSideStorageKey(store))["catch"](noop).then(function (sideStorage) {
1699
+ return JSON.parse(sideStorage || '{}');
1828
1700
  })
1829
1701
  // shouldnt get triggered, just a defensive measure against malformed storage entries
1830
- ["catch"](noop);
1702
+ ["catch"](function () {
1703
+ return {};
1704
+ });
1831
1705
  };
1832
1706
  var saveSideStorage = function saveSideStorage(store, sideStorage) {
1833
- storage.setItem(getSideStorageKeyByOrganization(store), JSON.stringify(sideStorage))["catch"](noop);
1707
+ return storage.setItem(getSideStorageKey(store), JSON.stringify(sideStorage))["catch"](noop);
1834
1708
  };
1835
1709
 
1836
1710
  var taskChain = function taskChain(_ref, onSuccess, onError) {
@@ -1871,7 +1745,7 @@
1871
1745
  setTimeout(resolve, ms);
1872
1746
  });
1873
1747
  };
1874
- function createLoginTask(auth, customerDataProvider, licenseId) {
1748
+ function createLoginTask(auth, customerDataProvider) {
1875
1749
  var store;
1876
1750
  var sentPage = null;
1877
1751
  var task;
@@ -1892,7 +1766,7 @@
1892
1766
  return store.dispatch(reconnect(currentBackoffStrategy.duration()));
1893
1767
  };
1894
1768
  var getTokenAndSideStorage = function getTokenAndSideStorage() {
1895
- return Promise.all([auth.getToken(), getSideStorage(store, licenseId)]);
1769
+ return Promise.all([auth.getToken(), getSideStorage(store)]);
1896
1770
  };
1897
1771
  var dispatchSelfId = function dispatchSelfId(_ref2) {
1898
1772
  var token = _ref2[0],
@@ -2032,7 +1906,7 @@
2032
1906
  return;
2033
1907
  }
2034
1908
  var query = buildQueryString({
2035
- organization_id: state.organizationId
1909
+ license_id: state.licenseId
2036
1910
  });
2037
1911
  var payload = {
2038
1912
  session_fields: parseCustomerSessionFields(sessionFields || {}),
@@ -2531,11 +2405,11 @@
2531
2405
  {
2532
2406
  var upgradedPushes = [];
2533
2407
  socket.emit(_extends({}, frame, {
2534
- version: '3.4',
2408
+ version: '3.3',
2535
2409
  payload: _extends({}, frame.payload, {
2536
2410
  pushes: {
2537
- // '3.5': upgradedPushes,
2538
- '3.4': values(serverPushActions).filter(function (pushAction) {
2411
+ // '3.4': upgradedPushes,
2412
+ '3.3': values(serverPushActions).filter(function (pushAction) {
2539
2413
  return (
2540
2414
  // `customer_disconnected` can be sent immediately after opening the connection, before it even received login request
2541
2415
  // therefore it's not possible to subscribe for a particular version of this push - the "connection version" is always used
@@ -2705,10 +2579,9 @@
2705
2579
  var auth = _ref9.auth,
2706
2580
  customerDataProvider = _ref9.customerDataProvider,
2707
2581
  emitter = _ref9.emitter,
2708
- socket = _ref9.socket,
2709
- licenseId = _ref9.licenseId;
2582
+ socket = _ref9.socket;
2710
2583
  var emit = emitter.emit;
2711
- var loginTask = createLoginTask(auth, customerDataProvider, licenseId);
2584
+ var loginTask = createLoginTask(auth, customerDataProvider);
2712
2585
 
2713
2586
  // TODO: using Store type here is a lie, middleware only provides MiddlewareAPI here
2714
2587
  return function (action, store) {
@@ -3120,14 +2993,14 @@
3120
2993
  resolve = noop;
3121
2994
  },
3122
2995
  check: function check() {
3123
- var deferred = promiseDeferred();
3124
- resolve = deferred.resolve;
2996
+ var deferred$1 = deferred();
2997
+ resolve = deferred$1.resolve;
3125
2998
  timer = setTimeout(function () {
3126
2999
  var err = new Error('Timeout.');
3127
3000
  err.code = 'TIMEOUT';
3128
- deferred.reject(err);
3001
+ deferred$1.reject(err);
3129
3002
  }, 2000);
3130
- return deferred.promise;
3003
+ return deferred$1.promise;
3131
3004
  },
3132
3005
  resolve: function (_resolve) {
3133
3006
  function resolve() {
@@ -3229,7 +3102,7 @@
3229
3102
  var url = (getServerUrl(state) + "/rtm/ws").replace(/^https/, 'wss');
3230
3103
  return createPlatformClient(url, {
3231
3104
  query: {
3232
- organization_id: state.organizationId
3105
+ license_id: state.licenseId
3233
3106
  },
3234
3107
  emitter: emitter
3235
3108
  });
@@ -3521,17 +3394,16 @@
3521
3394
  var lastEventSummary = last(lastEventSummariesArray.sort(function (eventSummaryA, eventSummaryB) {
3522
3395
  return eventSummaryA.thread_id === eventSummaryB.thread_id ? stringCompare(eventSummaryA.event.created_at, eventSummaryB.event.created_at) : stringCompare(eventSummaryA.thread_created_at, eventSummaryB.thread_created_at);
3523
3396
  }));
3524
- if (lastEventSummary && chatSummary.lastEventsPerType) {
3397
+ if (lastEventSummary) {
3525
3398
  chatSummary.lastEvent = chatSummary.lastEventsPerType[lastEventSummary.event.type];
3526
3399
  }
3527
3400
  return chatSummary;
3528
3401
  });
3529
3402
  return {
3530
3403
  chatsSummary: numericSortBy(function (_ref4) {
3531
- var _ref5;
3532
3404
  var lastEvent = _ref4.lastEvent,
3533
3405
  order = _ref4.order;
3534
- return -1 * ((_ref5 = lastEvent !== undefined ? lastEvent.timestamp : order) != null ? _ref5 : 0);
3406
+ return -1 * (lastEvent !== undefined ? lastEvent.timestamp : order);
3535
3407
  }, chatsSummary),
3536
3408
  totalChats: payload.total_chats,
3537
3409
  users: uniqBy(function (user) {
@@ -3708,9 +3580,9 @@
3708
3580
  };
3709
3581
  }
3710
3582
  };
3711
- var parseResponse = function parseResponse(_ref6) {
3712
- var request = _ref6.request,
3713
- response = _ref6.response;
3583
+ var parseResponse = function parseResponse(_ref5) {
3584
+ var request = _ref5.request,
3585
+ response = _ref5.response;
3714
3586
  switch (response.action) {
3715
3587
  case ACCEPT_GREETING:
3716
3588
  return {
@@ -3964,10 +3836,9 @@
3964
3836
  customerId = _ref.customerId,
3965
3837
  _ref$groupId = _ref.groupId,
3966
3838
  groupId = _ref$groupId === void 0 ? state.groupId : _ref$groupId,
3967
- licenseId = _ref.licenseId,
3968
3839
  timeZone = _ref.timeZone;
3969
3840
  var ticketBody = _extends({
3970
- licence_id: licenseId,
3841
+ licence_id: state.licenseId,
3971
3842
  ticket_message: '',
3972
3843
  offline_message: '',
3973
3844
  visitor_id: customerId,
@@ -4047,7 +3918,6 @@
4047
3918
  var sendTicketForm = function sendTicketForm(store, auth, _ref2) {
4048
3919
  var filledForm = _ref2.filledForm,
4049
3920
  groupId = _ref2.groupId,
4050
- licenseId = _ref2.licenseId,
4051
3921
  timeZone = _ref2.timeZone;
4052
3922
  return auth.getToken().then(function (token) {
4053
3923
  var state = store.getState();
@@ -4059,7 +3929,6 @@
4059
3929
  fields: filledForm.fields,
4060
3930
  customerId: token.entityId,
4061
3931
  groupId: groupId,
4062
- licenseId: licenseId,
4063
3932
  timeZone: timeZone
4064
3933
  });
4065
3934
  return unfetch(url, {
@@ -4211,7 +4080,7 @@
4211
4080
  validateFile(file);
4212
4081
  var state = store.getState();
4213
4082
  var query = buildQueryString({
4214
- organization_id: state.organizationId
4083
+ license_id: state.licenseId
4215
4084
  });
4216
4085
  var url = getServerUrl(state) + "/action/" + UPLOAD_FILE + "?" + query;
4217
4086
  var payload = {
@@ -4277,7 +4146,7 @@
4277
4146
  */
4278
4147
  var log = function log(_ref) {
4279
4148
  var env = _ref.env,
4280
- organizationId = _ref.organizationId,
4149
+ licenseId = _ref.licenseId,
4281
4150
  eventName = _ref.eventName;
4282
4151
  if (env !== 'production' || "customer_sdk" !== 'customer_sdk') {
4283
4152
  return Promise.resolve();
@@ -4285,10 +4154,10 @@
4285
4154
  var message = {
4286
4155
  event_name: eventName,
4287
4156
  severity: 'Informational',
4288
- sdkVersion: "3.1.3"
4157
+ sdkVersion: "3.1.5"
4289
4158
  };
4290
4159
  var body = {
4291
- organizationId: organizationId,
4160
+ licence_id: licenseId,
4292
4161
  event_id: 'chat_widget_customer_sdk',
4293
4162
  message: JSON.stringify(message)
4294
4163
  };
@@ -4403,7 +4272,7 @@
4403
4272
  });
4404
4273
 
4405
4274
  var CHATS_PAGINATION_MAX_LIMIT = 25;
4406
- var init = function init(config, env, licenseId) {
4275
+ var init = function init(config, env) {
4407
4276
  if (env === void 0) {
4408
4277
  env = 'production';
4409
4278
  }
@@ -4418,13 +4287,12 @@
4418
4287
  }));
4419
4288
  var emitter = createMitt();
4420
4289
  var socket = createSocketClient(store);
4421
- var auth = typeof identityProvider === 'function' ? identityProvider() : createAuth(instanceConfig, licenseId, env);
4290
+ var auth = typeof identityProvider === 'function' ? identityProvider() : createAuth(instanceConfig, env);
4422
4291
  store.addSideEffectsHandler(createSideEffectsHandler({
4423
4292
  emitter: emitter,
4424
4293
  socket: socket,
4425
4294
  auth: auth,
4426
- customerDataProvider: customerDataProvider,
4427
- licenseId: licenseId
4295
+ customerDataProvider: customerDataProvider
4428
4296
  }));
4429
4297
  socketListener(store, socket);
4430
4298
  var sendRequestAction$1 = sendRequestAction.bind(null, store);
@@ -4623,7 +4491,7 @@
4623
4491
  resumeChat: function resumeChat(data) {
4624
4492
  log({
4625
4493
  env: env,
4626
- organizationId: config.organizationId,
4494
+ licenseId: config.licenseId,
4627
4495
  eventName: 'chat_started'
4628
4496
  });
4629
4497
  return sendRequestAction$1(sendRequest(RESUME_CHAT, parseResumeChatData(data)));
@@ -4678,7 +4546,7 @@
4678
4546
  }
4679
4547
  log({
4680
4548
  env: env,
4681
- organizationId: config.organizationId,
4549
+ licenseId: config.licenseId,
4682
4550
  eventName: 'chat_started'
4683
4551
  });
4684
4552
  return sendRequestAction$1(sendRequest(START_CHAT, parseStartChatData(data)));