@livechat/customer-sdk 4.0.2 → 5.0.0

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.
@@ -2,47 +2,44 @@
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
3
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CustomerSDK = {}));
5
- }(this, (function (exports) { 'use strict';
5
+ })(this, (function (exports) { 'use strict';
6
6
 
7
+ function _arrayLikeToArray(r, a) {
8
+ (null == a || a > r.length) && (a = r.length);
9
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
10
+ return n;
11
+ }
7
12
  function _extends() {
8
- _extends = Object.assign ? Object.assign.bind() : function (target) {
9
- for (var i = 1; i < arguments.length; i++) {
10
- var source = arguments[i];
11
- for (var key in source) {
12
- if (Object.prototype.hasOwnProperty.call(source, key)) {
13
- target[key] = source[key];
14
- }
15
- }
13
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
14
+ for (var e = 1; e < arguments.length; e++) {
15
+ var t = arguments[e];
16
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
16
17
  }
17
- return target;
18
- };
19
- return _extends.apply(this, arguments);
18
+ return n;
19
+ }, _extends.apply(null, arguments);
20
20
  }
21
- function _objectWithoutPropertiesLoose(source, excluded) {
22
- if (source == null) return {};
23
- var target = {};
24
- var sourceKeys = Object.keys(source);
25
- var key, i;
26
- for (i = 0; i < sourceKeys.length; i++) {
27
- key = sourceKeys[i];
28
- if (excluded.indexOf(key) >= 0) continue;
29
- target[key] = source[key];
21
+ function _objectWithoutPropertiesLoose(r, e) {
22
+ if (null == r) return {};
23
+ var t = {};
24
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
25
+ if (-1 !== e.indexOf(n)) continue;
26
+ t[n] = r[n];
30
27
  }
31
- return target;
28
+ return t;
32
29
  }
33
- function _toPrimitive(input, hint) {
34
- if (typeof input !== "object" || input === null) return input;
35
- var prim = input[Symbol.toPrimitive];
36
- if (prim !== undefined) {
37
- var res = prim.call(input, hint || "default");
38
- if (typeof res !== "object") return res;
30
+ function _toPrimitive(t, r) {
31
+ if ("object" != typeof t || !t) return t;
32
+ var e = t[Symbol.toPrimitive];
33
+ if (void 0 !== e) {
34
+ var i = e.call(t, r || "default");
35
+ if ("object" != typeof i) return i;
39
36
  throw new TypeError("@@toPrimitive must return a primitive value.");
40
37
  }
41
- return (hint === "string" ? String : Number)(input);
38
+ return ("string" === r ? String : Number)(t);
42
39
  }
43
- function _toPropertyKey(arg) {
44
- var key = _toPrimitive(arg, "string");
45
- return typeof key === "symbol" ? key : String(key);
40
+ function _toPropertyKey(t) {
41
+ var i = _toPrimitive(t, "string");
42
+ return "symbol" == typeof i ? i : i + "";
46
43
  }
47
44
 
48
45
  var testKey = '__test_storage_support__';
@@ -84,27 +81,41 @@
84
81
  var index = /*#__PURE__*/
85
82
  createStorage();
86
83
 
87
- var usedStorage = testStorageSupport() ? window.localStorage : index;
88
- var storage = {
89
- setItem: function setItem(key, value) {
90
- return new Promise(function (resolve) {
91
- return resolve(usedStorage.setItem(key, value));
92
- });
93
- },
94
- getItem: function getItem(key) {
95
- return new Promise(function (resolve) {
96
- return resolve(usedStorage.getItem(key));
97
- });
98
- },
99
- removeItem: function removeItem(key) {
100
- return new Promise(function (resolve) {
101
- return resolve(usedStorage.removeItem(key));
102
- });
84
+ function determineStorage(parentStorage) {
85
+ try {
86
+ return window.localStorage;
87
+ } catch (error) {
88
+ if (error.name === 'SecurityError' && parentStorage) {
89
+ return parentStorage;
90
+ }
91
+ return testStorageSupport() ? window.localStorage : index;
103
92
  }
104
- };
93
+ }
94
+ function createAsyncStorage(parentStorage) {
95
+ var usedStorage = determineStorage(parentStorage);
96
+ return {
97
+ setItem: function setItem(key, value) {
98
+ return new Promise(function (resolve) {
99
+ return resolve(usedStorage.setItem(key, value));
100
+ });
101
+ },
102
+ getItem: function getItem(key) {
103
+ return new Promise(function (resolve) {
104
+ return resolve(usedStorage.getItem(key));
105
+ });
106
+ },
107
+ removeItem: function removeItem(key) {
108
+ return new Promise(function (resolve) {
109
+ return resolve(usedStorage.removeItem(key));
110
+ });
111
+ }
112
+ };
113
+ }
114
+ createAsyncStorage();
105
115
 
106
116
  var _ref = {},
107
117
  hasOwnProperty = _ref.hasOwnProperty;
118
+
108
119
  /**
109
120
  * returns true or false depending if the provided property is present inside the provided object
110
121
  * @example
@@ -242,7 +253,6 @@
242
253
  * includes('d', 'abc')
243
254
  * // returns false
244
255
  */
245
-
246
256
  function includes(value, arrOrStr) {
247
257
  return arrOrStr.indexOf(value) !== -1;
248
258
  }
@@ -414,7 +424,7 @@
414
424
  var intersperseWithTabOrNewline = function intersperseWithTabOrNewline(str) {
415
425
  return str.replace(/\w/g, '$&[\\r\\n\\t]*');
416
426
  };
417
- var unsafeProtocol = new RegExp("^[\0-\x1F]*(" + intersperseWithTabOrNewline('javascript') + "|" + intersperseWithTabOrNewline('data') + "):", 'i');
427
+ new RegExp("^[\0-\x1F]*(" + intersperseWithTabOrNewline('javascript') + "|" + intersperseWithTabOrNewline('data') + "):", 'i');
418
428
 
419
429
  var protocolRegexp = /^((http(s)?:)?\/\/)/;
420
430
  var removeProtocol = function removeProtocol(url) {
@@ -468,7 +478,7 @@
468
478
  });
469
479
  }
470
480
 
471
- var ACCOUNTS_URL = "https://accounts.livechatinc.com";
481
+ var ACCOUNTS_URL = process.env.PUBLIC_ACCOUNTS_URL;
472
482
  var buildPath = function buildPath(_ref) {
473
483
  var uniqueGroups = _ref.uniqueGroups,
474
484
  organizationId = _ref.organizationId,
@@ -481,7 +491,7 @@
481
491
  return "" + url + path;
482
492
  };
483
493
 
484
- var createError = function createError(_ref) {
494
+ var createError$1 = function createError(_ref) {
485
495
  var code = _ref.code,
486
496
  message = _ref.message;
487
497
  var err = new Error(message);
@@ -491,13 +501,13 @@
491
501
 
492
502
  var parseTokenResponse = function parseTokenResponse(token, organizationId) {
493
503
  if ('identity_exception' in token) {
494
- throw createError({
504
+ throw createError$1({
495
505
  code: 'SSO_IDENTITY_EXCEPTION',
496
506
  message: token.identity_exception
497
507
  });
498
508
  }
499
509
  if ('oauth_exception' in token) {
500
- throw createError({
510
+ throw createError$1({
501
511
  code: 'SSO_OAUTH_EXCEPTION',
502
512
  message: token.oauth_exception
503
513
  });
@@ -543,39 +553,29 @@
543
553
  expiresIn = _ref.expiresIn;
544
554
  return Date.now() >= creationDate + expiresIn;
545
555
  };
546
- var createAuth = function createAuth(config, licenseId, env) {
556
+ var createAuth = function createAuth(config, parentStorage) {
547
557
  validateConfig(config);
548
- var tokenStoragePrefix = config.tokenStoragePrefix || "@@lc_auth_token:";
549
- var oldCacheKey = "" + tokenStoragePrefix + licenseId + (config.uniqueGroups ? ":" + config.groupId : '');
550
- var newCacheKey = "" + tokenStoragePrefix + config.organizationId + (config.uniqueGroups ? ":" + config.groupId : '');
558
+ var configEnv = config.env;
559
+ var env = configEnv && ['labs', 'staging'].includes(configEnv) ? configEnv : 'production';
560
+ var storage = createAsyncStorage(parentStorage);
561
+ var tokenStoragePrefix = config.tokenStoragePrefix || process.env.PUBLIC_TOKEN_STORAGE_PREFIX;
562
+ var cacheKey = "" + tokenStoragePrefix + config.organizationId + (config.uniqueGroups ? ":" + config.groupId : '');
551
563
  var pendingTokenRequest = null;
552
564
  var cachedToken = null;
553
- var retrievingToken = storage.getItem(oldCacheKey).then(function (token) {
565
+ var retrievingToken = storage.getItem(cacheKey).then(function (token) {
554
566
  if (retrievingToken === null) {
555
567
  return;
556
568
  }
557
569
  retrievingToken = null;
558
570
  if (!token) {
559
- storage.removeItem(oldCacheKey).then(function () {
560
- return storage.getItem(newCacheKey).then(function (newKeyToken) {
561
- if (!newKeyToken) {
562
- return;
563
- }
564
- cachedToken = JSON.parse(newKeyToken);
565
- });
566
- });
567
571
  return;
568
572
  }
569
- storage.setItem(newCacheKey, token).then(function () {
570
- storage.removeItem(oldCacheKey).then(function () {
571
- cachedToken = JSON.parse(token);
572
- });
573
- });
573
+ cachedToken = JSON.parse(token);
574
574
  });
575
575
  var getFreshToken = function getFreshToken() {
576
576
  pendingTokenRequest = fetchToken(config, env).then(function (token) {
577
577
  pendingTokenRequest = null;
578
- storage.setItem(newCacheKey, JSON.stringify(token));
578
+ storage.setItem(cacheKey, JSON.stringify(token));
579
579
  cachedToken = token;
580
580
  return token;
581
581
  }, function (err) {
@@ -584,7 +584,7 @@
584
584
  });
585
585
  return pendingTokenRequest;
586
586
  };
587
- var getToken = function getToken() {
587
+ var _getToken = function getToken() {
588
588
  if (pendingTokenRequest) {
589
589
  return pendingTokenRequest;
590
590
  }
@@ -592,36 +592,37 @@
592
592
  return Promise.resolve(cachedToken);
593
593
  }
594
594
  if (retrievingToken) {
595
- return retrievingToken.then(getToken);
595
+ return retrievingToken.then(_getToken);
596
596
  }
597
597
  return getFreshToken();
598
598
  };
599
- var hasToken = function hasToken() {
599
+ var _hasToken = function hasToken() {
600
600
  if (retrievingToken) {
601
- return retrievingToken.then(hasToken);
601
+ return retrievingToken.then(_hasToken);
602
602
  }
603
603
  return Promise.resolve(!!cachedToken);
604
604
  };
605
605
  var invalidate = function invalidate() {
606
606
  cachedToken = null;
607
607
  retrievingToken = null;
608
- return storage.removeItem(newCacheKey);
608
+ return storage.removeItem(cacheKey);
609
609
  };
610
610
  return {
611
611
  getFreshToken: getFreshToken,
612
- getToken: getToken,
613
- hasToken: hasToken,
612
+ getToken: _getToken,
613
+ hasToken: _hasToken,
614
614
  invalidate: invalidate
615
615
  };
616
616
  };
617
617
 
618
618
  function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}
619
619
 
620
+ var _excluded$6 = ["all"];
620
621
  // Our wrapper over `mitt` starts here
621
622
  var createMitt = function createMitt() {
622
623
  var _mitt = mitt(),
623
624
  all = _mitt.all,
624
- instance = _objectWithoutPropertiesLoose(_mitt, ["all"]);
625
+ instance = _objectWithoutPropertiesLoose(_mitt, _excluded$6);
625
626
  var off = function off(type, handler) {
626
627
  if (!type) {
627
628
  all.clear();
@@ -642,8 +643,198 @@
642
643
  });
643
644
  };
644
645
 
646
+ var FILE = 'file';
647
+ var FORM = 'form';
648
+ var FILLED_FORM = 'filled_form';
649
+ var MESSAGE = 'message';
650
+ var RICH_MESSAGE = 'rich_message';
651
+ var SYSTEM_MESSAGE = 'system_message';
652
+ var CUSTOM = 'custom';
653
+
654
+ var eventTypes = /*#__PURE__*/Object.freeze({
655
+ __proto__: null,
656
+ FILE: FILE,
657
+ FORM: FORM,
658
+ FILLED_FORM: FILLED_FORM,
659
+ MESSAGE: MESSAGE,
660
+ RICH_MESSAGE: RICH_MESSAGE,
661
+ SYSTEM_MESSAGE: SYSTEM_MESSAGE,
662
+ CUSTOM: CUSTOM
663
+ });
664
+
665
+ var _excluded$5 = ["groupId"];
666
+ var createEventBase = function createEventBase(event) {
667
+ var base = {};
668
+ if (typeof event.customId === 'string') {
669
+ base.custom_id = event.customId;
670
+ }
671
+ if (isObject(event.properties)) {
672
+ base.properties = event.properties;
673
+ }
674
+ return base;
675
+ };
676
+
677
+ // TODO: we could validate and throw here
678
+ // but should we? maybe only in DEV mode?
679
+ var parseEvent$1 = function parseEvent(event) {
680
+ switch (event.type) {
681
+ case MESSAGE:
682
+ {
683
+ var message = _extends({}, createEventBase(event), {
684
+ type: event.type,
685
+ text: event.text
686
+ });
687
+ if (event.postback) {
688
+ message.postback = {
689
+ id: event.postback.id,
690
+ thread_id: event.postback.threadId,
691
+ event_id: event.postback.eventId,
692
+ type: event.postback.type,
693
+ value: event.postback.value
694
+ };
695
+ }
696
+ return message;
697
+ }
698
+ case FILE:
699
+ {
700
+ var file = _extends({}, createEventBase(event), {
701
+ type: event.type,
702
+ url: event.url,
703
+ alternative_text: event.alternativeText
704
+ });
705
+ return file;
706
+ }
707
+ case FILLED_FORM:
708
+ {
709
+ var filledForm = _extends({}, createEventBase(event), {
710
+ type: event.type,
711
+ form_id: event.formId
712
+ }, event.formType && {
713
+ form_type: event.formType
714
+ }, {
715
+ fields: event.fields.map(function (field) {
716
+ switch (field.type) {
717
+ case 'group_chooser':
718
+ {
719
+ if (!field.answer) {
720
+ return field;
721
+ }
722
+ var _field$answer = field.answer,
723
+ groupId = _field$answer.groupId,
724
+ answer = _objectWithoutPropertiesLoose(_field$answer, _excluded$5);
725
+ return _extends({}, field, {
726
+ answer: _extends({}, answer, {
727
+ group_id: groupId
728
+ })
729
+ });
730
+ }
731
+ default:
732
+ return field;
733
+ }
734
+ })
735
+ });
736
+ return filledForm;
737
+ }
738
+ case SYSTEM_MESSAGE:
739
+ {
740
+ var systemMessage = _extends({}, createEventBase(event), {
741
+ type: event.type,
742
+ text: event.text,
743
+ system_message_type: event.systemMessageType
744
+ });
745
+ if (event.recipients) {
746
+ systemMessage.recipients = event.recipients;
747
+ }
748
+ return systemMessage;
749
+ }
750
+ case CUSTOM:
751
+ {
752
+ var customEvent = _extends({}, createEventBase(event), {
753
+ type: event.type
754
+ });
755
+ if (event.content) {
756
+ customEvent.content = event.content;
757
+ }
758
+ return customEvent;
759
+ }
760
+ }
761
+ };
762
+ var parseThreadData = function parseThreadData(thread) {
763
+ var data = {};
764
+ var events = thread.events,
765
+ properties = thread.properties;
766
+ if (events) {
767
+ data.events = events.map(parseEvent$1);
768
+ }
769
+ if (properties) {
770
+ data.properties = properties;
771
+ }
772
+ return data;
773
+ };
774
+ var parseStartChatData = function parseStartChatData(_ref) {
775
+ var _ref$active = _ref.active,
776
+ active = _ref$active === void 0 ? true : _ref$active,
777
+ chat = _ref.chat,
778
+ welcomeMessageId = _ref.welcomeMessageId,
779
+ continuous = _ref.continuous;
780
+ var data = {
781
+ active: active,
782
+ chat: {}
783
+ };
784
+ if (typeof continuous === 'boolean') {
785
+ data.continuous = continuous;
786
+ }
787
+ if (welcomeMessageId && typeof welcomeMessageId === 'string') {
788
+ data.welcome_message_id = welcomeMessageId;
789
+ }
790
+ if (!chat) {
791
+ return data;
792
+ }
793
+ var access = chat.access,
794
+ thread = chat.thread,
795
+ properties = chat.properties;
796
+ if (access && access.groupIds) {
797
+ data.chat.access = {
798
+ group_ids: access.groupIds
799
+ };
800
+ }
801
+ if (properties) {
802
+ data.chat.properties = properties;
803
+ }
804
+ if (thread) {
805
+ data.chat.thread = parseThreadData(thread);
806
+ }
807
+ return data;
808
+ };
809
+ var parseResumeChatData = function parseResumeChatData(requestData) {
810
+ var data = parseStartChatData(requestData);
811
+ return _extends({}, data, {
812
+ chat: _extends({}, data.chat, {
813
+ id: requestData.chat.id
814
+ })
815
+ });
816
+ };
817
+ var parseCustomerSessionFields$1 = function parseCustomerSessionFields(sessionFields) {
818
+ return toPairs(sessionFields).map(function (_ref2) {
819
+ var _ref3;
820
+ var key = _ref2[0],
821
+ value = _ref2[1];
822
+ return _ref3 = {}, _ref3[key] = value, _ref3;
823
+ });
824
+ };
825
+ var parseCustomerUpdate = function parseCustomerUpdate(update) {
826
+ var result = pickOwn(['avatar', 'name', 'email'], update);
827
+ if (update.sessionFields) {
828
+ result.session_fields = parseCustomerSessionFields$1(update.sessionFields);
829
+ }
830
+ if (typeof update.nameIsDefault === 'boolean') {
831
+ result.name_is_default = update.nameIsDefault;
832
+ }
833
+ return result;
834
+ };
835
+
645
836
  var CHANGE_REGION = 'change_region';
646
- var CHECK_GOALS = 'check_goals';
837
+ var CHECK_GOALS$1 = 'check_goals';
647
838
  var DESTROY = 'destroy';
648
839
  var FAIL_ALL_REQUESTS = 'fail_all_requests';
649
840
  var LOGIN_SUCCESS = 'login_success';
@@ -662,21 +853,13 @@
662
853
  var SOCKET_RECOVERED = 'socket_recovered';
663
854
  var SOCKET_UNSTABLE = 'socket_unstable';
664
855
  var START_CONNECTION = 'start_connection';
665
- var UPDATE_CUSTOMER_PAGE = 'update_customer_page';
666
-
667
- var CONNECTION_LOST = 'CONNECTION_LOST';
668
- var IDENTITY_MISMATCH = 'IDENTITY_MISMATCH';
669
- var MISDIRECTED_CONNECTION = 'MISDIRECTED_CONNECTION';
670
- var MISSING_CHAT_THREAD = 'MISSING_CHAT_THREAD';
671
- var NO_CONNECTION = 'NO_CONNECTION';
672
- var REQUEST_TIMEOUT = 'REQUEST_TIMEOUT';
673
- var SDK_DESTROYED = 'SDK_DESTROYED';
674
- var SERVICE_TEMPORARILY_UNAVAILABLE = 'SERVICE_TEMPORARILY_UNAVAILABLE';
675
- var TOO_BIG_FILE = 'TOO_BIG_FILE';
856
+ var UPDATE_CUSTOMER_PAGE$1 = 'update_customer_page';
857
+ var CLEAR_SENSITIVE_SESSION_STATE = 'clear_sensitive_session_state';
858
+ var IDENTITY_CHANGED = 'identity_changed';
676
859
 
677
860
  var ACCEPT_GREETING = 'accept_greeting';
678
861
  var CANCEL_GREETING = 'cancel_greeting';
679
- var CHECK_GOALS$1 = 'check_goals';
862
+ var CHECK_GOALS = 'check_goals';
680
863
  var DEACTIVATE_CHAT = 'deactivate_chat';
681
864
  var DELETE_CHAT_PROPERTIES = 'delete_chat_properties';
682
865
  var DELETE_EVENT_PROPERTIES = 'delete_event_properties';
@@ -684,579 +867,316 @@
684
867
  var GET_CHAT = 'get_chat';
685
868
  var GET_CUSTOMER = 'get_customer';
686
869
  var GET_FORM = 'get_form';
687
- var GET_PREDICTED_AGENT = 'get_predicted_agent';
688
870
  var GET_URL_INFO = 'get_url_info';
689
871
  var LIST_CHATS = 'list_chats';
690
872
  var LIST_GROUP_STATUSES = 'list_group_statuses';
691
873
  var LIST_THREADS = 'list_threads';
692
874
  var LOGIN = 'login';
693
875
  var MARK_EVENTS_AS_SEEN = 'mark_events_as_seen';
876
+ var REQUEST_WELCOME_MESSAGE = 'request_welcome_message';
694
877
  var RESUME_CHAT = 'resume_chat';
695
878
  var SEND_EVENT = 'send_event';
879
+ var SEND_GREETING_BUTTON_CLICKED = 'send_greeting_button_clicked';
880
+ var SEND_CUSTOMER_ACTIONS = 'send_customer_actions';
696
881
  var SEND_RICH_MESSAGE_POSTBACK = 'send_rich_message_postback';
697
882
  var SEND_SNEAK_PEEK = 'send_sneak_peek';
698
883
  var SET_CUSTOMER_SESSION_FIELDS = 'set_customer_session_fields';
699
884
  var START_CHAT = 'start_chat';
700
885
  var UPDATE_CHAT_PROPERTIES = 'update_chat_properties';
701
886
  var UPDATE_CUSTOMER = 'update_customer';
702
- var UPDATE_CUSTOMER_PAGE$1 = 'update_customer_page';
887
+ var UPDATE_CUSTOMER_PAGE = 'update_customer_page';
703
888
  var UPDATE_EVENT_PROPERTIES = 'update_event_properties';
704
889
  var UPDATE_THREAD_PROPERTIES = 'update_thread_properties';
705
890
  var UPLOAD_FILE = 'upload_file';
706
891
 
707
- function symbolObservablePonyfill(root) {
708
- var result;
709
- var Symbol = root.Symbol;
710
- if (typeof Symbol === 'function') {
711
- if (Symbol.observable) {
712
- result = Symbol.observable;
713
- } else {
714
- result = Symbol('observable');
715
- Symbol.observable = result;
892
+ var destroy = function destroy(reason) {
893
+ return {
894
+ type: DESTROY,
895
+ payload: {
896
+ reason: reason
716
897
  }
717
- } else {
718
- result = '@@observable';
719
- }
720
- return result;
721
- }
722
-
723
- /* global window */
724
- var root;
725
- if (typeof self !== 'undefined') {
726
- root = self;
727
- } else if (typeof window !== 'undefined') {
728
- root = window;
729
- } else if (typeof global !== 'undefined') {
730
- root = global;
731
- } else if (typeof module !== 'undefined') {
732
- root = module;
733
- } else {
734
- root = Function('return this')();
735
- }
736
- var result = symbolObservablePonyfill(root);
737
-
738
- /**
739
- * These are private action types reserved by Redux.
740
- * For any unknown actions, you must return the current state.
741
- * If the current state is undefined, you must return the initial state.
742
- * Do not reference these action types directly in your code.
743
- */
744
- var randomString = function randomString() {
745
- return Math.random().toString(36).substring(7).split('').join('.');
898
+ };
746
899
  };
747
- var ActionTypes = {
748
- INIT: "@@redux/INIT" + randomString(),
749
- REPLACE: "@@redux/REPLACE" + randomString(),
750
- PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
751
- return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
752
- }
900
+ var loginSuccess = function loginSuccess(payload) {
901
+ return {
902
+ type: LOGIN_SUCCESS,
903
+ payload: payload
904
+ };
753
905
  };
754
-
755
- /**
756
- * @param {any} obj The object to inspect.
757
- * @returns {boolean} True if the argument appears to be a plain object.
758
- */
759
- function isPlainObject(obj) {
760
- if (typeof obj !== 'object' || obj === null) return false;
761
- var proto = obj;
762
- while (Object.getPrototypeOf(proto) !== null) {
763
- proto = Object.getPrototypeOf(proto);
764
- }
765
- return Object.getPrototypeOf(obj) === proto;
766
- }
767
-
768
- /**
769
- * Creates a Redux store that holds the state tree.
770
- * The only way to change the data in the store is to call `dispatch()` on it.
771
- *
772
- * There should only be a single store in your app. To specify how different
773
- * parts of the state tree respond to actions, you may combine several reducers
774
- * into a single reducer function by using `combineReducers`.
775
- *
776
- * @param {Function} reducer A function that returns the next state tree, given
777
- * the current state tree and the action to handle.
778
- *
779
- * @param {any} [preloadedState] The initial state. You may optionally specify it
780
- * to hydrate the state from the server in universal apps, or to restore a
781
- * previously serialized user session.
782
- * If you use `combineReducers` to produce the root reducer function, this must be
783
- * an object with the same shape as `combineReducers` keys.
784
- *
785
- * @param {Function} [enhancer] The store enhancer. You may optionally specify it
786
- * to enhance the store with third-party capabilities such as middleware,
787
- * time travel, persistence, etc. The only store enhancer that ships with Redux
788
- * is `applyMiddleware()`.
789
- *
790
- * @returns {Store} A Redux store that lets you read the state, dispatch actions
791
- * and subscribe to changes.
792
- */
793
-
794
- function createStore(reducer, preloadedState, enhancer) {
795
- var _ref2;
796
- if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
797
- throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function.');
798
- }
799
- if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
800
- enhancer = preloadedState;
801
- preloadedState = undefined;
802
- }
803
- if (typeof enhancer !== 'undefined') {
804
- if (typeof enhancer !== 'function') {
805
- throw new Error('Expected the enhancer to be a function.');
906
+ var pauseConnection = function pauseConnection(reason) {
907
+ return {
908
+ type: PAUSE_CONNECTION,
909
+ payload: {
910
+ reason: reason
806
911
  }
807
- return enhancer(createStore)(reducer, preloadedState);
808
- }
809
- if (typeof reducer !== 'function') {
810
- throw new Error('Expected the reducer to be a function.');
912
+ };
913
+ };
914
+ var prefetchToken = function prefetchToken(fresh) {
915
+ if (fresh === void 0) {
916
+ fresh = false;
811
917
  }
812
- var currentReducer = reducer;
813
- var currentState = preloadedState;
814
- var currentListeners = [];
815
- var nextListeners = currentListeners;
816
- var isDispatching = false;
817
- /**
818
- * This makes a shallow copy of currentListeners so we can use
819
- * nextListeners as a temporary list while dispatching.
820
- *
821
- * This prevents any bugs around consumers calling
822
- * subscribe/unsubscribe in the middle of a dispatch.
823
- */
824
-
825
- function ensureCanMutateNextListeners() {
826
- if (nextListeners === currentListeners) {
827
- nextListeners = currentListeners.slice();
918
+ return {
919
+ type: PREFETCH_TOKEN,
920
+ payload: {
921
+ fresh: fresh
828
922
  }
829
- }
830
- /**
831
- * Reads the state tree managed by the store.
832
- *
833
- * @returns {any} The current state tree of your application.
834
- */
835
-
836
- function getState() {
837
- if (isDispatching) {
838
- throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
923
+ };
924
+ };
925
+ var reconnect = function reconnect(delay) {
926
+ return {
927
+ type: RECONNECT,
928
+ payload: {
929
+ delay: delay
839
930
  }
840
- return currentState;
841
- }
842
- /**
843
- * Adds a change listener. It will be called any time an action is dispatched,
844
- * and some part of the state tree may potentially have changed. You may then
845
- * call `getState()` to read the current state tree inside the callback.
846
- *
847
- * You may call `dispatch()` from a change listener, with the following
848
- * caveats:
849
- *
850
- * 1. The subscriptions are snapshotted just before every `dispatch()` call.
851
- * If you subscribe or unsubscribe while the listeners are being invoked, this
852
- * will not have any effect on the `dispatch()` that is currently in progress.
853
- * However, the next `dispatch()` call, whether nested or not, will use a more
854
- * recent snapshot of the subscription list.
855
- *
856
- * 2. The listener should not expect to see all state changes, as the state
857
- * might have been updated multiple times during a nested `dispatch()` before
858
- * the listener is called. It is, however, guaranteed that all subscribers
859
- * registered before the `dispatch()` started will be called with the latest
860
- * state by the time it exits.
861
- *
862
- * @param {Function} listener A callback to be invoked on every dispatch.
863
- * @returns {Function} A function to remove this change listener.
864
- */
931
+ };
932
+ };
865
933
 
866
- function subscribe(listener) {
867
- if (typeof listener !== 'function') {
868
- throw new Error('Expected the listener to be a function.');
869
- }
870
- if (isDispatching) {
871
- throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
872
- }
873
- var isSubscribed = true;
874
- ensureCanMutateNextListeners();
875
- nextListeners.push(listener);
876
- return function unsubscribe() {
877
- if (!isSubscribed) {
878
- return;
879
- }
880
- if (isDispatching) {
881
- throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
934
+ // TODO: this one was currently pretty hard to type in full
935
+ // we should explore providing stricter types for this in the future
936
+ var sendRequest$1 = function sendRequest(action, payload, source) {
937
+ return {
938
+ type: SEND_REQUEST,
939
+ payload: _extends({
940
+ request: {
941
+ action: action,
942
+ payload: payload
882
943
  }
883
- isSubscribed = false;
884
- ensureCanMutateNextListeners();
885
- var index = nextListeners.indexOf(listener);
886
- nextListeners.splice(index, 1);
887
- };
944
+ }, source && {
945
+ source: source
946
+ })
947
+ };
948
+ };
949
+ var sendEvent = function sendEvent(_ref) {
950
+ var chatId = _ref.chatId,
951
+ event = _ref.event,
952
+ attachToLastThread = _ref.attachToLastThread;
953
+ var payload = {
954
+ chat_id: chatId,
955
+ event: parseEvent$1(event)
956
+ };
957
+ if (attachToLastThread) {
958
+ payload.attach_to_last_thread = true;
888
959
  }
889
- /**
890
- * Dispatches an action. It is the only way to trigger a state change.
891
- *
892
- * The `reducer` function, used to create the store, will be called with the
893
- * current state tree and the given `action`. Its return value will
894
- * be considered the **next** state of the tree, and the change listeners
895
- * will be notified.
896
- *
897
- * The base implementation only supports plain object actions. If you want to
898
- * dispatch a Promise, an Observable, a thunk, or something else, you need to
899
- * wrap your store creating function into the corresponding middleware. For
900
- * example, see the documentation for the `redux-thunk` package. Even the
901
- * middleware will eventually dispatch plain object actions using this method.
902
- *
903
- * @param {Object} action A plain object representing “what changed”. It is
904
- * a good idea to keep actions serializable so you can record and replay user
905
- * sessions, or use the time travelling `redux-devtools`. An action must have
906
- * a `type` property which may not be `undefined`. It is a good idea to use
907
- * string constants for action types.
908
- *
909
- * @returns {Object} For convenience, the same action object you dispatched.
910
- *
911
- * Note that, if you use a custom middleware, it may wrap `dispatch()` to
912
- * return something else (for example, a Promise you can await).
913
- */
914
-
915
- function dispatch(action) {
916
- if (!isPlainObject(action)) {
917
- throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
918
- }
919
- if (typeof action.type === 'undefined') {
920
- throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
921
- }
922
- if (isDispatching) {
923
- throw new Error('Reducers may not dispatch actions.');
960
+ return sendRequest$1(SEND_EVENT, payload);
961
+ };
962
+ var setChatActive = function setChatActive(id, active) {
963
+ return {
964
+ type: SET_CHAT_ACTIVE,
965
+ payload: {
966
+ id: id,
967
+ active: active
924
968
  }
925
- try {
926
- isDispatching = true;
927
- currentState = currentReducer(currentState, action);
928
- } finally {
929
- isDispatching = false;
969
+ };
970
+ };
971
+ var setSelfId = function setSelfId(id) {
972
+ return {
973
+ type: SET_SELF_ID,
974
+ payload: {
975
+ id: id
930
976
  }
931
- var listeners = currentListeners = nextListeners;
932
- for (var i = 0; i < listeners.length; i++) {
933
- var listener = listeners[i];
934
- listener();
935
- }
936
- return action;
937
- }
938
- /**
939
- * Replaces the reducer currently used by the store to calculate the state.
940
- *
941
- * You might need this if your app implements code splitting and you want to
942
- * load some of the reducers dynamically. You might also need this if you
943
- * implement a hot reloading mechanism for Redux.
944
- *
945
- * @param {Function} nextReducer The reducer for the store to use instead.
946
- * @returns {void}
947
- */
948
-
949
- function replaceReducer(nextReducer) {
950
- if (typeof nextReducer !== 'function') {
951
- throw new Error('Expected the nextReducer to be a function.');
952
- }
953
- currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
954
- // Any reducers that existed in both the new and old rootReducer
955
- // will receive the previous state. This effectively populates
956
- // the new state tree with any relevant data from the old one.
977
+ };
978
+ };
979
+ var socketDisconnected = function socketDisconnected() {
980
+ return {
981
+ type: SOCKET_DISCONNECTED
982
+ };
983
+ };
984
+ var clearSensitiveSessionState = function clearSensitiveSessionState() {
985
+ return {
986
+ type: CLEAR_SENSITIVE_SESSION_STATE
987
+ };
988
+ };
989
+ var identityChanged = function identityChanged(payload) {
990
+ return {
991
+ type: IDENTITY_CHANGED,
992
+ payload: payload
993
+ };
994
+ };
957
995
 
958
- dispatch({
959
- type: ActionTypes.REPLACE
960
- });
961
- }
962
- /**
963
- * Interoperability point for observable/reactive libraries.
964
- * @returns {observable} A minimal observable of state changes.
965
- * For more information, see the observable proposal:
966
- * https://github.com/tc39/proposal-observable
967
- */
996
+ var CONNECTION_LOST = 'CONNECTION_LOST';
997
+ var MISDIRECTED_CONNECTION$1 = 'MISDIRECTED_CONNECTION';
998
+ var MISSING_CHAT_THREAD = 'MISSING_CHAT_THREAD';
999
+ var NO_CONNECTION = 'NO_CONNECTION';
1000
+ var REQUEST_TIMEOUT$1 = 'REQUEST_TIMEOUT';
1001
+ var SDK_DESTROYED = 'SDK_DESTROYED';
1002
+ var SERVICE_TEMPORARILY_UNAVAILABLE$1 = 'SERVICE_TEMPORARILY_UNAVAILABLE';
1003
+ var TOO_BIG_FILE = 'TOO_BIG_FILE';
968
1004
 
969
- function observable() {
970
- var _ref;
971
- var outerSubscribe = subscribe;
972
- return _ref = {
973
- /**
974
- * The minimal observable subscription method.
975
- * @param {Object} observer Any object that can be used as an observer.
976
- * The observer object should have a `next` method.
977
- * @returns {subscription} An object with an `unsubscribe` method that can
978
- * be used to unsubscribe the observable from the store, and prevent further
979
- * emission of values from the observable.
980
- */
981
- subscribe: function subscribe(observer) {
982
- if (typeof observer !== 'object' || observer === null) {
983
- throw new TypeError('Expected the observer to be an object.');
984
- }
985
- function observeState() {
986
- if (observer.next) {
987
- observer.next(getState());
988
- }
989
- }
990
- observeState();
991
- var unsubscribe = outerSubscribe(observeState);
992
- return {
993
- unsubscribe: unsubscribe
994
- };
995
- }
996
- }, _ref[result] = function () {
997
- return this;
998
- }, _ref;
999
- } // When a store is created, an "INIT" action is dispatched so that every
1000
- // reducer returns their initial state. This effectively populates
1001
- // the initial state tree.
1005
+ var CONNECTED = 'connected';
1006
+ var DESTROYED = 'destroyed';
1007
+ var DISCONNECTED = 'disconnected';
1008
+ var PAUSED = 'paused';
1009
+ var RECONNECTING = 'reconnecting';
1002
1010
 
1003
- dispatch({
1004
- type: ActionTypes.INIT
1005
- });
1006
- return _ref2 = {
1007
- dispatch: dispatch,
1008
- subscribe: subscribe,
1009
- getState: getState,
1010
- replaceReducer: replaceReducer
1011
- }, _ref2[result] = observable, _ref2;
1012
- }
1011
+ var connectionStatuses = /*#__PURE__*/Object.freeze({
1012
+ __proto__: null,
1013
+ CONNECTED: CONNECTED,
1014
+ DESTROYED: DESTROYED,
1015
+ DISCONNECTED: DISCONNECTED,
1016
+ PAUSED: PAUSED,
1017
+ RECONNECTING: RECONNECTING
1018
+ });
1013
1019
 
1014
- /**
1015
- * Prints a warning in the console if it exists.
1016
- *
1017
- * @param {String} message The warning message.
1018
- * @returns {void}
1019
- */
1020
- function warning(message) {
1021
- /* eslint-disable no-console */
1022
- if (typeof console !== 'undefined' && typeof console.error === 'function') {
1023
- console.error(message);
1024
- }
1025
- /* eslint-enable no-console */
1020
+ var ACCESS_TOKEN_EXPIRED = 'access_token_expired';
1021
+ var CONNECTION_TIMEOUT = 'connection_timeout';
1022
+ var CUSTOMER_BANNED$1 = 'customer_banned';
1023
+ // customer tried reconnecting too many times after they received too_many_connections error
1024
+ var CUSTOMER_TEMPORARILY_BLOCKED = 'customer_temporarily_blocked';
1025
+ var INACTIVITY_TIMEOUT = 'inactivity_timeout';
1026
+ var INTERNAL_ERROR = 'internal_error';
1027
+ var LICENSE_EXPIRED$1 = 'license_expired';
1028
+ var LICENSE_NOT_FOUND = 'license_not_found';
1029
+ var MISDIRECTED_CONNECTION = 'misdirected_connection';
1030
+ var PRODUCT_VERSION_CHANGED = 'product_version_changed';
1031
+ // the limit of connections per user host has been exceeded
1032
+ // or rate limit for new connections has been hit
1033
+ // (in 3.2 only the latter case, the first one is using `too_many_connections` to avoid breaking changes)
1034
+ var SERVICE_TEMPORARILY_UNAVAILABLE = 'service_temporarily_unavailable';
1035
+ // the limit of those connections is per user
1036
+ var TOO_MANY_CONNECTIONS = 'too_many_connections';
1037
+ // the limit of unauthorized connections is per IP
1038
+ var TOO_MANY_UNAUTHORIZED_CONNECTIONS = 'too_many_unauthorized_connections';
1039
+ var UNSUPPORTED_VERSION$1 = 'unsupported_version';
1040
+ // introduced in 3.5 meaning the customer was logged out by the server
1041
+ var LOGGED_OUT_REMOTELY = 'logged_out_remotely';
1026
1042
 
1027
- try {
1028
- // This error was thrown as a convenience so that if you enable
1029
- // "break on all exceptions" in your console,
1030
- // it would pause the execution at this line.
1031
- throw new Error(message);
1032
- } catch (e) {} // eslint-disable-line no-empty
1033
- }
1034
- function _defineProperty(obj, key, value) {
1035
- if (key in obj) {
1036
- Object.defineProperty(obj, key, {
1037
- value: value,
1038
- enumerable: true,
1039
- configurable: true,
1040
- writable: true
1041
- });
1042
- } else {
1043
- obj[key] = value;
1044
- }
1045
- return obj;
1046
- }
1047
- function ownKeys(object, enumerableOnly) {
1048
- var keys = Object.keys(object);
1049
- if (Object.getOwnPropertySymbols) {
1050
- keys.push.apply(keys, Object.getOwnPropertySymbols(object));
1051
- }
1052
- if (enumerableOnly) keys = keys.filter(function (sym) {
1053
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
1054
- });
1055
- return keys;
1056
- }
1057
- function _objectSpread2(target) {
1058
- for (var i = 1; i < arguments.length; i++) {
1059
- var source = arguments[i] != null ? arguments[i] : {};
1060
- if (i % 2) {
1061
- ownKeys(source, true).forEach(function (key) {
1062
- _defineProperty(target, key, source[key]);
1063
- });
1064
- } else if (Object.getOwnPropertyDescriptors) {
1065
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1066
- } else {
1067
- ownKeys(source).forEach(function (key) {
1068
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1069
- });
1070
- }
1071
- }
1072
- return target;
1073
- }
1043
+ var serverDisconnectionReasons = /*#__PURE__*/Object.freeze({
1044
+ __proto__: null,
1045
+ ACCESS_TOKEN_EXPIRED: ACCESS_TOKEN_EXPIRED,
1046
+ CONNECTION_TIMEOUT: CONNECTION_TIMEOUT,
1047
+ CUSTOMER_BANNED: CUSTOMER_BANNED$1,
1048
+ CUSTOMER_TEMPORARILY_BLOCKED: CUSTOMER_TEMPORARILY_BLOCKED,
1049
+ INACTIVITY_TIMEOUT: INACTIVITY_TIMEOUT,
1050
+ INTERNAL_ERROR: INTERNAL_ERROR,
1051
+ LICENSE_EXPIRED: LICENSE_EXPIRED$1,
1052
+ LICENSE_NOT_FOUND: LICENSE_NOT_FOUND,
1053
+ MISDIRECTED_CONNECTION: MISDIRECTED_CONNECTION,
1054
+ PRODUCT_VERSION_CHANGED: PRODUCT_VERSION_CHANGED,
1055
+ SERVICE_TEMPORARILY_UNAVAILABLE: SERVICE_TEMPORARILY_UNAVAILABLE,
1056
+ TOO_MANY_CONNECTIONS: TOO_MANY_CONNECTIONS,
1057
+ TOO_MANY_UNAUTHORIZED_CONNECTIONS: TOO_MANY_UNAUTHORIZED_CONNECTIONS,
1058
+ UNSUPPORTED_VERSION: UNSUPPORTED_VERSION$1,
1059
+ LOGGED_OUT_REMOTELY: LOGGED_OUT_REMOTELY
1060
+ });
1074
1061
 
1075
- /**
1076
- * Composes single-argument functions from right to left. The rightmost
1077
- * function can take multiple arguments as it provides the signature for
1078
- * the resulting composite function.
1079
- *
1080
- * @param {...Function} funcs The functions to compose.
1081
- * @returns {Function} A function obtained by composing the argument functions
1082
- * from right to left. For example, compose(f, g, h) is identical to doing
1083
- * (...args) => f(g(h(...args))).
1084
- */
1085
- function compose() {
1086
- for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
1087
- funcs[_key] = arguments[_key];
1088
- }
1089
- if (funcs.length === 0) {
1090
- return function (arg) {
1091
- return arg;
1092
- };
1093
- }
1094
- if (funcs.length === 1) {
1095
- return funcs[0];
1096
- }
1097
- return funcs.reduce(function (a, b) {
1098
- return function () {
1099
- return a(b.apply(void 0, arguments));
1100
- };
1101
- });
1102
- }
1062
+ var AUTHENTICATION = 'AUTHENTICATION';
1063
+ var AUTHORIZATION = 'AUTHORIZATION';
1064
+ var CHAT_ALREADY_ACTIVE = 'CHAT_ALREADY_ACTIVE';
1065
+ var CHAT_LIMIT_REACHED = 'CHAT_LIMIT_REACHED';
1066
+ var CUSTOMER_BANNED = 'CUSTOMER_BANNED';
1067
+ var CUSTOMER_SESSION_FIELDS_LIMIT_REACHED = 'CUSTOMER_SESSION_FIELDS_LIMIT_REACHED';
1068
+ var ENTITY_TOO_LARGE = 'ENTITY_TOO_LARGE';
1069
+ var GREETING_NOT_FOUND = 'GREETING_NOT_FOUND';
1070
+ var GROUP_OFFLINE = 'GROUP_OFFLINE';
1071
+ var GROUPS_OFFLINE = 'GROUPS_OFFLINE';
1072
+ var GROUP_NOT_FOUND = 'GROUP_NOT_FOUND';
1073
+ var GROUP_UNAVAILABLE = 'GROUP_UNAVAILABLE';
1074
+ var INTERNAL = 'INTERNAL';
1075
+ var LICENSE_EXPIRED = 'LICENSE_EXPIRED';
1076
+ // actually this can happen only when using REST
1077
+ var MISDIRECTED_REQUEST = 'MISDIRECTED_REQUEST';
1078
+ var PENDING_REQUESTS_LIMIT_REACHED = 'PENDING_REQUESTS_LIMIT_REACHED';
1079
+ var REQUEST_TIMEOUT = 'REQUEST_TIMEOUT';
1080
+ var SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE';
1081
+ var UNSUPPORTED_VERSION = 'UNSUPPORTED_VERSION';
1082
+ var USERS_LIMIT_REACHED = 'USERS_LIMIT_REACHED';
1083
+ var VALIDATION = 'VALIDATION';
1084
+ var WRONG_PRODUCT_VERSION = 'WRONG_PRODUCT_VERSION';
1103
1085
 
1104
- /**
1105
- * Creates a store enhancer that applies middleware to the dispatch method
1106
- * of the Redux store. This is handy for a variety of tasks, such as expressing
1107
- * asynchronous actions in a concise manner, or logging every action payload.
1108
- *
1109
- * See `redux-thunk` package as an example of the Redux middleware.
1110
- *
1111
- * Because middleware is potentially asynchronous, this should be the first
1112
- * store enhancer in the composition chain.
1113
- *
1114
- * Note that each middleware will be given the `dispatch` and `getState` functions
1115
- * as named arguments.
1116
- *
1117
- * @param {...Function} middlewares The middleware chain to be applied.
1118
- * @returns {Function} A store enhancer applying the middleware.
1119
- */
1120
-
1121
- function applyMiddleware() {
1122
- for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
1123
- middlewares[_key] = arguments[_key];
1124
- }
1125
- return function (createStore) {
1126
- return function () {
1127
- var store = createStore.apply(void 0, arguments);
1128
- var _dispatch = function dispatch() {
1129
- throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
1130
- };
1131
- var middlewareAPI = {
1132
- getState: store.getState,
1133
- dispatch: function dispatch() {
1134
- return _dispatch.apply(void 0, arguments);
1135
- }
1136
- };
1137
- var chain = middlewares.map(function (middleware) {
1138
- return middleware(middlewareAPI);
1139
- });
1140
- _dispatch = compose.apply(void 0, chain)(store.dispatch);
1141
- return _objectSpread2({}, store, {
1142
- dispatch: _dispatch
1143
- });
1144
- };
1145
- };
1146
- }
1147
-
1148
- /*
1149
- * This is a dummy function to check if the function name has been altered by minification.
1150
- * If the function has been minified and NODE_ENV !== 'production', warn the user.
1151
- */
1152
-
1153
- function isCrushed() {}
1154
- if ( typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
1155
- warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
1156
- }
1157
-
1158
- var createSideEffectsMiddleware = function createSideEffectsMiddleware() {
1159
- var handlers = [];
1160
- var sideEffectsMiddleware = function sideEffectsMiddleware(store) {
1161
- return function (next) {
1162
- return function (action) {
1163
- var result = next(action);
1164
- handlers.forEach(function (handler) {
1165
- handler(action, store);
1166
- });
1167
- return result;
1168
- };
1169
- };
1170
- };
1171
- sideEffectsMiddleware.add = function (handler) {
1172
- handlers.push(handler);
1173
- };
1174
- return sideEffectsMiddleware;
1175
- };
1176
-
1177
- var createBackoff = function createBackoff(_ref) {
1178
- var _ref$min = _ref.min,
1179
- min = _ref$min === void 0 ? 1000 : _ref$min,
1180
- _ref$max = _ref.max,
1181
- max = _ref$max === void 0 ? 5000 : _ref$max,
1182
- _ref$jitter = _ref.jitter,
1183
- jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1184
- var attempts = 0;
1185
- return {
1186
- duration: function duration() {
1187
- var ms = min * Math.pow(2, attempts++);
1188
- if (jitter) {
1189
- var rand = Math.random();
1190
- var deviation = Math.floor(rand * jitter * ms);
1191
- ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1192
- }
1193
- return Math.min(ms, max) | 0;
1194
- },
1195
- reset: function reset() {
1196
- attempts = 0;
1197
- }
1198
- };
1199
- };
1200
-
1201
- /**
1202
- * 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.
1203
- * @param anyFunction - function to be called
1204
- * @returns promise that resolves to the return value of the function
1205
- * @example
1206
- * const promise = promiseTry(() => 1)
1207
- * promise.then(value => console.log(value)) // 1
1208
- */
1209
-
1210
- function promiseTry(anyFunction) {
1211
- return new Promise(function (resolve) {
1212
- resolve(anyFunction());
1213
- });
1214
- }
1215
-
1216
- /**
1217
- * Creates a deferred object that can be resolved or rejected later.
1218
- * @returns A deferred object with a promise and resolve and reject functions.
1219
- * @example
1220
- * const def = promiseDeferred()
1221
- * const promise = def.promise
1222
- * def.resolve(1)
1223
- * return promise.then(res => console.log(res)) // 1
1224
- */
1086
+ var serverErrorCodes = /*#__PURE__*/Object.freeze({
1087
+ __proto__: null,
1088
+ AUTHENTICATION: AUTHENTICATION,
1089
+ AUTHORIZATION: AUTHORIZATION,
1090
+ CHAT_ALREADY_ACTIVE: CHAT_ALREADY_ACTIVE,
1091
+ CHAT_LIMIT_REACHED: CHAT_LIMIT_REACHED,
1092
+ CUSTOMER_BANNED: CUSTOMER_BANNED,
1093
+ CUSTOMER_SESSION_FIELDS_LIMIT_REACHED: CUSTOMER_SESSION_FIELDS_LIMIT_REACHED,
1094
+ ENTITY_TOO_LARGE: ENTITY_TOO_LARGE,
1095
+ GREETING_NOT_FOUND: GREETING_NOT_FOUND,
1096
+ GROUP_OFFLINE: GROUP_OFFLINE,
1097
+ GROUPS_OFFLINE: GROUPS_OFFLINE,
1098
+ GROUP_NOT_FOUND: GROUP_NOT_FOUND,
1099
+ GROUP_UNAVAILABLE: GROUP_UNAVAILABLE,
1100
+ INTERNAL: INTERNAL,
1101
+ LICENSE_EXPIRED: LICENSE_EXPIRED,
1102
+ MISDIRECTED_REQUEST: MISDIRECTED_REQUEST,
1103
+ PENDING_REQUESTS_LIMIT_REACHED: PENDING_REQUESTS_LIMIT_REACHED,
1104
+ REQUEST_TIMEOUT: REQUEST_TIMEOUT,
1105
+ SERVICE_UNAVAILABLE: SERVICE_UNAVAILABLE,
1106
+ UNSUPPORTED_VERSION: UNSUPPORTED_VERSION,
1107
+ USERS_LIMIT_REACHED: USERS_LIMIT_REACHED,
1108
+ VALIDATION: VALIDATION,
1109
+ WRONG_PRODUCT_VERSION: WRONG_PRODUCT_VERSION
1110
+ });
1225
1111
 
1226
- function promiseDeferred() {
1227
- var deferred = {};
1228
- deferred.promise = new Promise(function (resolve, reject) {
1229
- deferred.resolve = resolve;
1230
- deferred.reject = reject;
1231
- });
1232
- return deferred;
1233
- }
1112
+ var CHAT_DEACTIVATED = 'chat_deactivated';
1113
+ var CHAT_PROPERTIES_DELETED = 'chat_properties_deleted';
1114
+ var CHAT_PROPERTIES_UPDATED = 'chat_properties_updated';
1115
+ var CHAT_TRANSFERRED = 'chat_transferred';
1116
+ var CUSTOMER_DISCONNECTED = 'customer_disconnected';
1117
+ var CUSTOMER_SIDE_STORAGE_UPDATED = 'customer_side_storage_updated';
1118
+ var CUSTOMER_UPDATED = 'customer_updated';
1119
+ var EVENT_PROPERTIES_DELETED = 'event_properties_deleted';
1120
+ var EVENT_PROPERTIES_UPDATED = 'event_properties_updated';
1121
+ var EVENT_UPDATED = 'event_updated';
1122
+ var EVENTS_MARKED_AS_SEEN = 'events_marked_as_seen';
1123
+ var GREETING_ACCEPTED = 'greeting_accepted';
1124
+ var GREETING_CANCELED = 'greeting_canceled';
1125
+ var GROUPS_STATUS_UPDATED = 'groups_status_updated';
1126
+ var INCOMING_CHAT = 'incoming_chat';
1127
+ var INCOMING_EVENT = 'incoming_event';
1128
+ var INCOMING_GREETING = 'incoming_greeting';
1129
+ var INCOMING_MULTICAST = 'incoming_multicast';
1130
+ var INCOMING_RICH_MESSAGE_POSTBACK = 'incoming_rich_message_postback';
1131
+ var INCOMING_TYPING_INDICATOR = 'incoming_typing_indicator';
1132
+ var INCOMING_WELCOME_MESSAGE = 'incoming_welcome_message';
1133
+ var QUEUE_POSITION_UPDATED = 'queue_position_updated';
1134
+ var THREAD_PROPERTIES_DELETED = 'thread_properties_deleted';
1135
+ var THREAD_PROPERTIES_UPDATED = 'thread_properties_updated';
1136
+ var USER_ADDED_TO_CHAT = 'user_added_to_chat';
1137
+ var USER_REMOVED_FROM_CHAT = 'user_removed_from_chat';
1138
+ var INCOMING_THINKING_INDICATOR = 'incoming_thinking_indicator';
1139
+ var INCOMING_EVENT_PREVIEW = 'incoming_event_preview';
1234
1140
 
1235
- var createReducer = function createReducer(initialState, reducersMap) {
1236
- return function reducer(state, action) {
1237
- if (state === void 0) {
1238
- state = initialState;
1239
- }
1240
- if (hasOwn(action.type, reducersMap)) {
1241
- return reducersMap[action.type](state, action.payload);
1242
- }
1243
- return state;
1244
- };
1245
- };
1141
+ var serverPushActions = /*#__PURE__*/Object.freeze({
1142
+ __proto__: null,
1143
+ CHAT_DEACTIVATED: CHAT_DEACTIVATED,
1144
+ CHAT_PROPERTIES_DELETED: CHAT_PROPERTIES_DELETED,
1145
+ CHAT_PROPERTIES_UPDATED: CHAT_PROPERTIES_UPDATED,
1146
+ CHAT_TRANSFERRED: CHAT_TRANSFERRED,
1147
+ CUSTOMER_DISCONNECTED: CUSTOMER_DISCONNECTED,
1148
+ CUSTOMER_SIDE_STORAGE_UPDATED: CUSTOMER_SIDE_STORAGE_UPDATED,
1149
+ CUSTOMER_UPDATED: CUSTOMER_UPDATED,
1150
+ EVENT_PROPERTIES_DELETED: EVENT_PROPERTIES_DELETED,
1151
+ EVENT_PROPERTIES_UPDATED: EVENT_PROPERTIES_UPDATED,
1152
+ EVENT_UPDATED: EVENT_UPDATED,
1153
+ EVENTS_MARKED_AS_SEEN: EVENTS_MARKED_AS_SEEN,
1154
+ GREETING_ACCEPTED: GREETING_ACCEPTED,
1155
+ GREETING_CANCELED: GREETING_CANCELED,
1156
+ GROUPS_STATUS_UPDATED: GROUPS_STATUS_UPDATED,
1157
+ INCOMING_CHAT: INCOMING_CHAT,
1158
+ INCOMING_EVENT: INCOMING_EVENT,
1159
+ INCOMING_GREETING: INCOMING_GREETING,
1160
+ INCOMING_MULTICAST: INCOMING_MULTICAST,
1161
+ INCOMING_RICH_MESSAGE_POSTBACK: INCOMING_RICH_MESSAGE_POSTBACK,
1162
+ INCOMING_TYPING_INDICATOR: INCOMING_TYPING_INDICATOR,
1163
+ INCOMING_WELCOME_MESSAGE: INCOMING_WELCOME_MESSAGE,
1164
+ QUEUE_POSITION_UPDATED: QUEUE_POSITION_UPDATED,
1165
+ THREAD_PROPERTIES_DELETED: THREAD_PROPERTIES_DELETED,
1166
+ THREAD_PROPERTIES_UPDATED: THREAD_PROPERTIES_UPDATED,
1167
+ USER_ADDED_TO_CHAT: USER_ADDED_TO_CHAT,
1168
+ USER_REMOVED_FROM_CHAT: USER_REMOVED_FROM_CHAT,
1169
+ INCOMING_THINKING_INDICATOR: INCOMING_THINKING_INDICATOR,
1170
+ INCOMING_EVENT_PREVIEW: INCOMING_EVENT_PREVIEW
1171
+ });
1246
1172
 
1247
- var CONNECTED = 'connected';
1248
- var DESTROYED = 'destroyed';
1249
- var DISCONNECTED = 'disconnected';
1250
- var PAUSED = 'paused';
1251
- var RECONNECTING = 'reconnecting';
1173
+ var ASC = 'asc';
1174
+ var DESC = 'desc';
1252
1175
 
1253
- var connectionStatuses = /*#__PURE__*/Object.freeze({
1176
+ var sortOrders = /*#__PURE__*/Object.freeze({
1254
1177
  __proto__: null,
1255
- CONNECTED: CONNECTED,
1256
- DESTROYED: DESTROYED,
1257
- DISCONNECTED: DISCONNECTED,
1258
- PAUSED: PAUSED,
1259
- RECONNECTING: RECONNECTING
1178
+ ASC: ASC,
1179
+ DESC: DESC
1260
1180
  });
1261
1181
 
1262
1182
  var AGENT = 'agent';
@@ -1268,181 +1188,100 @@
1268
1188
  CUSTOMER: CUSTOMER
1269
1189
  });
1270
1190
 
1271
- var LIVECHAT_ORGANIZATION_ID = 'feaf6c0e-9f43-48ff-9ad0-8e24e0350932';
1272
-
1273
- var getAllRequests = function getAllRequests(state) {
1274
- return state.requests;
1275
- };
1276
- var getConnectionStatus = function getConnectionStatus(state) {
1277
- return state.connection.status;
1278
- };
1279
- var getRequest = function getRequest(state, id) {
1280
- return state.requests[id];
1281
- };
1282
- var getSelfId = function getSelfId(state) {
1283
- return state.users.self.id;
1284
- };
1285
- var isChatActive = function isChatActive(state, chatId) {
1286
- var chat = state.chats[chatId];
1287
- return !!chat && chat.active;
1288
- };
1289
- var isConnected = function isConnected(state) {
1290
- return getConnectionStatus(state) === CONNECTED;
1291
- };
1292
- var isDestroyed = function isDestroyed(state) {
1293
- return getConnectionStatus(state) === DESTROYED;
1191
+ var HISTORY_EVENT_COUNT_TARGET = 25;
1192
+ var createState = function createState() {
1193
+ return {
1194
+ status: 'idle',
1195
+ queuedTasks: [],
1196
+ nextPageId: null
1197
+ };
1294
1198
  };
1295
- var getEnvPart = function getEnvPart(_ref) {
1296
- var organizationId = _ref.organizationId,
1297
- env = _ref.env;
1298
- if (organizationId === LIVECHAT_ORGANIZATION_ID) {
1299
- return '.staging';
1300
- }
1301
- if (env === 'production') {
1302
- return '';
1303
- }
1304
- return "." + env;
1305
- };
1306
- var getApiOrigin = function getApiOrigin(state) {
1307
- var region = state.region;
1308
- var regionPart = region ? "-" + region : '';
1309
- return "https://api" + regionPart + getEnvPart(state) + ".livechatinc.com";
1310
- };
1311
- var getServerUrl = function getServerUrl(state) {
1312
- return getApiOrigin(state) + "/v3.5/customer";
1313
- };
1314
- var createInitialState = function createInitialState(initialStateData) {
1315
- var _initialStateData$app = initialStateData.application,
1316
- application = _initialStateData$app === void 0 ? {} : _initialStateData$app,
1317
- organizationId = initialStateData.organizationId,
1318
- _initialStateData$gro = initialStateData.groupId,
1319
- groupId = _initialStateData$gro === void 0 ? null : _initialStateData$gro,
1320
- env = initialStateData.env,
1321
- _initialStateData$pag = initialStateData.page,
1322
- page = _initialStateData$pag === void 0 ? null : _initialStateData$pag,
1323
- _initialStateData$reg = initialStateData.region,
1324
- region = _initialStateData$reg === void 0 ? null : _initialStateData$reg,
1325
- _initialStateData$ref = initialStateData.referrer,
1326
- referrer = _initialStateData$ref === void 0 ? null : _initialStateData$ref,
1327
- _initialStateData$uni = initialStateData.uniqueGroups,
1328
- uniqueGroups = _initialStateData$uni === void 0 ? false : _initialStateData$uni,
1329
- _initialStateData$mob = initialStateData.mobile,
1330
- mobile = _initialStateData$mob === void 0 ? false : _initialStateData$mob;
1331
- return {
1332
- application: _extends({}, application, {
1333
- name: "customer_sdk",
1334
- version: "4.0.2"
1335
- }),
1336
- organizationId: organizationId,
1337
- env: env,
1338
- groupId: groupId,
1339
- chats: {},
1340
- connection: {
1341
- status: DISCONNECTED
1342
- },
1343
- page: page,
1344
- region: region,
1345
- referrer: referrer,
1346
- requests: {},
1347
- users: {
1348
- self: {
1349
- id: null,
1350
- type: CUSTOMER
1351
- },
1352
- others: {}
1353
- },
1354
- uniqueGroups: uniqueGroups,
1355
- mobile: mobile
1356
- };
1357
- };
1358
- var removeStoredRequest = function removeStoredRequest(state, _ref2) {
1359
- var id = _ref2.id;
1360
- var _state$requests = state.requests,
1361
- requests = _objectWithoutPropertiesLoose(_state$requests, [id].map(_toPropertyKey));
1362
- return _extends({}, state, {
1363
- requests: requests
1199
+ var createChatHistoryIterator = function createChatHistoryIterator(sdk, chatId) {
1200
+ var historyState = createState();
1201
+ var next = function (_next) {
1202
+ function next(_x, _x2) {
1203
+ return _next.apply(this, arguments);
1204
+ }
1205
+ next.toString = function () {
1206
+ return _next.toString();
1207
+ };
1208
+ return next;
1209
+ }(function (resolve, reject) {
1210
+ switch (historyState.status) {
1211
+ case 'idle':
1212
+ historyState.status = 'fetching';
1213
+ sdk.listThreads(historyState.nextPageId ? {
1214
+ chatId: chatId,
1215
+ pageId: historyState.nextPageId
1216
+ } : {
1217
+ chatId: chatId,
1218
+ minEventsCount: HISTORY_EVENT_COUNT_TARGET
1219
+ }).then(function (_ref) {
1220
+ var threads = _ref.threads,
1221
+ nextPageId = _ref.nextPageId;
1222
+ historyState.nextPageId = nextPageId;
1223
+ if (!historyState.nextPageId) {
1224
+ historyState.status = 'done';
1225
+ resolve({
1226
+ value: {
1227
+ threads: [].concat(threads).reverse()
1228
+ },
1229
+ done: true
1230
+ });
1231
+ } else {
1232
+ historyState.status = 'idle';
1233
+ resolve({
1234
+ value: {
1235
+ threads: [].concat(threads).reverse()
1236
+ },
1237
+ done: false
1238
+ });
1239
+ }
1240
+ var queuedTask = historyState.queuedTasks.shift();
1241
+ if (!queuedTask) {
1242
+ return;
1243
+ }
1244
+ next(queuedTask.resolve, queuedTask.reject);
1245
+ }, function (err) {
1246
+ var queuedTasks = historyState.queuedTasks;
1247
+ historyState.status = 'idle';
1248
+ historyState.queuedTasks = [];
1249
+ reject(err);
1250
+ queuedTasks.forEach(function (queuedTask) {
1251
+ return queuedTask.reject(err);
1252
+ });
1253
+ });
1254
+ return;
1255
+ case 'fetching':
1256
+ historyState.queuedTasks.push({
1257
+ resolve: resolve,
1258
+ reject: reject
1259
+ });
1260
+ return;
1261
+ case 'done':
1262
+ resolve({
1263
+ value: undefined,
1264
+ done: true
1265
+ });
1266
+ return;
1267
+ }
1364
1268
  });
1365
- };
1366
- var setConnectionStatus = function setConnectionStatus(status, state) {
1367
- return _extends({}, state, {
1368
- connection: _extends({}, state.connection, {
1369
- status: status
1269
+ return {
1270
+ next: function (_next2) {
1271
+ function next() {
1272
+ return _next2.apply(this, arguments);
1273
+ }
1274
+ next.toString = function () {
1275
+ return _next2.toString();
1276
+ };
1277
+ return next;
1278
+ }(function () {
1279
+ return new Promise(next);
1370
1280
  })
1371
- });
1281
+ };
1372
1282
  };
1373
- var createReducer$1 = (function (state) {
1374
- var _createReducer;
1375
- return createReducer(state, (_createReducer = {}, _createReducer[CHANGE_REGION] = function (state, _ref3) {
1376
- var region = _ref3.region;
1377
- return _extends({}, state, {
1378
- region: region
1379
- });
1380
- }, _createReducer[DESTROY] = function (state) {
1381
- return setConnectionStatus(DESTROYED, state);
1382
- }, _createReducer[LOGIN_SUCCESS] = function (state) {
1383
- return setConnectionStatus(CONNECTED, state);
1384
- }, _createReducer[PAUSE_CONNECTION] = function (state) {
1385
- return setConnectionStatus(PAUSED, state);
1386
- }, _createReducer[REQUEST_FAILED] = removeStoredRequest, _createReducer[RESPONSE_RECEIVED] = removeStoredRequest, _createReducer[PUSH_RESPONSE_RECEIVED] = removeStoredRequest, _createReducer[SEND_REQUEST] = function (state, _ref4) {
1387
- var _extends2;
1388
- var promise = _ref4.promise,
1389
- resolve = _ref4.resolve,
1390
- reject = _ref4.reject,
1391
- id = _ref4.id,
1392
- request = _ref4.request;
1393
- return _extends({}, state, {
1394
- requests: _extends({}, state.requests, (_extends2 = {}, _extends2[id] = {
1395
- id: id,
1396
- promise: promise,
1397
- resolve: resolve,
1398
- reject: reject,
1399
- request: request
1400
- }, _extends2))
1401
- });
1402
- }, _createReducer[SET_CHAT_ACTIVE] = function (state, _ref5) {
1403
- var _extends3;
1404
- var id = _ref5.id,
1405
- active = _ref5.active;
1406
- return _extends({}, state, {
1407
- chats: _extends({}, state.chats, (_extends3 = {}, _extends3[id] = _extends({}, state.chats[id], {
1408
- active: active
1409
- }), _extends3))
1410
- });
1411
- }, _createReducer[SET_SELF_ID] = function (state, payload) {
1412
- return _extends({}, state, {
1413
- users: _extends({}, state.users, {
1414
- self: _extends({}, state.users.self, {
1415
- id: payload.id
1416
- })
1417
- })
1418
- });
1419
- }, _createReducer[SOCKET_DISCONNECTED] = function (state) {
1420
- var previousStatus = getConnectionStatus(state);
1421
- if ( (previousStatus === PAUSED || previousStatus === DESTROYED)) {
1422
- throw new Error("Got 'socket_disconnected' action when in " + previousStatus + " state. This should be an impossible state.");
1423
- }
1424
- var state1 = setConnectionStatus(previousStatus === DISCONNECTED ? DISCONNECTED : RECONNECTING, state);
1425
- return _extends({}, state1, {
1426
- requests: {}
1427
- });
1428
- }, _createReducer[UPDATE_CUSTOMER_PAGE] = function (state, page) {
1429
- return _extends({}, state, {
1430
- page: _extends({}, state.page, page)
1431
- });
1432
- }, _createReducer));
1433
- });
1434
-
1435
- function finalCreateStore(initialStateData) {
1436
- var compose = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
1437
- name: '@livechat/customer-sdk'
1438
- }) : identity;
1439
- var sideEffectsMiddleware = createSideEffectsMiddleware();
1440
- var store = createStore(createReducer$1(createInitialState(initialStateData)), compose(applyMiddleware(sideEffectsMiddleware)));
1441
- store.addSideEffectsHandler = sideEffectsMiddleware.add;
1442
- return store;
1443
- }
1444
1283
 
1445
- function createError$1(_ref) {
1284
+ function createError(_ref) {
1446
1285
  var message = _ref.message,
1447
1286
  code = _ref.code;
1448
1287
  var error = new Error(message);
@@ -1450,729 +1289,844 @@
1450
1289
  return error;
1451
1290
  }
1452
1291
 
1453
- var ACCESS_TOKEN_EXPIRED = 'access_token_expired';
1454
- var CONNECTION_TIMEOUT = 'connection_timeout';
1455
- var CUSTOMER_BANNED = 'customer_banned';
1456
- // customer tried reconnecting too many times after they received too_many_connections error
1457
- var CUSTOMER_TEMPORARILY_BLOCKED = 'customer_temporarily_blocked';
1458
- var INACTIVITY_TIMEOUT = 'inactivity_timeout';
1459
- var INTERNAL_ERROR = 'internal_error';
1460
- var LICENSE_EXPIRED = 'license_expired';
1461
- var LICENSE_NOT_FOUND = 'license_not_found';
1462
- var MISDIRECTED_CONNECTION$1 = 'misdirected_connection';
1463
- var PRODUCT_VERSION_CHANGED = 'product_version_changed';
1464
- // the limit of connections per user host has been exceeded
1465
- // or rate limit for new connections has been hit
1466
- // (in 3.2 only the latter case, the first one is using `too_many_connections` to avoid breaking changes)
1467
- var SERVICE_TEMPORARILY_UNAVAILABLE$1 = 'service_temporarily_unavailable';
1468
- // the limit of those connections is per user
1469
- var TOO_MANY_CONNECTIONS = 'too_many_connections';
1470
- // the limit of unauthorized connections is per IP
1471
- var TOO_MANY_UNAUTHORIZED_CONNECTIONS = 'too_many_unauthorized_connections';
1472
- var UNSUPPORTED_VERSION = 'unsupported_version';
1473
- // introduced in 3.5 meaning the customer was logged out by the server
1474
- var LOGGED_OUT_REMOTELY = 'logged_out_remotely';
1292
+ function symbolObservablePonyfill(root) {
1293
+ var result;
1294
+ var Symbol = root.Symbol;
1295
+ if (typeof Symbol === 'function') {
1296
+ if (Symbol.observable) {
1297
+ result = Symbol.observable;
1298
+ } else {
1299
+ result = Symbol('observable');
1300
+ Symbol.observable = result;
1301
+ }
1302
+ } else {
1303
+ result = '@@observable';
1304
+ }
1305
+ return result;
1306
+ }
1475
1307
 
1476
- var serverDisconnectionReasons = /*#__PURE__*/Object.freeze({
1477
- __proto__: null,
1478
- ACCESS_TOKEN_EXPIRED: ACCESS_TOKEN_EXPIRED,
1479
- CONNECTION_TIMEOUT: CONNECTION_TIMEOUT,
1480
- CUSTOMER_BANNED: CUSTOMER_BANNED,
1481
- CUSTOMER_TEMPORARILY_BLOCKED: CUSTOMER_TEMPORARILY_BLOCKED,
1482
- INACTIVITY_TIMEOUT: INACTIVITY_TIMEOUT,
1483
- INTERNAL_ERROR: INTERNAL_ERROR,
1484
- LICENSE_EXPIRED: LICENSE_EXPIRED,
1485
- LICENSE_NOT_FOUND: LICENSE_NOT_FOUND,
1486
- MISDIRECTED_CONNECTION: MISDIRECTED_CONNECTION$1,
1487
- PRODUCT_VERSION_CHANGED: PRODUCT_VERSION_CHANGED,
1488
- SERVICE_TEMPORARILY_UNAVAILABLE: SERVICE_TEMPORARILY_UNAVAILABLE$1,
1489
- TOO_MANY_CONNECTIONS: TOO_MANY_CONNECTIONS,
1490
- TOO_MANY_UNAUTHORIZED_CONNECTIONS: TOO_MANY_UNAUTHORIZED_CONNECTIONS,
1491
- UNSUPPORTED_VERSION: UNSUPPORTED_VERSION,
1492
- LOGGED_OUT_REMOTELY: LOGGED_OUT_REMOTELY
1493
- });
1308
+ /* global window */
1309
+ var root;
1310
+ if (typeof self !== 'undefined') {
1311
+ root = self;
1312
+ } else if (typeof window !== 'undefined') {
1313
+ root = window;
1314
+ } else if (typeof global !== 'undefined') {
1315
+ root = global;
1316
+ } else if (typeof module !== 'undefined') {
1317
+ root = module;
1318
+ } else {
1319
+ root = Function('return this')();
1320
+ }
1321
+ var result = symbolObservablePonyfill(root);
1494
1322
 
1495
- var CHAT_DEACTIVATED = 'chat_deactivated';
1496
- var CHAT_PROPERTIES_DELETED = 'chat_properties_deleted';
1497
- var CHAT_PROPERTIES_UPDATED = 'chat_properties_updated';
1498
- var CHAT_TRANSFERRED = 'chat_transferred';
1499
- var CUSTOMER_DISCONNECTED = 'customer_disconnected';
1500
- var CUSTOMER_PAGE_UPDATED = 'customer_page_updated';
1501
- var CUSTOMER_SIDE_STORAGE_UPDATED = 'customer_side_storage_updated';
1502
- var CUSTOMER_UPDATED = 'customer_updated';
1503
- var EVENT_PROPERTIES_DELETED = 'event_properties_deleted';
1504
- var EVENT_PROPERTIES_UPDATED = 'event_properties_updated';
1505
- var EVENT_UPDATED = 'event_updated';
1506
- var EVENTS_MARKED_AS_SEEN = 'events_marked_as_seen';
1507
- var GREETING_ACCEPTED = 'greeting_accepted';
1508
- var GREETING_CANCELED = 'greeting_canceled';
1509
- var GROUPS_STATUS_UPDATED = 'groups_status_updated';
1510
- var INCOMING_CHAT = 'incoming_chat';
1511
- var INCOMING_EVENT = 'incoming_event';
1512
- var INCOMING_GREETING = 'incoming_greeting';
1513
- var INCOMING_MULTICAST = 'incoming_multicast';
1514
- var INCOMING_RICH_MESSAGE_POSTBACK = 'incoming_rich_message_postback';
1515
- var INCOMING_TYPING_INDICATOR = 'incoming_typing_indicator';
1516
- var QUEUE_POSITION_UPDATED = 'queue_position_updated';
1517
- var THREAD_PROPERTIES_DELETED = 'thread_properties_deleted';
1518
- var THREAD_PROPERTIES_UPDATED = 'thread_properties_updated';
1519
- var USER_ADDED_TO_CHAT = 'user_added_to_chat';
1520
- var USER_REMOVED_FROM_CHAT = 'user_removed_from_chat';
1323
+ /**
1324
+ * These are private action types reserved by Redux.
1325
+ * For any unknown actions, you must return the current state.
1326
+ * If the current state is undefined, you must return the initial state.
1327
+ * Do not reference these action types directly in your code.
1328
+ */
1329
+ var randomString = function randomString() {
1330
+ return Math.random().toString(36).substring(7).split('').join('.');
1331
+ };
1332
+ var ActionTypes = {
1333
+ INIT: "@@redux/INIT" + randomString(),
1334
+ REPLACE: "@@redux/REPLACE" + randomString(),
1335
+ PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
1336
+ return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
1337
+ }
1338
+ };
1521
1339
 
1522
- var serverPushActions = /*#__PURE__*/Object.freeze({
1523
- __proto__: null,
1524
- CHAT_DEACTIVATED: CHAT_DEACTIVATED,
1525
- CHAT_PROPERTIES_DELETED: CHAT_PROPERTIES_DELETED,
1526
- CHAT_PROPERTIES_UPDATED: CHAT_PROPERTIES_UPDATED,
1527
- CHAT_TRANSFERRED: CHAT_TRANSFERRED,
1528
- CUSTOMER_DISCONNECTED: CUSTOMER_DISCONNECTED,
1529
- CUSTOMER_PAGE_UPDATED: CUSTOMER_PAGE_UPDATED,
1530
- CUSTOMER_SIDE_STORAGE_UPDATED: CUSTOMER_SIDE_STORAGE_UPDATED,
1531
- CUSTOMER_UPDATED: CUSTOMER_UPDATED,
1532
- EVENT_PROPERTIES_DELETED: EVENT_PROPERTIES_DELETED,
1533
- EVENT_PROPERTIES_UPDATED: EVENT_PROPERTIES_UPDATED,
1534
- EVENT_UPDATED: EVENT_UPDATED,
1535
- EVENTS_MARKED_AS_SEEN: EVENTS_MARKED_AS_SEEN,
1536
- GREETING_ACCEPTED: GREETING_ACCEPTED,
1537
- GREETING_CANCELED: GREETING_CANCELED,
1538
- GROUPS_STATUS_UPDATED: GROUPS_STATUS_UPDATED,
1539
- INCOMING_CHAT: INCOMING_CHAT,
1540
- INCOMING_EVENT: INCOMING_EVENT,
1541
- INCOMING_GREETING: INCOMING_GREETING,
1542
- INCOMING_MULTICAST: INCOMING_MULTICAST,
1543
- INCOMING_RICH_MESSAGE_POSTBACK: INCOMING_RICH_MESSAGE_POSTBACK,
1544
- INCOMING_TYPING_INDICATOR: INCOMING_TYPING_INDICATOR,
1545
- QUEUE_POSITION_UPDATED: QUEUE_POSITION_UPDATED,
1546
- THREAD_PROPERTIES_DELETED: THREAD_PROPERTIES_DELETED,
1547
- THREAD_PROPERTIES_UPDATED: THREAD_PROPERTIES_UPDATED,
1548
- USER_ADDED_TO_CHAT: USER_ADDED_TO_CHAT,
1549
- USER_REMOVED_FROM_CHAT: USER_REMOVED_FROM_CHAT
1550
- });
1340
+ /**
1341
+ * @param {any} obj The object to inspect.
1342
+ * @returns {boolean} True if the argument appears to be a plain object.
1343
+ */
1344
+ function isPlainObject(obj) {
1345
+ if (typeof obj !== 'object' || obj === null) return false;
1346
+ var proto = obj;
1347
+ while (Object.getPrototypeOf(proto) !== null) {
1348
+ proto = Object.getPrototypeOf(proto);
1349
+ }
1350
+ return Object.getPrototypeOf(obj) === proto;
1351
+ }
1551
1352
 
1552
- var FILE = 'file';
1553
- var FORM = 'form';
1554
- var FILLED_FORM = 'filled_form';
1555
- var MESSAGE = 'message';
1556
- var RICH_MESSAGE = 'rich_message';
1557
- var SYSTEM_MESSAGE = 'system_message';
1558
- var CUSTOM = 'custom';
1353
+ /**
1354
+ * Creates a Redux store that holds the state tree.
1355
+ * The only way to change the data in the store is to call `dispatch()` on it.
1356
+ *
1357
+ * There should only be a single store in your app. To specify how different
1358
+ * parts of the state tree respond to actions, you may combine several reducers
1359
+ * into a single reducer function by using `combineReducers`.
1360
+ *
1361
+ * @param {Function} reducer A function that returns the next state tree, given
1362
+ * the current state tree and the action to handle.
1363
+ *
1364
+ * @param {any} [preloadedState] The initial state. You may optionally specify it
1365
+ * to hydrate the state from the server in universal apps, or to restore a
1366
+ * previously serialized user session.
1367
+ * If you use `combineReducers` to produce the root reducer function, this must be
1368
+ * an object with the same shape as `combineReducers` keys.
1369
+ *
1370
+ * @param {Function} [enhancer] The store enhancer. You may optionally specify it
1371
+ * to enhance the store with third-party capabilities such as middleware,
1372
+ * time travel, persistence, etc. The only store enhancer that ships with Redux
1373
+ * is `applyMiddleware()`.
1374
+ *
1375
+ * @returns {Store} A Redux store that lets you read the state, dispatch actions
1376
+ * and subscribe to changes.
1377
+ */
1559
1378
 
1560
- var eventTypes = /*#__PURE__*/Object.freeze({
1561
- __proto__: null,
1562
- FILE: FILE,
1563
- FORM: FORM,
1564
- FILLED_FORM: FILLED_FORM,
1565
- MESSAGE: MESSAGE,
1566
- RICH_MESSAGE: RICH_MESSAGE,
1567
- SYSTEM_MESSAGE: SYSTEM_MESSAGE,
1568
- CUSTOM: CUSTOM
1569
- });
1379
+ function createStore(reducer, preloadedState, enhancer) {
1380
+ var _ref2;
1381
+ if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
1382
+ throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function.');
1383
+ }
1384
+ if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
1385
+ enhancer = preloadedState;
1386
+ preloadedState = undefined;
1387
+ }
1388
+ if (typeof enhancer !== 'undefined') {
1389
+ if (typeof enhancer !== 'function') {
1390
+ throw new Error('Expected the enhancer to be a function.');
1391
+ }
1392
+ return enhancer(createStore)(reducer, preloadedState);
1393
+ }
1394
+ if (typeof reducer !== 'function') {
1395
+ throw new Error('Expected the reducer to be a function.');
1396
+ }
1397
+ var currentReducer = reducer;
1398
+ var currentState = preloadedState;
1399
+ var currentListeners = [];
1400
+ var nextListeners = currentListeners;
1401
+ var isDispatching = false;
1402
+ /**
1403
+ * This makes a shallow copy of currentListeners so we can use
1404
+ * nextListeners as a temporary list while dispatching.
1405
+ *
1406
+ * This prevents any bugs around consumers calling
1407
+ * subscribe/unsubscribe in the middle of a dispatch.
1408
+ */
1409
+
1410
+ function ensureCanMutateNextListeners() {
1411
+ if (nextListeners === currentListeners) {
1412
+ nextListeners = currentListeners.slice();
1413
+ }
1414
+ }
1415
+ /**
1416
+ * Reads the state tree managed by the store.
1417
+ *
1418
+ * @returns {any} The current state tree of your application.
1419
+ */
1420
+
1421
+ function getState() {
1422
+ if (isDispatching) {
1423
+ throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
1424
+ }
1425
+ return currentState;
1426
+ }
1427
+ /**
1428
+ * Adds a change listener. It will be called any time an action is dispatched,
1429
+ * and some part of the state tree may potentially have changed. You may then
1430
+ * call `getState()` to read the current state tree inside the callback.
1431
+ *
1432
+ * You may call `dispatch()` from a change listener, with the following
1433
+ * caveats:
1434
+ *
1435
+ * 1. The subscriptions are snapshotted just before every `dispatch()` call.
1436
+ * If you subscribe or unsubscribe while the listeners are being invoked, this
1437
+ * will not have any effect on the `dispatch()` that is currently in progress.
1438
+ * However, the next `dispatch()` call, whether nested or not, will use a more
1439
+ * recent snapshot of the subscription list.
1440
+ *
1441
+ * 2. The listener should not expect to see all state changes, as the state
1442
+ * might have been updated multiple times during a nested `dispatch()` before
1443
+ * the listener is called. It is, however, guaranteed that all subscribers
1444
+ * registered before the `dispatch()` started will be called with the latest
1445
+ * state by the time it exits.
1446
+ *
1447
+ * @param {Function} listener A callback to be invoked on every dispatch.
1448
+ * @returns {Function} A function to remove this change listener.
1449
+ */
1450
+
1451
+ function subscribe(listener) {
1452
+ if (typeof listener !== 'function') {
1453
+ throw new Error('Expected the listener to be a function.');
1454
+ }
1455
+ if (isDispatching) {
1456
+ throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
1457
+ }
1458
+ var isSubscribed = true;
1459
+ ensureCanMutateNextListeners();
1460
+ nextListeners.push(listener);
1461
+ return function unsubscribe() {
1462
+ if (!isSubscribed) {
1463
+ return;
1464
+ }
1465
+ if (isDispatching) {
1466
+ throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
1467
+ }
1468
+ isSubscribed = false;
1469
+ ensureCanMutateNextListeners();
1470
+ var index = nextListeners.indexOf(listener);
1471
+ nextListeners.splice(index, 1);
1472
+ };
1473
+ }
1474
+ /**
1475
+ * Dispatches an action. It is the only way to trigger a state change.
1476
+ *
1477
+ * The `reducer` function, used to create the store, will be called with the
1478
+ * current state tree and the given `action`. Its return value will
1479
+ * be considered the **next** state of the tree, and the change listeners
1480
+ * will be notified.
1481
+ *
1482
+ * The base implementation only supports plain object actions. If you want to
1483
+ * dispatch a Promise, an Observable, a thunk, or something else, you need to
1484
+ * wrap your store creating function into the corresponding middleware. For
1485
+ * example, see the documentation for the `redux-thunk` package. Even the
1486
+ * middleware will eventually dispatch plain object actions using this method.
1487
+ *
1488
+ * @param {Object} action A plain object representing “what changed”. It is
1489
+ * a good idea to keep actions serializable so you can record and replay user
1490
+ * sessions, or use the time travelling `redux-devtools`. An action must have
1491
+ * a `type` property which may not be `undefined`. It is a good idea to use
1492
+ * string constants for action types.
1493
+ *
1494
+ * @returns {Object} For convenience, the same action object you dispatched.
1495
+ *
1496
+ * Note that, if you use a custom middleware, it may wrap `dispatch()` to
1497
+ * return something else (for example, a Promise you can await).
1498
+ */
1570
1499
 
1571
- var createEventBase = function createEventBase(event) {
1572
- var base = {};
1573
- if (typeof event.customId === 'string') {
1574
- base.custom_id = event.customId;
1500
+ function dispatch(action) {
1501
+ if (!isPlainObject(action)) {
1502
+ throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
1503
+ }
1504
+ if (typeof action.type === 'undefined') {
1505
+ throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
1506
+ }
1507
+ if (isDispatching) {
1508
+ throw new Error('Reducers may not dispatch actions.');
1509
+ }
1510
+ try {
1511
+ isDispatching = true;
1512
+ currentState = currentReducer(currentState, action);
1513
+ } finally {
1514
+ isDispatching = false;
1515
+ }
1516
+ var listeners = currentListeners = nextListeners;
1517
+ for (var i = 0; i < listeners.length; i++) {
1518
+ var listener = listeners[i];
1519
+ listener();
1520
+ }
1521
+ return action;
1575
1522
  }
1576
- if (isObject(event.properties)) {
1577
- base.properties = event.properties;
1523
+ /**
1524
+ * Replaces the reducer currently used by the store to calculate the state.
1525
+ *
1526
+ * You might need this if your app implements code splitting and you want to
1527
+ * load some of the reducers dynamically. You might also need this if you
1528
+ * implement a hot reloading mechanism for Redux.
1529
+ *
1530
+ * @param {Function} nextReducer The reducer for the store to use instead.
1531
+ * @returns {void}
1532
+ */
1533
+
1534
+ function replaceReducer(nextReducer) {
1535
+ if (typeof nextReducer !== 'function') {
1536
+ throw new Error('Expected the nextReducer to be a function.');
1537
+ }
1538
+ currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
1539
+ // Any reducers that existed in both the new and old rootReducer
1540
+ // will receive the previous state. This effectively populates
1541
+ // the new state tree with any relevant data from the old one.
1542
+
1543
+ dispatch({
1544
+ type: ActionTypes.REPLACE
1545
+ });
1578
1546
  }
1579
- return base;
1580
- };
1547
+ /**
1548
+ * Interoperability point for observable/reactive libraries.
1549
+ * @returns {observable} A minimal observable of state changes.
1550
+ * For more information, see the observable proposal:
1551
+ * https://github.com/tc39/proposal-observable
1552
+ */
1581
1553
 
1582
- // TODO: we could validate and throw here
1583
- // but should we? maybe only in DEV mode?
1584
- var parseEvent = function parseEvent(event) {
1585
- switch (event.type) {
1586
- case MESSAGE:
1587
- {
1588
- var message = _extends({}, createEventBase(event), {
1589
- type: event.type,
1590
- text: event.text
1591
- });
1592
- if (event.postback) {
1593
- message.postback = {
1594
- id: event.postback.id,
1595
- thread_id: event.postback.threadId,
1596
- event_id: event.postback.eventId,
1597
- type: event.postback.type,
1598
- value: event.postback.value
1599
- };
1600
- }
1601
- return message;
1602
- }
1603
- case FILE:
1604
- {
1605
- var file = _extends({}, createEventBase(event), {
1606
- type: event.type,
1607
- url: event.url,
1608
- alternative_text: event.alternativeText
1609
- });
1610
- return file;
1611
- }
1612
- case FILLED_FORM:
1613
- {
1614
- var filledForm = _extends({}, createEventBase(event), {
1615
- type: event.type,
1616
- form_id: event.formId,
1617
- fields: event.fields.map(function (field) {
1618
- switch (field.type) {
1619
- case 'group_chooser':
1620
- {
1621
- if (!field.answer) {
1622
- return field;
1623
- }
1624
- var _field$answer = field.answer,
1625
- groupId = _field$answer.groupId,
1626
- answer = _objectWithoutPropertiesLoose(_field$answer, ["groupId"]);
1627
- return _extends({}, field, {
1628
- answer: _extends({}, answer, {
1629
- group_id: groupId
1630
- })
1631
- });
1632
- }
1633
- default:
1634
- return field;
1635
- }
1636
- })
1637
- });
1638
- return filledForm;
1639
- }
1640
- case SYSTEM_MESSAGE:
1641
- {
1642
- var systemMessage = _extends({}, createEventBase(event), {
1643
- type: event.type,
1644
- text: event.text,
1645
- system_message_type: event.systemMessageType
1646
- });
1647
- if (event.recipients) {
1648
- systemMessage.recipients = event.recipients;
1554
+ function observable() {
1555
+ var _ref;
1556
+ var outerSubscribe = subscribe;
1557
+ return _ref = {
1558
+ /**
1559
+ * The minimal observable subscription method.
1560
+ * @param {Object} observer Any object that can be used as an observer.
1561
+ * The observer object should have a `next` method.
1562
+ * @returns {subscription} An object with an `unsubscribe` method that can
1563
+ * be used to unsubscribe the observable from the store, and prevent further
1564
+ * emission of values from the observable.
1565
+ */
1566
+ subscribe: function subscribe(observer) {
1567
+ if (typeof observer !== 'object' || observer === null) {
1568
+ throw new TypeError('Expected the observer to be an object.');
1649
1569
  }
1650
- return systemMessage;
1651
- }
1652
- case CUSTOM:
1653
- {
1654
- var customEvent = _extends({}, createEventBase(event), {
1655
- type: event.type
1656
- });
1657
- if (event.content) {
1658
- customEvent.content = event.content;
1570
+ function observeState() {
1571
+ if (observer.next) {
1572
+ observer.next(getState());
1573
+ }
1659
1574
  }
1660
- return customEvent;
1575
+ observeState();
1576
+ var unsubscribe = outerSubscribe(observeState);
1577
+ return {
1578
+ unsubscribe: unsubscribe
1579
+ };
1661
1580
  }
1581
+ }, _ref[result] = function () {
1582
+ return this;
1583
+ }, _ref;
1584
+ } // When a store is created, an "INIT" action is dispatched so that every
1585
+ // reducer returns their initial state. This effectively populates
1586
+ // the initial state tree.
1587
+
1588
+ dispatch({
1589
+ type: ActionTypes.INIT
1590
+ });
1591
+ return _ref2 = {
1592
+ dispatch: dispatch,
1593
+ subscribe: subscribe,
1594
+ getState: getState,
1595
+ replaceReducer: replaceReducer
1596
+ }, _ref2[result] = observable, _ref2;
1597
+ }
1598
+
1599
+ /**
1600
+ * Prints a warning in the console if it exists.
1601
+ *
1602
+ * @param {String} message The warning message.
1603
+ * @returns {void}
1604
+ */
1605
+ function warning(message) {
1606
+ /* eslint-disable no-console */
1607
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
1608
+ console.error(message);
1662
1609
  }
1663
- };
1664
- var parseThreadData = function parseThreadData(thread) {
1665
- var data = {};
1666
- var events = thread.events,
1667
- properties = thread.properties;
1668
- if (events) {
1669
- data.events = events.map(parseEvent);
1670
- }
1671
- if (properties) {
1672
- data.properties = properties;
1610
+ /* eslint-enable no-console */
1611
+
1612
+ try {
1613
+ // This error was thrown as a convenience so that if you enable
1614
+ // "break on all exceptions" in your console,
1615
+ // it would pause the execution at this line.
1616
+ throw new Error(message);
1617
+ } catch (e) {} // eslint-disable-line no-empty
1618
+ }
1619
+ function _defineProperty(obj, key, value) {
1620
+ if (key in obj) {
1621
+ Object.defineProperty(obj, key, {
1622
+ value: value,
1623
+ enumerable: true,
1624
+ configurable: true,
1625
+ writable: true
1626
+ });
1627
+ } else {
1628
+ obj[key] = value;
1673
1629
  }
1674
- return data;
1675
- };
1676
- var parseStartChatData = function parseStartChatData(_ref) {
1677
- var _ref$active = _ref.active,
1678
- active = _ref$active === void 0 ? true : _ref$active,
1679
- chat = _ref.chat,
1680
- continuous = _ref.continuous;
1681
- var data = {
1682
- active: active,
1683
- chat: {}
1684
- };
1685
- if (typeof continuous === 'boolean') {
1686
- data.continuous = continuous;
1630
+ return obj;
1631
+ }
1632
+ function ownKeys(object, enumerableOnly) {
1633
+ var keys = Object.keys(object);
1634
+ if (Object.getOwnPropertySymbols) {
1635
+ keys.push.apply(keys, Object.getOwnPropertySymbols(object));
1687
1636
  }
1688
- if (!chat) {
1689
- return data;
1637
+ if (enumerableOnly) keys = keys.filter(function (sym) {
1638
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
1639
+ });
1640
+ return keys;
1641
+ }
1642
+ function _objectSpread2(target) {
1643
+ for (var i = 1; i < arguments.length; i++) {
1644
+ var source = arguments[i] != null ? arguments[i] : {};
1645
+ if (i % 2) {
1646
+ ownKeys(source, true).forEach(function (key) {
1647
+ _defineProperty(target, key, source[key]);
1648
+ });
1649
+ } else if (Object.getOwnPropertyDescriptors) {
1650
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1651
+ } else {
1652
+ ownKeys(source).forEach(function (key) {
1653
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1654
+ });
1655
+ }
1690
1656
  }
1691
- var access = chat.access,
1692
- thread = chat.thread,
1693
- properties = chat.properties;
1694
- if (access && access.groupIds) {
1695
- data.chat.access = {
1696
- group_ids: access.groupIds
1697
- };
1657
+ return target;
1658
+ }
1659
+
1660
+ /**
1661
+ * Composes single-argument functions from right to left. The rightmost
1662
+ * function can take multiple arguments as it provides the signature for
1663
+ * the resulting composite function.
1664
+ *
1665
+ * @param {...Function} funcs The functions to compose.
1666
+ * @returns {Function} A function obtained by composing the argument functions
1667
+ * from right to left. For example, compose(f, g, h) is identical to doing
1668
+ * (...args) => f(g(h(...args))).
1669
+ */
1670
+ function compose() {
1671
+ for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
1672
+ funcs[_key] = arguments[_key];
1698
1673
  }
1699
- if (properties) {
1700
- data.chat.properties = properties;
1674
+ if (funcs.length === 0) {
1675
+ return function (arg) {
1676
+ return arg;
1677
+ };
1701
1678
  }
1702
- if (thread) {
1703
- data.chat.thread = parseThreadData(thread);
1679
+ if (funcs.length === 1) {
1680
+ return funcs[0];
1704
1681
  }
1705
- return data;
1706
- };
1707
- var parseResumeChatData = function parseResumeChatData(requestData) {
1708
- var data = parseStartChatData(requestData);
1709
- return _extends({}, data, {
1710
- chat: _extends({}, data.chat, {
1711
- id: requestData.chat.id
1712
- })
1713
- });
1714
- };
1715
- var parseCustomerSessionFields = function parseCustomerSessionFields(sessionFields) {
1716
- return toPairs(sessionFields).map(function (_ref2) {
1717
- var _ref3;
1718
- var key = _ref2[0],
1719
- value = _ref2[1];
1720
- return _ref3 = {}, _ref3[key] = value, _ref3;
1682
+ return funcs.reduce(function (a, b) {
1683
+ return function () {
1684
+ return a(b.apply(void 0, arguments));
1685
+ };
1721
1686
  });
1722
- };
1723
- var parseCustomerUpdate = function parseCustomerUpdate(update) {
1724
- var result = pickOwn(['avatar', 'name', 'email'], update);
1725
- if (update.sessionFields) {
1726
- result.session_fields = parseCustomerSessionFields(update.sessionFields);
1727
- }
1728
- return result;
1729
- };
1687
+ }
1730
1688
 
1731
- var destroy = function destroy(reason) {
1732
- return {
1733
- type: DESTROY,
1734
- payload: {
1735
- reason: reason
1736
- }
1737
- };
1738
- };
1739
- var loginSuccess = function loginSuccess(payload) {
1740
- return {
1741
- type: LOGIN_SUCCESS,
1742
- payload: payload
1743
- };
1744
- };
1745
- var pauseConnection = function pauseConnection(reason) {
1746
- return {
1747
- type: PAUSE_CONNECTION,
1748
- payload: {
1749
- reason: reason
1750
- }
1751
- };
1752
- };
1753
- var prefetchToken = function prefetchToken(fresh) {
1754
- if (fresh === void 0) {
1755
- fresh = false;
1689
+ /**
1690
+ * Creates a store enhancer that applies middleware to the dispatch method
1691
+ * of the Redux store. This is handy for a variety of tasks, such as expressing
1692
+ * asynchronous actions in a concise manner, or logging every action payload.
1693
+ *
1694
+ * See `redux-thunk` package as an example of the Redux middleware.
1695
+ *
1696
+ * Because middleware is potentially asynchronous, this should be the first
1697
+ * store enhancer in the composition chain.
1698
+ *
1699
+ * Note that each middleware will be given the `dispatch` and `getState` functions
1700
+ * as named arguments.
1701
+ *
1702
+ * @param {...Function} middlewares The middleware chain to be applied.
1703
+ * @returns {Function} A store enhancer applying the middleware.
1704
+ */
1705
+
1706
+ function applyMiddleware() {
1707
+ for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
1708
+ middlewares[_key] = arguments[_key];
1756
1709
  }
1757
- return {
1758
- type: PREFETCH_TOKEN,
1759
- payload: {
1760
- fresh: fresh
1761
- }
1762
- };
1763
- };
1764
- var reconnect = function reconnect(delay) {
1765
- return {
1766
- type: RECONNECT,
1767
- payload: {
1768
- delay: delay
1769
- }
1710
+ return function (createStore) {
1711
+ return function () {
1712
+ var store = createStore.apply(void 0, arguments);
1713
+ var _dispatch = function dispatch() {
1714
+ throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
1715
+ };
1716
+ var middlewareAPI = {
1717
+ getState: store.getState,
1718
+ dispatch: function dispatch() {
1719
+ return _dispatch.apply(void 0, arguments);
1720
+ }
1721
+ };
1722
+ var chain = middlewares.map(function (middleware) {
1723
+ return middleware(middlewareAPI);
1724
+ });
1725
+ _dispatch = compose.apply(void 0, chain)(store.dispatch);
1726
+ return _objectSpread2({}, store, {
1727
+ dispatch: _dispatch
1728
+ });
1729
+ };
1770
1730
  };
1771
- };
1731
+ }
1772
1732
 
1773
- // TODO: this one was currently pretty hard to type in full
1774
- // we should explore providing stricter types for this in the future
1775
- var sendRequest = function sendRequest(action, payload, source) {
1776
- return {
1777
- type: SEND_REQUEST,
1778
- payload: _extends({
1779
- request: {
1780
- action: action,
1781
- payload: payload
1782
- }
1783
- }, source && {
1784
- source: source
1785
- })
1733
+ /*
1734
+ * This is a dummy function to check if the function name has been altered by minification.
1735
+ * If the function has been minified and NODE_ENV !== 'production', warn the user.
1736
+ */
1737
+
1738
+ function isCrushed() {}
1739
+ if (typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
1740
+ warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
1741
+ }
1742
+
1743
+ var createSideEffectsMiddleware = function createSideEffectsMiddleware() {
1744
+ var handlers = [];
1745
+ var sideEffectsMiddleware = function sideEffectsMiddleware(store) {
1746
+ return function (next) {
1747
+ return function (action) {
1748
+ var result = next(action);
1749
+ handlers.forEach(function (handler) {
1750
+ handler(action, store);
1751
+ });
1752
+ return result;
1753
+ };
1754
+ };
1786
1755
  };
1787
- };
1788
- var sendEvent = function sendEvent(_ref) {
1789
- var chatId = _ref.chatId,
1790
- event = _ref.event,
1791
- attachToLastThread = _ref.attachToLastThread;
1792
- var payload = {
1793
- chat_id: chatId,
1794
- event: parseEvent(event)
1756
+ sideEffectsMiddleware.add = function (handler) {
1757
+ handlers.push(handler);
1795
1758
  };
1796
- if (attachToLastThread) {
1797
- payload.attach_to_last_thread = true;
1798
- }
1799
- return sendRequest(SEND_EVENT, payload);
1759
+ return sideEffectsMiddleware;
1800
1760
  };
1801
- var setChatActive = function setChatActive(id, active) {
1761
+
1762
+ var createBackoff = function createBackoff(_ref) {
1763
+ var _ref$min = _ref.min,
1764
+ min = _ref$min === void 0 ? 1000 : _ref$min,
1765
+ _ref$max = _ref.max,
1766
+ max = _ref$max === void 0 ? 5000 : _ref$max,
1767
+ _ref$jitter = _ref.jitter,
1768
+ jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1769
+ var attempts = 0;
1802
1770
  return {
1803
- type: SET_CHAT_ACTIVE,
1804
- payload: {
1805
- id: id,
1806
- active: active
1771
+ duration: function duration() {
1772
+ var ms = min * Math.pow(2, attempts++);
1773
+ if (jitter) {
1774
+ var rand = Math.random();
1775
+ var deviation = Math.floor(rand * jitter * ms);
1776
+ ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1777
+ }
1778
+ return Math.min(ms, max) | 0;
1779
+ },
1780
+ reset: function reset() {
1781
+ attempts = 0;
1807
1782
  }
1808
1783
  };
1809
1784
  };
1810
- var setSelfId = function setSelfId(id) {
1811
- return {
1812
- type: SET_SELF_ID,
1813
- payload: {
1814
- id: id
1785
+
1786
+ /**
1787
+ * 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.
1788
+ * @param anyFunction - function to be called
1789
+ * @returns promise that resolves to the return value of the function
1790
+ * @example
1791
+ * const promise = promiseTry(() => 1)
1792
+ * promise.then(value => console.log(value)) // 1
1793
+ */
1794
+
1795
+ function promiseTry(anyFunction) {
1796
+ return new Promise(function (resolve) {
1797
+ resolve(anyFunction());
1798
+ });
1799
+ }
1800
+
1801
+ /**
1802
+ * Creates a deferred object that can be resolved or rejected later.
1803
+ * @returns A deferred object with a promise and resolve and reject functions.
1804
+ * @example
1805
+ * const def = promiseDeferred()
1806
+ * const promise = def.promise
1807
+ * def.resolve(1)
1808
+ * return promise.then(res => console.log(res)) // 1
1809
+ */
1810
+
1811
+ function promiseDeferred() {
1812
+ var deferred = {};
1813
+ deferred.promise = new Promise(function (resolve, reject) {
1814
+ deferred.resolve = resolve;
1815
+ deferred.reject = reject;
1816
+ });
1817
+ return deferred;
1818
+ }
1819
+
1820
+ var createReducer$1 = function createReducer(initialState, reducersMap) {
1821
+ return function reducer(state, action) {
1822
+ if (state === void 0) {
1823
+ state = initialState;
1824
+ }
1825
+ if (hasOwn(action.type, reducersMap)) {
1826
+ return reducersMap[action.type](state, action.payload);
1815
1827
  }
1816
- };
1817
- };
1818
- var socketDisconnected = function socketDisconnected() {
1819
- return {
1820
- type: SOCKET_DISCONNECTED
1828
+ return state;
1821
1829
  };
1822
1830
  };
1823
1831
 
1824
- // TODO: this thing is not really well typed and should be improved
1825
- var sendRequestAction = function sendRequestAction(store, action) {
1826
- action.payload.id = generateUniqueId(store.getState().requests);
1827
- var _promiseDeferred = promiseDeferred(),
1828
- resolve = _promiseDeferred.resolve,
1829
- reject = _promiseDeferred.reject,
1830
- promise = _promiseDeferred.promise;
1831
- action.payload.promise = promise;
1832
- action.payload.resolve = resolve;
1833
- action.payload.reject = reject;
1834
- store.dispatch(action);
1835
- return promise;
1832
+ var getAllRequests = function getAllRequests(state) {
1833
+ return state.requests;
1836
1834
  };
1837
-
1838
- var AUTHENTICATION = 'AUTHENTICATION';
1839
- var AUTHORIZATION = 'AUTHORIZATION';
1840
- var CHAT_ALREADY_ACTIVE = 'CHAT_ALREADY_ACTIVE';
1841
- var CHAT_LIMIT_REACHED = 'CHAT_LIMIT_REACHED';
1842
- var CUSTOMER_BANNED$1 = 'CUSTOMER_BANNED';
1843
- var CUSTOMER_SESSION_FIELDS_LIMIT_REACHED = 'CUSTOMER_SESSION_FIELDS_LIMIT_REACHED';
1844
- var ENTITY_TOO_LARGE = 'ENTITY_TOO_LARGE';
1845
- var GREETING_NOT_FOUND = 'GREETING_NOT_FOUND';
1846
- var GROUP_OFFLINE = 'GROUP_OFFLINE';
1847
- var GROUPS_OFFLINE = 'GROUPS_OFFLINE';
1848
- var GROUP_NOT_FOUND = 'GROUP_NOT_FOUND';
1849
- var GROUP_UNAVAILABLE = 'GROUP_UNAVAILABLE';
1850
- var INTERNAL = 'INTERNAL';
1851
- var LICENSE_EXPIRED$1 = 'LICENSE_EXPIRED';
1852
- // actually this can happen only when using REST
1853
- var MISDIRECTED_REQUEST = 'MISDIRECTED_REQUEST';
1854
- var PENDING_REQUESTS_LIMIT_REACHED = 'PENDING_REQUESTS_LIMIT_REACHED';
1855
- var REQUEST_TIMEOUT$1 = 'REQUEST_TIMEOUT';
1856
- var SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE';
1857
- var UNSUPPORTED_VERSION$1 = 'UNSUPPORTED_VERSION';
1858
- var USERS_LIMIT_REACHED = 'USERS_LIMIT_REACHED';
1859
- var VALIDATION = 'VALIDATION';
1860
- var WRONG_PRODUCT_VERSION = 'WRONG_PRODUCT_VERSION';
1861
-
1862
- var serverErrorCodes = /*#__PURE__*/Object.freeze({
1863
- __proto__: null,
1864
- AUTHENTICATION: AUTHENTICATION,
1865
- AUTHORIZATION: AUTHORIZATION,
1866
- CHAT_ALREADY_ACTIVE: CHAT_ALREADY_ACTIVE,
1867
- CHAT_LIMIT_REACHED: CHAT_LIMIT_REACHED,
1868
- CUSTOMER_BANNED: CUSTOMER_BANNED$1,
1869
- CUSTOMER_SESSION_FIELDS_LIMIT_REACHED: CUSTOMER_SESSION_FIELDS_LIMIT_REACHED,
1870
- ENTITY_TOO_LARGE: ENTITY_TOO_LARGE,
1871
- GREETING_NOT_FOUND: GREETING_NOT_FOUND,
1872
- GROUP_OFFLINE: GROUP_OFFLINE,
1873
- GROUPS_OFFLINE: GROUPS_OFFLINE,
1874
- GROUP_NOT_FOUND: GROUP_NOT_FOUND,
1875
- GROUP_UNAVAILABLE: GROUP_UNAVAILABLE,
1876
- INTERNAL: INTERNAL,
1877
- LICENSE_EXPIRED: LICENSE_EXPIRED$1,
1878
- MISDIRECTED_REQUEST: MISDIRECTED_REQUEST,
1879
- PENDING_REQUESTS_LIMIT_REACHED: PENDING_REQUESTS_LIMIT_REACHED,
1880
- REQUEST_TIMEOUT: REQUEST_TIMEOUT$1,
1881
- SERVICE_UNAVAILABLE: SERVICE_UNAVAILABLE,
1882
- UNSUPPORTED_VERSION: UNSUPPORTED_VERSION$1,
1883
- USERS_LIMIT_REACHED: USERS_LIMIT_REACHED,
1884
- VALIDATION: VALIDATION,
1885
- WRONG_PRODUCT_VERSION: WRONG_PRODUCT_VERSION
1886
- });
1887
-
1888
- var getSideStorageKeyByLicense = function getSideStorageKeyByLicense(store, licenseId) {
1889
- var _store$getState = store.getState(),
1890
- groupId = _store$getState.groupId,
1891
- uniqueGroups = _store$getState.uniqueGroups;
1892
- return "side_storage_" + licenseId + (uniqueGroups ? ":" + groupId : '');
1835
+ var getConnectionStatus = function getConnectionStatus(state) {
1836
+ return state.connection.status;
1893
1837
  };
1894
- var getSideStorageKeyByOrganization = function getSideStorageKeyByOrganization(store) {
1895
- var _store$getState2 = store.getState(),
1896
- organizationId = _store$getState2.organizationId,
1897
- groupId = _store$getState2.groupId,
1898
- uniqueGroups = _store$getState2.uniqueGroups;
1899
- return "side_storage_" + organizationId + (uniqueGroups ? ":" + groupId : '');
1838
+ var getRequest = function getRequest(state, id) {
1839
+ return state.requests[id];
1900
1840
  };
1901
- var getSideStorage = function getSideStorage(store, licenseId) {
1902
- var sideStorageLicenseKey = getSideStorageKeyByLicense(store, licenseId);
1903
- var sideStorageOrganizationKey = getSideStorageKeyByOrganization(store);
1904
- return storage.getItem(sideStorageLicenseKey)["catch"](noop).then(function (sideStorage) {
1905
- if (!sideStorage) {
1906
- return storage.getItem(sideStorageOrganizationKey)["catch"](noop).then(function (organizationSideStorage) {
1907
- return JSON.parse(organizationSideStorage || '{}');
1908
- })["catch"](noop);
1909
- }
1910
- return storage.setItem(sideStorageOrganizationKey, sideStorage)["catch"](noop).then(function () {
1911
- return storage.removeItem(sideStorageLicenseKey)["catch"](noop).then(function () {
1912
- return JSON.parse(sideStorage);
1913
- })["catch"](noop);
1914
- });
1915
- })
1916
- // shouldnt get triggered, just a defensive measure against malformed storage entries
1917
- ["catch"](noop);
1841
+ var getSelfId = function getSelfId(state) {
1842
+ return state.users.self.id;
1918
1843
  };
1919
- var saveSideStorage = function saveSideStorage(store, sideStorage) {
1920
- storage.setItem(getSideStorageKeyByOrganization(store), JSON.stringify(sideStorage))["catch"](noop);
1844
+ var isChatActive = function isChatActive(state, chatId) {
1845
+ var chat = state.chats[chatId];
1846
+ return !!chat && chat.active;
1921
1847
  };
1922
-
1923
- var taskChain = function taskChain(_ref, onSuccess, onError) {
1924
- var steps = _ref.slice(0);
1925
- var cancelled = false;
1926
- var next = function next(intermediateResult) {
1927
- var step = steps.shift();
1928
- promiseTry(function () {
1929
- return step(intermediateResult);
1930
- }).then(function (result) {
1931
- if (cancelled) {
1932
- return;
1933
- }
1934
- if (steps.length) {
1935
- next(result);
1936
- return;
1937
- }
1938
- onSuccess(result);
1939
- }, function (error) {
1940
- if (cancelled) {
1941
- return;
1942
- }
1943
- onError(error);
1944
- });
1848
+ var isConnected = function isConnected(state) {
1849
+ return getConnectionStatus(state) === CONNECTED;
1850
+ };
1851
+ var isDestroyed = function isDestroyed(state) {
1852
+ return getConnectionStatus(state) === DESTROYED;
1853
+ };
1854
+ var getRegionParam = function getRegionParam(options) {
1855
+ var _options$region;
1856
+ return {
1857
+ 'x-region': (_options$region = options.region) != null ? _options$region : ''
1945
1858
  };
1946
- next();
1859
+ };
1860
+ var getEnvPart = function getEnvPart(_ref) {
1861
+ var env = _ref.env;
1862
+ if (env === 'production') {
1863
+ return '';
1864
+ }
1865
+ return "." + env;
1866
+ };
1867
+ var getApiOrigin = function getApiOrigin(state) {
1868
+ {
1869
+ return "https://api" + getEnvPart(state) + ".livechatinc.com";
1870
+ }
1871
+ };
1872
+ var getServerUrl = function getServerUrl(state) {
1873
+ return getApiOrigin(state) + "/v3.6/customer";
1874
+ };
1875
+ var createInitialState = function createInitialState(initialStateData) {
1876
+ var _initialStateData$app = initialStateData.application,
1877
+ application = _initialStateData$app === void 0 ? {} : _initialStateData$app,
1878
+ organizationId = initialStateData.organizationId,
1879
+ _initialStateData$gro = initialStateData.groupId,
1880
+ groupId = _initialStateData$gro === void 0 ? null : _initialStateData$gro,
1881
+ env = initialStateData.env,
1882
+ _initialStateData$pag = initialStateData.page,
1883
+ page = _initialStateData$pag === void 0 ? null : _initialStateData$pag,
1884
+ _initialStateData$reg = initialStateData.region,
1885
+ region = _initialStateData$reg === void 0 ? null : _initialStateData$reg,
1886
+ _initialStateData$ref = initialStateData.referrer,
1887
+ referrer = _initialStateData$ref === void 0 ? null : _initialStateData$ref,
1888
+ _initialStateData$tab = initialStateData.tabId,
1889
+ tabId = _initialStateData$tab === void 0 ? null : _initialStateData$tab,
1890
+ _initialStateData$uni = initialStateData.uniqueGroups,
1891
+ uniqueGroups = _initialStateData$uni === void 0 ? false : _initialStateData$uni,
1892
+ _initialStateData$mob = initialStateData.mobile,
1893
+ mobile = _initialStateData$mob === void 0 ? false : _initialStateData$mob;
1947
1894
  return {
1948
- cancel: function cancel() {
1949
- cancelled = true;
1950
- }
1895
+ application: _extends({}, application, {
1896
+ name: "customer_sdk",
1897
+ version: "5.0.0"
1898
+ }),
1899
+ organizationId: organizationId,
1900
+ env: env,
1901
+ groupId: groupId,
1902
+ chats: {},
1903
+ connection: {
1904
+ status: DISCONNECTED
1905
+ },
1906
+ page: page,
1907
+ region: region,
1908
+ referrer: referrer,
1909
+ tabId: tabId,
1910
+ requests: {},
1911
+ users: {
1912
+ self: {
1913
+ id: null,
1914
+ type: CUSTOMER
1915
+ },
1916
+ others: {}
1917
+ },
1918
+ uniqueGroups: uniqueGroups,
1919
+ mobile: mobile
1951
1920
  };
1952
1921
  };
1953
- var sendLoginFlowRequest = function sendLoginFlowRequest(store, type, payload) {
1954
- return sendRequestAction(store, sendRequest(type, payload, 'login'));
1922
+ var removeStoredRequest = function removeStoredRequest(state, _ref2) {
1923
+ var id = _ref2.id;
1924
+ var _state$requests = state.requests,
1925
+ requests = _objectWithoutPropertiesLoose(_state$requests, [id].map(_toPropertyKey));
1926
+ return _extends({}, state, {
1927
+ requests: requests
1928
+ });
1955
1929
  };
1956
- var delay = function delay(ms) {
1930
+ var setConnectionStatus = function setConnectionStatus(status, state) {
1931
+ return _extends({}, state, {
1932
+ connection: _extends({}, state.connection, {
1933
+ status: status
1934
+ })
1935
+ });
1936
+ };
1937
+ var createReducer = (function (state) {
1938
+ var _createReducer;
1939
+ return createReducer$1(state, (_createReducer = {}, _createReducer[CHANGE_REGION] = function (state, _ref3) {
1940
+ var region = _ref3.region;
1941
+ return _extends({}, state, {
1942
+ region: region
1943
+ });
1944
+ }, _createReducer[DESTROY] = function (state) {
1945
+ return setConnectionStatus(DESTROYED, state);
1946
+ }, _createReducer[LOGIN_SUCCESS] = function (state) {
1947
+ return setConnectionStatus(CONNECTED, state);
1948
+ }, _createReducer[PAUSE_CONNECTION] = function (state) {
1949
+ return setConnectionStatus(PAUSED, state);
1950
+ }, _createReducer[REQUEST_FAILED] = removeStoredRequest, _createReducer[RESPONSE_RECEIVED] = removeStoredRequest, _createReducer[PUSH_RESPONSE_RECEIVED] = removeStoredRequest, _createReducer[SEND_REQUEST] = function (state, _ref4) {
1951
+ var _extends2;
1952
+ var promise = _ref4.promise,
1953
+ resolve = _ref4.resolve,
1954
+ reject = _ref4.reject,
1955
+ id = _ref4.id,
1956
+ request = _ref4.request;
1957
+ return _extends({}, state, {
1958
+ requests: _extends({}, state.requests, (_extends2 = {}, _extends2[id] = {
1959
+ id: id,
1960
+ promise: promise,
1961
+ resolve: resolve,
1962
+ reject: reject,
1963
+ request: request
1964
+ }, _extends2))
1965
+ });
1966
+ }, _createReducer[SET_CHAT_ACTIVE] = function (state, _ref5) {
1967
+ var _extends3;
1968
+ var id = _ref5.id,
1969
+ active = _ref5.active;
1970
+ return _extends({}, state, {
1971
+ chats: _extends({}, state.chats, (_extends3 = {}, _extends3[id] = _extends({}, state.chats[id], {
1972
+ active: active
1973
+ }), _extends3))
1974
+ });
1975
+ }, _createReducer[SET_SELF_ID] = function (state, payload) {
1976
+ return _extends({}, state, {
1977
+ users: _extends({}, state.users, {
1978
+ self: _extends({}, state.users.self, {
1979
+ id: payload.id
1980
+ })
1981
+ })
1982
+ });
1983
+ }, _createReducer[SOCKET_DISCONNECTED] = function (state) {
1984
+ var previousStatus = getConnectionStatus(state);
1985
+ if ((previousStatus === PAUSED || previousStatus === DESTROYED)) {
1986
+ throw new Error("Got 'socket_disconnected' action when in " + previousStatus + " state. This should be an impossible state.");
1987
+ }
1988
+ var state1 = setConnectionStatus(previousStatus === DISCONNECTED ? DISCONNECTED : RECONNECTING, state);
1989
+ return _extends({}, state1, {
1990
+ requests: {}
1991
+ });
1992
+ }, _createReducer[UPDATE_CUSTOMER_PAGE$1] = function (state, page) {
1993
+ return _extends({}, state, {
1994
+ page: _extends({}, state.page, page)
1995
+ });
1996
+ }, _createReducer[CLEAR_SENSITIVE_SESSION_STATE] = function (state) {
1997
+ return _extends({}, state, {
1998
+ chats: {},
1999
+ users: {
2000
+ self: {
2001
+ id: null,
2002
+ type: CUSTOMER
2003
+ },
2004
+ others: {}
2005
+ },
2006
+ requests: {}
2007
+ });
2008
+ }, _createReducer[IDENTITY_CHANGED] = function (state) {
2009
+ return state;
2010
+ }, _createReducer));
2011
+ });
2012
+
2013
+ function finalCreateStore(initialStateData) {
2014
+ var compose = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
2015
+ name: '@livechat/customer-sdk'
2016
+ }) : identity;
2017
+ var sideEffectsMiddleware = createSideEffectsMiddleware();
2018
+ var store = createStore(createReducer(createInitialState(initialStateData)), compose(applyMiddleware(sideEffectsMiddleware)));
2019
+ store.addSideEffectsHandler = sideEffectsMiddleware.add;
2020
+ return store;
2021
+ }
2022
+
2023
+ var makeGraylogRequest = function makeGraylogRequest(url, body) {
1957
2024
  return new Promise(function (resolve) {
1958
- setTimeout(resolve, ms);
2025
+ var img = new Image();
2026
+ img.src = url + "?" + body;
2027
+ img.onerror = noop;
2028
+ img.onload = function () {
2029
+ return resolve();
2030
+ };
1959
2031
  });
1960
2032
  };
1961
- function createLoginTask(auth, customerDataProvider, licenseId) {
1962
- var store;
1963
- var sentPage = null;
1964
- var task;
1965
- var backoffConfig = {
1966
- min: 300,
1967
- max: 60000,
1968
- jitter: 0.3
1969
- };
1970
- var defaultBackoffStrategy = createBackoff(backoffConfig);
1971
- var slowerBackoffStrategy = createBackoff(_extends({}, backoffConfig, {
1972
- min: 1000
1973
- }));
1974
- var currentBackoffStrategy = defaultBackoffStrategy;
1975
- var destroy$1 = function destroy$1(reason) {
1976
- return store.dispatch(destroy(reason));
1977
- };
1978
- var reconnect$1 = function reconnect$1() {
1979
- return store.dispatch(reconnect(currentBackoffStrategy.duration()));
1980
- };
1981
- var getTokenAndSideStorage = function getTokenAndSideStorage() {
1982
- return Promise.all([auth.getToken(), getSideStorage(store, licenseId)]);
1983
- };
1984
- var dispatchSelfId = function dispatchSelfId(_ref2) {
1985
- var token = _ref2[0],
1986
- sideStorage = _ref2[1];
1987
- var selfId = getSelfId(store.getState());
1988
- if (selfId === null) {
1989
- store.dispatch(setSelfId(token.entityId));
1990
- } else if (selfId !== token.entityId) {
1991
- var err = new Error('Identity has changed.');
1992
- err.code = IDENTITY_MISMATCH;
1993
- throw err;
1994
- }
1995
- return [token, sideStorage];
1996
- };
1997
- var _sendLogin = function sendLogin(_ref3) {
1998
- var token = _ref3[0],
1999
- sideStorage = _ref3[1];
2000
- var state = store.getState();
2001
- var application = state.application,
2002
- groupId = state.groupId,
2003
- page = state.page,
2004
- referrer = state.referrer,
2005
- mobile = state.mobile;
2006
- var payload = {
2007
- token: token.tokenType + " " + token.accessToken,
2008
- customer: typeof customerDataProvider === 'function' ? parseCustomerUpdate(customerDataProvider()) : {},
2009
- customer_side_storage: sideStorage,
2010
- is_mobile: mobile,
2011
- application: pick(['name', 'version'], application)
2012
- };
2013
- if (typeof groupId === 'number') {
2014
- payload.group_id = groupId;
2015
- }
2016
- if (application.channelType) {
2017
- payload.application.channel_type = application.channelType;
2018
- }
2019
- if (page !== null) {
2020
- sentPage = page;
2021
- payload.customer_page = page;
2022
- }
2023
- if (referrer !== null) {
2024
- payload.referrer = referrer;
2025
- }
2026
- return Promise.race([sendLoginFlowRequest(store, LOGIN, payload), delay(15 * 1000).then(function () {
2027
- return Promise.reject(createError$1({
2028
- message: 'Request timed out.',
2029
- code: REQUEST_TIMEOUT
2030
- }));
2031
- })]);
2032
- };
2033
- var updateCustomerPageIfNeeded = function updateCustomerPageIfNeeded() {
2034
- var _store$getState = store.getState(),
2035
- page = _store$getState.page;
2036
- if (sentPage !== page) {
2037
- sendLoginFlowRequest(store, UPDATE_CUSTOMER_PAGE$1, page)["catch"](noop);
2038
- }
2039
- sentPage = null;
2040
- };
2041
- return {
2042
- sendLogin: function sendLogin(_store) {
2043
- var _task;
2044
- // after switching to callbags, we should be able to use smth similar to redux-observable
2045
- // and thus just use store given to epic
2046
- store = _store;
2047
- (_task = task) == null ? void 0 : _task.cancel();
2048
- task = taskChain([getTokenAndSideStorage, dispatchSelfId, _sendLogin], function (loginResponse) {
2049
- task = null;
2050
- defaultBackoffStrategy.reset();
2051
- slowerBackoffStrategy.reset();
2052
- currentBackoffStrategy = defaultBackoffStrategy;
2053
2033
 
2054
- // TODO: rethink if this should be handled by SDK consumer
2055
- updateCustomerPageIfNeeded();
2056
- store.dispatch(loginSuccess(loginResponse));
2057
- }, function (error) {
2058
- task = null;
2059
- {
2060
- console.error('[Customer SDK] Login flow has thrown code', error.code, 'with', error);
2061
- }
2062
- switch (error.code) {
2063
- case AUTHENTICATION:
2064
- auth.getFreshToken();
2065
- reconnect$1();
2066
- return;
2067
- case CONNECTION_LOST:
2068
- // this is connectivity problem, not a server error
2069
- // and is taken care of in socket module
2070
- // as it has its own backoff implementation
2071
- return;
2072
- case MISDIRECTED_CONNECTION:
2073
- // socket gets reinitialized on this anyway, so just ignore it here
2074
- return;
2075
- case SDK_DESTROYED:
2076
- return;
2077
- // those are auth errors, we should maybe export those constants from the auth package
2078
- case 'SSO_IDENTITY_EXCEPTION':
2079
- case 'SSO_OAUTH_EXCEPTION':
2080
- if (error.message === 'server_error' || error.message === 'temporarily_unavailable') {
2081
- reconnect$1();
2082
- return;
2083
- }
2084
- destroy$1(error.message);
2085
- return;
2086
- case USERS_LIMIT_REACHED:
2087
- store.dispatch(pauseConnection(error.code.toLowerCase()));
2088
- return;
2089
- case IDENTITY_MISMATCH:
2090
- case CUSTOMER_BANNED$1:
2091
- case WRONG_PRODUCT_VERSION:
2092
- destroy$1(error.code.toLowerCase());
2093
- return;
2094
- case SERVICE_TEMPORARILY_UNAVAILABLE:
2095
- currentBackoffStrategy = slowerBackoffStrategy;
2096
- reconnect$1();
2097
- return;
2098
- default:
2099
- reconnect$1();
2100
- return;
2101
- }
2102
- });
2103
- },
2104
- cancel: function cancel() {
2105
- var _task2;
2106
- (_task2 = task) == null ? void 0 : _task2.cancel();
2107
- }
2034
+ // eslint-disable-next-line local/no-livechat-package-direct-file-import
2035
+ /**
2036
+ * Logs event to Graylog with provided config data.
2037
+ * Logging request is fired only when all of those conditions are true:
2038
+ * 1. package is used in lc production environment
2039
+ * 2. package is used standalone because only then "customer_sdk" will be set to customer_sdk
2040
+ */
2041
+ var log = function log(_ref) {
2042
+ var env = _ref.env,
2043
+ organizationId = _ref.organizationId,
2044
+ eventName = _ref.eventName;
2045
+ if (env !== 'production' || "customer_sdk" !== 'customer_sdk') {
2046
+ return Promise.resolve();
2047
+ }
2048
+ var message = {
2049
+ event_name: eventName,
2050
+ severity: 'Informational',
2051
+ sdkVersion: "5.0.0"
2108
2052
  };
2109
- }
2053
+ var body = {
2054
+ organizationId: organizationId,
2055
+ event_id: 'chat_widget_customer_sdk',
2056
+ message: JSON.stringify(message)
2057
+ };
2058
+ return makeGraylogRequest('https://applog.livechatinc.com/logs', buildQueryString(body));
2059
+ };
2110
2060
 
2111
- var checkGoals = function checkGoals(store, auth, sessionFields) {
2061
+ var sendCustomerActions = function sendCustomerActions(_ref, _ref2) {
2062
+ var auth = _ref.auth,
2063
+ store = _ref.store;
2064
+ var actions = _ref2.actions;
2112
2065
  return auth.getToken().then(function (token) {
2113
2066
  var state = store.getState();
2114
- if (getSelfId(state) === null) {
2115
- store.dispatch(setSelfId(token.entityId));
2116
- }
2117
- var page = state.page;
2118
- if (!page || !page.url) {
2119
- return;
2120
- }
2121
- var query = buildQueryString({
2067
+ var query = buildQueryString(_extends({
2122
2068
  organization_id: state.organizationId
2123
- });
2124
- var payload = {
2125
- session_fields: parseCustomerSessionFields(sessionFields || {}),
2126
- group_id: state.groupId || 0,
2127
- page_url: page.url
2128
- };
2129
- return unfetch(getServerUrl(state) + "/action/" + CHECK_GOALS$1 + "?" + query, {
2069
+ }, getRegionParam(state)));
2070
+ var apiUrl = getServerUrl(state) + "/action/" + SEND_CUSTOMER_ACTIONS + "?" + query;
2071
+ return fetch(apiUrl, {
2130
2072
  method: 'POST',
2131
2073
  headers: {
2132
2074
  'Content-Type': 'application/json',
2133
2075
  Authorization: token.tokenType + " " + token.accessToken
2134
2076
  },
2135
- body: JSON.stringify(payload)
2136
- }).then(function () {
2137
- // TODO: we should actually normalize response here
2138
- return undefined;
2139
- });
2077
+ body: JSON.stringify({
2078
+ actions: actions
2079
+ }),
2080
+ keepalive: true
2081
+ }).then(noop);
2140
2082
  });
2141
2083
  };
2142
2084
 
2143
- var failAllRequests = function failAllRequests(_ref, reason) {
2144
- var getState = _ref.getState,
2145
- dispatch = _ref.dispatch;
2146
- var state = getState();
2147
- var requests = getAllRequests(state);
2148
- dispatch({
2149
- type: FAIL_ALL_REQUESTS,
2150
- payload: {
2151
- rejects: Object.keys(requests).map(function (requestId) {
2152
- return requests[requestId].reject;
2085
+ var sendGreetingButtonClicked = function sendGreetingButtonClicked(_ref, _ref2) {
2086
+ var auth = _ref.auth,
2087
+ store = _ref.store;
2088
+ var greetingUniqueId = _ref2.greetingUniqueId,
2089
+ buttonId = _ref2.buttonId;
2090
+ return auth.getToken().then(function (token) {
2091
+ var state = store.getState();
2092
+ var query = buildQueryString(_extends({
2093
+ organization_id: state.organizationId
2094
+ }, getRegionParam(state)));
2095
+ var apiUrl = getServerUrl(state) + "/action/" + SEND_GREETING_BUTTON_CLICKED + "?" + query;
2096
+ return fetch(apiUrl, {
2097
+ method: 'POST',
2098
+ headers: {
2099
+ 'Content-Type': 'application/json',
2100
+ Authorization: token.tokenType + " " + token.accessToken
2101
+ },
2102
+ body: JSON.stringify({
2103
+ greeting_unique_id: greetingUniqueId,
2104
+ button_id: buttonId
2153
2105
  }),
2154
- reason: reason
2155
- }
2106
+ keepalive: true
2107
+ }).then(noop);
2156
2108
  });
2157
2109
  };
2158
- var failRequest = function failRequest(_ref2, requestAction, error) {
2159
- var getState = _ref2.getState,
2160
- dispatch = _ref2.dispatch;
2161
- var requestId = requestAction.payload.id;
2162
- dispatch({
2163
- type: REQUEST_FAILED,
2164
- payload: {
2165
- id: requestId,
2166
- reject: getState().requests[requestId].reject,
2167
- error: error
2168
- }
2169
- });
2110
+
2111
+ // TODO: this thing is not really well typed and should be improved
2112
+ var sendRequestAction = function sendRequestAction(store, action) {
2113
+ action.payload.id = generateUniqueId(store.getState().requests);
2114
+ var _promiseDeferred = promiseDeferred(),
2115
+ resolve = _promiseDeferred.resolve,
2116
+ reject = _promiseDeferred.reject,
2117
+ promise = _promiseDeferred.promise;
2118
+ action.payload.promise = promise;
2119
+ action.payload.resolve = resolve;
2120
+ action.payload.reject = reject;
2121
+ store.dispatch(action);
2122
+ return promise;
2170
2123
  };
2171
2124
 
2172
2125
  var SUCCESS = Object.freeze({
2173
2126
  success: true
2174
2127
  });
2175
2128
 
2129
+ var _excluded$4 = ["group_id"];
2176
2130
  var parseCommonEventProps = function parseCommonEventProps(threadId, event) {
2177
2131
  var parsed = {
2178
2132
  id: event.id,
@@ -2237,18 +2191,24 @@
2237
2191
  name: file.name
2238
2192
  });
2239
2193
  };
2240
- var parseForm = function parseForm(thread, form) {
2194
+ var parseForm$1 = function parseForm(thread, form) {
2241
2195
  return _extends({}, parseCommonEventProps(thread, form), {
2242
2196
  authorId: 'system',
2243
2197
  type: FORM,
2244
- formId: form.form_id,
2198
+ formId: form.form_id
2199
+ }, form.form_type && {
2200
+ formType: form.form_type
2201
+ }, {
2245
2202
  fields: form.fields
2246
2203
  });
2247
2204
  };
2248
2205
  var parseFilledForm = function parseFilledForm(thread, filledForm) {
2249
2206
  return _extends({}, parseCommonEventProps(thread, filledForm), {
2250
2207
  type: FILLED_FORM,
2251
- formId: filledForm.form_id,
2208
+ formId: filledForm.form_id
2209
+ }, filledForm.form_type && {
2210
+ formType: filledForm.form_type
2211
+ }, {
2252
2212
  fields: filledForm.fields.map(function (field) {
2253
2213
  switch (field.type) {
2254
2214
  case 'group_chooser':
@@ -2258,7 +2218,7 @@
2258
2218
  }
2259
2219
  var _field$answer = field.answer,
2260
2220
  groupId = _field$answer.group_id,
2261
- answer = _objectWithoutPropertiesLoose(_field$answer, ["group_id"]);
2221
+ answer = _objectWithoutPropertiesLoose(_field$answer, _excluded$4);
2262
2222
  return _extends({}, field, {
2263
2223
  answer: _extends({}, answer, {
2264
2224
  groupId: groupId
@@ -2302,69 +2262,147 @@
2302
2262
  alternativeText: image.alternative_text
2303
2263
  });
2304
2264
  }
2265
+ if (element.ecommerce) {
2266
+ parsed.ecommerce = _extends({
2267
+ productId: element.ecommerce.product_id,
2268
+ viewType: element.ecommerce.view_type
2269
+ }, typeof element.ecommerce.label === 'string' && {
2270
+ label: element.ecommerce.label
2271
+ }, Array.isArray(element.ecommerce.options) && {
2272
+ options: element.ecommerce.options.map(function (option) {
2273
+ return _extends({
2274
+ label: option.label,
2275
+ optionId: option.option_id
2276
+ }, option.price !== undefined && {
2277
+ price: option.price
2278
+ }, option.regular_price !== undefined && {
2279
+ regularPrice: option.regular_price
2280
+ }, option.max_price !== undefined && {
2281
+ maxPrice: option.max_price
2282
+ }, option.currency !== undefined && {
2283
+ currency: option.currency
2284
+ }, typeof option.color === 'string' && {
2285
+ color: option.color
2286
+ }, option.image_url && _extends({
2287
+ imageUrl: option.image_url
2288
+ }, typeof option.image_thumbnail_url === 'string' && {
2289
+ imageThumbnailUrl: option.image_thumbnail_url
2290
+ }), typeof option.available === 'boolean' && {
2291
+ available: option.available
2292
+ }, typeof option.selected === 'boolean' && {
2293
+ selected: option.selected
2294
+ });
2295
+ })
2296
+ }, Array.isArray(element.ecommerce.addons) && {
2297
+ addons: element.ecommerce.addons.map(function (addon) {
2298
+ switch (addon.addon_type) {
2299
+ case 'price_range':
2300
+ return _extends({
2301
+ addonType: addon.addon_type
2302
+ }, addon.range_from !== undefined && {
2303
+ rangeFrom: addon.range_from
2304
+ }, addon.range_to !== undefined && {
2305
+ rangeTo: addon.range_to
2306
+ }, typeof addon.currency === 'string' && {
2307
+ currency: addon.currency
2308
+ });
2309
+ default:
2310
+ return {
2311
+ addonType: addon.addon_type
2312
+ };
2313
+ }
2314
+ })
2315
+ });
2316
+ }
2305
2317
  if (element.buttons) {
2306
2318
  parsed.buttons = element.buttons.map(function (serverButton) {
2307
2319
  switch (serverButton.type) {
2308
2320
  case 'message':
2321
+ case 'add_to_cart':
2322
+ case 'show_gallery':
2323
+ case 'copy':
2309
2324
  case 'phone':
2310
2325
  {
2311
- return {
2326
+ return _extends({
2312
2327
  type: serverButton.type,
2313
2328
  text: serverButton.text,
2314
2329
  postbackId: serverButton.postback_id,
2315
2330
  userIds: serverButton.user_ids,
2316
2331
  value: serverButton.value,
2317
2332
  role: serverButton.role || 'default'
2318
- };
2333
+ }, serverButton.button_id && {
2334
+ buttonId: serverButton.button_id
2335
+ });
2319
2336
  }
2320
2337
  case 'cancel':
2321
2338
  {
2322
- return {
2339
+ return _extends({
2323
2340
  type: serverButton.type,
2324
2341
  text: serverButton.text,
2325
2342
  postbackId: serverButton.postback_id,
2326
2343
  userIds: serverButton.user_ids,
2327
2344
  role: serverButton.role || 'default'
2328
- };
2345
+ }, serverButton.button_id && {
2346
+ buttonId: serverButton.button_id
2347
+ });
2348
+ }
2349
+ case 'url':
2350
+ {
2351
+ var button = _extends({
2352
+ type: serverButton.type,
2353
+ text: serverButton.text,
2354
+ postbackId: serverButton.postback_id,
2355
+ userIds: serverButton.user_ids,
2356
+ value: serverButton.value,
2357
+ role: serverButton.role || 'default'
2358
+ }, serverButton.button_id && {
2359
+ buttonId: serverButton.button_id
2360
+ });
2361
+ if (serverButton.target) {
2362
+ button.target = serverButton.target;
2363
+ }
2364
+ return button;
2329
2365
  }
2330
- case 'url':
2366
+ case 'open_external':
2331
2367
  {
2332
- var button = {
2368
+ var _button = _extends({
2333
2369
  type: serverButton.type,
2334
2370
  text: serverButton.text,
2335
2371
  postbackId: serverButton.postback_id,
2336
2372
  userIds: serverButton.user_ids,
2337
2373
  value: serverButton.value,
2338
2374
  role: serverButton.role || 'default'
2339
- };
2340
- if (serverButton.target) {
2341
- button.target = serverButton.target;
2342
- }
2343
- return button;
2375
+ }, serverButton.button_id && {
2376
+ buttonId: serverButton.button_id
2377
+ }, serverButton.target && {
2378
+ target: serverButton.target
2379
+ });
2380
+ return _button;
2344
2381
  }
2345
2382
  case 'webview':
2346
2383
  {
2347
- var _button = {
2384
+ var _button2 = _extends({
2348
2385
  type: serverButton.type,
2349
2386
  text: serverButton.text,
2350
2387
  postbackId: serverButton.postback_id,
2351
2388
  userIds: serverButton.user_ids,
2352
2389
  value: serverButton.value,
2353
2390
  role: serverButton.role || 'default'
2354
- };
2355
- if (typeof serverButton.webview_height === 'string') {
2356
- _button.webviewHeight = serverButton.webview_height;
2357
- }
2358
- return _button;
2391
+ }, serverButton.button_id && {
2392
+ buttonId: serverButton.button_id
2393
+ });
2394
+ return _button2;
2359
2395
  }
2360
2396
  default:
2361
2397
  {
2362
- return {
2398
+ return _extends({
2363
2399
  text: serverButton.text,
2364
2400
  postbackId: serverButton.postback_id,
2365
2401
  userIds: serverButton.user_ids,
2366
2402
  role: serverButton.role || 'default'
2367
- };
2403
+ }, serverButton.button_id && {
2404
+ buttonId: serverButton.button_id
2405
+ });
2368
2406
  }
2369
2407
  }
2370
2408
  });
@@ -2376,6 +2414,7 @@
2376
2414
  case 'cards':
2377
2415
  case 'quick_replies':
2378
2416
  case 'sticker':
2417
+ case 'ecommerce':
2379
2418
  return _extends({}, parseCommonEventProps(thread, richMessage), {
2380
2419
  type: RICH_MESSAGE,
2381
2420
  template: richMessage.template_id,
@@ -2398,12 +2437,12 @@
2398
2437
  }
2399
2438
  return parsed;
2400
2439
  };
2401
- var parseEvent$1 = function parseEvent(thread, event) {
2440
+ var parseEvent = function parseEvent(thread, event) {
2402
2441
  switch (event.type) {
2403
2442
  case FILE:
2404
2443
  return parseFile(thread, event);
2405
2444
  case FORM:
2406
- return parseForm(thread, event);
2445
+ return parseForm$1(thread, event);
2407
2446
  case FILLED_FORM:
2408
2447
  return parseFilledForm(thread, event);
2409
2448
  case MESSAGE:
@@ -2424,10 +2463,11 @@
2424
2463
  addon: greeting.addon || null,
2425
2464
  uniqueId: greeting.unique_id,
2426
2465
  displayedFirstTime: greeting.displayed_first_time,
2466
+ isExitIntent: greeting.is_exit_intent,
2427
2467
  accepted: greeting.accepted || false,
2428
2468
  subtype: greeting.subtype || 'greeting',
2429
2469
  // threadId is typed as nonoptional string but for greetings it doesn't exist
2430
- event: parseEvent$1(null, greeting.event),
2470
+ event: parseEvent(null, greeting.event),
2431
2471
  agent: {
2432
2472
  id: greeting.agent.id,
2433
2473
  name: greeting.agent.name,
@@ -2440,7 +2480,7 @@
2440
2480
 
2441
2481
  // we could use `mergeAll` for this, but we need to preserve insertion order here
2442
2482
  // so it's better to rely on a custom implementation
2443
- var parseCustomerSessionFields$1 = function parseCustomerSessionFields(sessionFields) {
2483
+ var parseCustomerSessionFields = function parseCustomerSessionFields(sessionFields) {
2444
2484
  return sessionFields.reduce(function (acc, field) {
2445
2485
  var _Object$keys = Object.keys(field),
2446
2486
  key = _Object$keys[0];
@@ -2471,7 +2511,7 @@
2471
2511
  createdAt: thread.created_at,
2472
2512
  userIds: thread.user_ids,
2473
2513
  events: thread.events.map(function (event) {
2474
- return parseEvent$1(thread.id, event);
2514
+ return parseEvent(thread.id, event);
2475
2515
  }).filter(Boolean),
2476
2516
  properties: properties,
2477
2517
  previousThreadId: thread.previous_thread_id || null,
@@ -2504,7 +2544,7 @@
2504
2544
  var parseCustomerOptionalProps = function parseCustomerOptionalProps(customerProps) {
2505
2545
  var optionalProps = pickOwn(['avatar', 'email', 'name'], customerProps);
2506
2546
  if (customerProps.session_fields) {
2507
- optionalProps.sessionFields = parseCustomerSessionFields$1(customerProps.session_fields);
2547
+ optionalProps.sessionFields = parseCustomerSessionFields(customerProps.session_fields);
2508
2548
  }
2509
2549
  return optionalProps;
2510
2550
  };
@@ -2535,44 +2575,315 @@
2535
2575
  }
2536
2576
  });
2537
2577
  };
2538
- var parsePredictedAgent = function parsePredictedAgent(payload) {
2539
- var agent = payload.agent,
2540
- queue = payload.queue;
2578
+ var parseQueueUpdate = function parseQueueUpdate(queueUpdate) {
2541
2579
  return {
2542
- agent: {
2543
- id: agent.id,
2544
- type: AGENT,
2545
- name: agent.name,
2546
- avatar: agent.avatar,
2547
- jobTitle: agent.job_title,
2548
- isBot: agent.is_bot
2580
+ position: queueUpdate.position,
2581
+ waitTime: queueUpdate.wait_time
2582
+ };
2583
+ };
2584
+ var parseQueue = function parseQueue(queue) {
2585
+ return _extends({}, parseQueueUpdate(queue), {
2586
+ queuedAt: queue.queued_at
2587
+ });
2588
+ };
2589
+ var parseChatUser = function parseChatUser(user) {
2590
+ return user.type === CUSTOMER ? parseChatCustomer(user) : parseChatAgent(user);
2591
+ };
2592
+ var parseGroupStatus = function parseGroupStatus(status) {
2593
+ return status === 'offline' ? 'offline' : 'online';
2594
+ };
2595
+
2596
+ var getSideStorageKey = function getSideStorageKey(store) {
2597
+ var _store$getState = store.getState(),
2598
+ organizationId = _store$getState.organizationId,
2599
+ groupId = _store$getState.groupId,
2600
+ uniqueGroups = _store$getState.uniqueGroups;
2601
+ return "side_storage_" + organizationId + (uniqueGroups ? ":" + groupId : '');
2602
+ };
2603
+ var getSideStorage = function getSideStorage(store, parentStorage) {
2604
+ var storage = createAsyncStorage(parentStorage);
2605
+ var sideStorageKey = getSideStorageKey(store);
2606
+ return storage.getItem(sideStorageKey)["catch"](noop).then(function (sideStorage) {
2607
+ return JSON.parse(sideStorage || '{}');
2608
+ })
2609
+ // shouldnt get triggered, just a defensive measure against malformed storage entries
2610
+ ["catch"](noop);
2611
+ };
2612
+ var saveSideStorage = function saveSideStorage(store, sideStorage, parentStorage) {
2613
+ var storage = createAsyncStorage(parentStorage);
2614
+ storage.setItem(getSideStorageKey(store), JSON.stringify(sideStorage))["catch"](noop);
2615
+ };
2616
+ var clearSideStorage = function clearSideStorage(store, parentStorage) {
2617
+ var storage = createAsyncStorage(parentStorage);
2618
+ storage.removeItem(getSideStorageKey(store))["catch"](noop);
2619
+ };
2620
+
2621
+ var failAllRequests = function failAllRequests(_ref, reason) {
2622
+ var getState = _ref.getState,
2623
+ dispatch = _ref.dispatch;
2624
+ var state = getState();
2625
+ var requests = getAllRequests(state);
2626
+ dispatch({
2627
+ type: FAIL_ALL_REQUESTS,
2628
+ payload: {
2629
+ rejects: Object.keys(requests).map(function (requestId) {
2630
+ return requests[requestId].reject;
2631
+ }),
2632
+ reason: reason
2633
+ }
2634
+ });
2635
+ };
2636
+ var failRequest = function failRequest(_ref2, requestAction, error) {
2637
+ var getState = _ref2.getState,
2638
+ dispatch = _ref2.dispatch;
2639
+ var requestId = requestAction.payload.id;
2640
+ dispatch({
2641
+ type: REQUEST_FAILED,
2642
+ payload: {
2643
+ id: requestId,
2644
+ reject: getState().requests[requestId].reject,
2645
+ error: error
2646
+ }
2647
+ });
2648
+ };
2649
+
2650
+ var checkGoals = function checkGoals(store, auth, sessionFields) {
2651
+ return auth.getToken().then(function (token) {
2652
+ var state = store.getState();
2653
+ if (getSelfId(state) === null) {
2654
+ store.dispatch(setSelfId(token.entityId));
2655
+ }
2656
+ var page = state.page;
2657
+ if (!page || !page.url) {
2658
+ return;
2659
+ }
2660
+ var query = buildQueryString(_extends({
2661
+ organization_id: state.organizationId
2662
+ }, getRegionParam(state)));
2663
+ var payload = {
2664
+ session_fields: parseCustomerSessionFields$1(sessionFields || {}),
2665
+ group_id: state.groupId || 0,
2666
+ page_url: page.url
2667
+ };
2668
+ return unfetch(getServerUrl(state) + "/action/" + CHECK_GOALS + "?" + query, {
2669
+ method: 'POST',
2670
+ headers: {
2671
+ 'Content-Type': 'application/json',
2672
+ Authorization: token.tokenType + " " + token.accessToken
2673
+ },
2674
+ body: JSON.stringify(payload)
2675
+ }).then(function () {
2676
+ // TODO: we should actually normalize response here
2677
+ return undefined;
2678
+ });
2679
+ });
2680
+ };
2681
+
2682
+ var taskChain = function taskChain(_ref, onSuccess, onError) {
2683
+ var steps = _arrayLikeToArray(_ref).slice(0);
2684
+ var cancelled = false;
2685
+ var _next = function next(intermediateResult) {
2686
+ var step = steps.shift();
2687
+ promiseTry(function () {
2688
+ return step(intermediateResult);
2689
+ }).then(function (result) {
2690
+ if (cancelled) {
2691
+ return;
2692
+ }
2693
+ if (steps.length) {
2694
+ _next(result);
2695
+ return;
2696
+ }
2697
+ onSuccess(result);
2698
+ }, function (error) {
2699
+ if (cancelled) {
2700
+ return;
2701
+ }
2702
+ onError(error);
2703
+ });
2704
+ };
2705
+ _next();
2706
+ return {
2707
+ cancel: function cancel() {
2708
+ cancelled = true;
2709
+ }
2710
+ };
2711
+ };
2712
+ var sendLoginFlowRequest = function sendLoginFlowRequest(store, type, payload) {
2713
+ return sendRequestAction(store, sendRequest$1(type, payload, 'login'));
2714
+ };
2715
+ var delay = function delay(ms) {
2716
+ return new Promise(function (resolve) {
2717
+ setTimeout(resolve, ms);
2718
+ });
2719
+ };
2720
+ function createLoginTask(auth, customerDataProvider, parentStorage) {
2721
+ var store;
2722
+ var sentPage = null;
2723
+ var task;
2724
+ var backoffConfig = {
2725
+ min: 300,
2726
+ max: 60000,
2727
+ jitter: 0.3
2728
+ };
2729
+ var defaultBackoffStrategy = createBackoff(backoffConfig);
2730
+ var slowerBackoffStrategy = createBackoff(_extends({}, backoffConfig, {
2731
+ min: 1000
2732
+ }));
2733
+ var currentBackoffStrategy = defaultBackoffStrategy;
2734
+ var destroy$1 = function destroy$1(reason) {
2735
+ return store.dispatch(destroy(reason));
2736
+ };
2737
+ var reconnect$1 = function reconnect$1() {
2738
+ return store.dispatch(reconnect(currentBackoffStrategy.duration()));
2739
+ };
2740
+ var getTokenAndSideStorage = function getTokenAndSideStorage() {
2741
+ return Promise.all([auth.getToken(), getSideStorage(store, parentStorage)]);
2742
+ };
2743
+ var dispatchSelfId = function dispatchSelfId(_ref3) {
2744
+ var token = _ref3[0],
2745
+ sideStorage = _ref3[1];
2746
+ var selfId = getSelfId(store.getState());
2747
+ if (selfId === null) {
2748
+ store.dispatch(setSelfId(token.entityId));
2749
+ } else if (selfId !== token.entityId) {
2750
+ if (parentStorage) {
2751
+ clearSideStorage(store, parentStorage);
2752
+ }
2753
+ store.dispatch(clearSensitiveSessionState());
2754
+ store.dispatch(setSelfId(token.entityId));
2755
+ store.dispatch(identityChanged({
2756
+ previousId: selfId,
2757
+ newId: token.entityId
2758
+ }));
2759
+ return [token, {}];
2760
+ }
2761
+ return [token, sideStorage];
2762
+ };
2763
+ var _sendLogin = function sendLogin(_ref4) {
2764
+ var token = _ref4[0],
2765
+ sideStorage = _ref4[1];
2766
+ var state = store.getState();
2767
+ var application = state.application,
2768
+ groupId = state.groupId,
2769
+ page = state.page,
2770
+ referrer = state.referrer,
2771
+ mobile = state.mobile,
2772
+ tabId = state.tabId;
2773
+ var payload = {
2774
+ token: token.tokenType + " " + token.accessToken,
2775
+ customer: typeof customerDataProvider === 'function' ? parseCustomerUpdate(customerDataProvider()) : {},
2776
+ customer_side_storage: sideStorage,
2777
+ is_mobile: mobile,
2778
+ application: pick(['name', 'version'], application)
2779
+ };
2780
+ if (typeof groupId === 'number') {
2781
+ payload.group_id = groupId;
2782
+ }
2783
+ if (application.channelType) {
2784
+ payload.application.channel_type = application.channelType;
2785
+ }
2786
+ if (page !== null) {
2787
+ sentPage = page;
2788
+ payload.customer_page = page;
2789
+ }
2790
+ if (referrer !== null) {
2791
+ payload.referrer = referrer;
2792
+ }
2793
+ if (tabId !== null) {
2794
+ payload.tab_id = tabId;
2795
+ }
2796
+ return Promise.race([sendLoginFlowRequest(store, LOGIN, payload), delay(15 * 1000).then(function () {
2797
+ return Promise.reject(createError({
2798
+ message: 'Request timed out.',
2799
+ code: REQUEST_TIMEOUT$1
2800
+ }));
2801
+ })]);
2802
+ };
2803
+ var updateCustomerPageIfNeeded = function updateCustomerPageIfNeeded() {
2804
+ var _store$getState = store.getState(),
2805
+ page = _store$getState.page;
2806
+ if (sentPage !== page) {
2807
+ sendLoginFlowRequest(store, UPDATE_CUSTOMER_PAGE, page)["catch"](noop);
2808
+ }
2809
+ sentPage = null;
2810
+ };
2811
+ return {
2812
+ sendLogin: function sendLogin(_store) {
2813
+ var _task;
2814
+ // after switching to callbags, we should be able to use smth similar to redux-observable
2815
+ // and thus just use store given to epic
2816
+ store = _store;
2817
+ (_task = task) == null || _task.cancel();
2818
+ task = taskChain([getTokenAndSideStorage, dispatchSelfId, _sendLogin], function (loginResponse) {
2819
+ task = null;
2820
+ defaultBackoffStrategy.reset();
2821
+ slowerBackoffStrategy.reset();
2822
+ currentBackoffStrategy = defaultBackoffStrategy;
2823
+
2824
+ // TODO: rethink if this should be handled by SDK consumer
2825
+ updateCustomerPageIfNeeded();
2826
+ store.dispatch(loginSuccess(loginResponse));
2827
+ }, function (error) {
2828
+ task = null;
2829
+ {
2830
+ console.error('[Customer SDK] Login flow has thrown code', error.code, 'with', error);
2831
+ }
2832
+ switch (error.code) {
2833
+ case AUTHENTICATION:
2834
+ auth.getFreshToken();
2835
+ reconnect$1();
2836
+ return;
2837
+ case CONNECTION_LOST:
2838
+ // this is connectivity problem, not a server error
2839
+ // and is taken care of in socket module
2840
+ // as it has its own backoff implementation
2841
+ return;
2842
+ case MISDIRECTED_CONNECTION$1:
2843
+ // socket gets reinitialized on this anyway, so just ignore it here
2844
+ return;
2845
+ case SDK_DESTROYED:
2846
+ return;
2847
+ // those are auth errors, we should maybe export those constants from the auth package
2848
+ case 'SSO_IDENTITY_EXCEPTION':
2849
+ case 'SSO_OAUTH_EXCEPTION':
2850
+ if (error.message === 'server_error' || error.message === 'temporarily_unavailable') {
2851
+ reconnect$1();
2852
+ return;
2853
+ }
2854
+ destroy$1(error.message);
2855
+ return;
2856
+ case USERS_LIMIT_REACHED:
2857
+ store.dispatch(pauseConnection(error.code.toLowerCase()));
2858
+ return;
2859
+ case CUSTOMER_BANNED:
2860
+ case WRONG_PRODUCT_VERSION:
2861
+ destroy$1(error.code.toLowerCase());
2862
+ return;
2863
+ case SERVICE_TEMPORARILY_UNAVAILABLE$1:
2864
+ currentBackoffStrategy = slowerBackoffStrategy;
2865
+ reconnect$1();
2866
+ return;
2867
+ default:
2868
+ reconnect$1();
2869
+ return;
2870
+ }
2871
+ });
2549
2872
  },
2550
- queue: queue
2551
- };
2552
- };
2553
- var parseQueueUpdate = function parseQueueUpdate(queueUpdate) {
2554
- return {
2555
- position: queueUpdate.position,
2556
- waitTime: queueUpdate.wait_time
2873
+ cancel: function cancel() {
2874
+ var _task2;
2875
+ (_task2 = task) == null || _task2.cancel();
2876
+ }
2557
2877
  };
2558
- };
2559
- var parseQueue = function parseQueue(queue) {
2560
- return _extends({}, parseQueueUpdate(queue), {
2561
- queuedAt: queue.queued_at
2562
- });
2563
- };
2564
- var parseChatUser = function parseChatUser(user) {
2565
- return user.type === CUSTOMER ? parseChatCustomer(user) : parseChatAgent(user);
2566
- };
2567
- var parseGroupStatus = function parseGroupStatus(status) {
2568
- return status === 'offline' ? 'offline' : 'online';
2569
- };
2878
+ }
2570
2879
 
2880
+ var _excluded$3 = ["present"],
2881
+ _excluded2$1 = ["statistics"];
2571
2882
  var _FAIL_ALL_REQUESTS_ME;
2572
2883
 
2573
2884
  // TODO: rethink how we handle reconnects
2574
2885
  var SMALL_RECONNECT_DELAY = 100;
2575
- var FAIL_ALL_REQUESTS_MESSAGES = (_FAIL_ALL_REQUESTS_ME = {}, _FAIL_ALL_REQUESTS_ME[CONNECTION_LOST] = 'Connection lost.', _FAIL_ALL_REQUESTS_ME[MISDIRECTED_CONNECTION] = 'Connected to wrong region.', _FAIL_ALL_REQUESTS_ME);
2886
+ var FAIL_ALL_REQUESTS_MESSAGES = (_FAIL_ALL_REQUESTS_ME = {}, _FAIL_ALL_REQUESTS_ME[CONNECTION_LOST] = 'Connection lost.', _FAIL_ALL_REQUESTS_ME[MISDIRECTED_CONNECTION$1] = 'Connected to wrong region.', _FAIL_ALL_REQUESTS_ME);
2576
2887
  var updateStateIfNeeded = function updateStateIfNeeded(store, action) {
2577
2888
  var state = store.getState();
2578
2889
  switch (action.type) {
@@ -2606,7 +2917,7 @@
2606
2917
  }
2607
2918
  }
2608
2919
  };
2609
- var sendRequest$1 = function sendRequest(socket, _ref3) {
2920
+ var sendRequest = function sendRequest(socket, _ref3, hasCustomIdentityProvider) {
2610
2921
  var _ref3$payload = _ref3.payload,
2611
2922
  id = _ref3$payload.id,
2612
2923
  request = _ref3$payload.request;
@@ -2616,20 +2927,19 @@
2616
2927
  switch (frame.action) {
2617
2928
  case LOGIN:
2618
2929
  {
2619
- var upgradedPushes = [];
2930
+ var pushes = {
2931
+ '3.6': values(serverPushActions).filter(function (pushAction) {
2932
+ return (
2933
+ // `customer_disconnected` can be sent immediately after opening the connection, before it even received login request
2934
+ // therefore it's not possible to subscribe for a particular version of this push - the "connection version" is always used
2935
+ pushAction !== CUSTOMER_DISCONNECTED
2936
+ );
2937
+ })
2938
+ };
2620
2939
  socket.emit(_extends({}, frame, {
2621
- version: '3.5',
2940
+ version: '3.6',
2622
2941
  payload: _extends({}, frame.payload, {
2623
- pushes: {
2624
- // '3.6': upgradedPushes,
2625
- '3.5': values(serverPushActions).filter(function (pushAction) {
2626
- return (
2627
- // `customer_disconnected` can be sent immediately after opening the connection, before it even received login request
2628
- // therefore it's not possible to subscribe for a particular version of this push - the "connection version" is always used
2629
- pushAction !== CUSTOMER_DISCONNECTED && !includes(pushAction, upgradedPushes)
2630
- );
2631
- })
2632
- }
2942
+ pushes: pushes
2633
2943
  })
2634
2944
  }));
2635
2945
  return;
@@ -2642,19 +2952,19 @@
2642
2952
  var emitUsers = function emitUsers(emit, users) {
2643
2953
  users.forEach(function (user) {
2644
2954
  if ('present' in user) {
2645
- var rest = _objectWithoutPropertiesLoose(user, ["present"]);
2955
+ var rest = _objectWithoutPropertiesLoose(user, _excluded$3);
2646
2956
  emit('user_data', rest);
2647
2957
  return;
2648
2958
  }
2649
2959
  if (user.type === CUSTOMER) {
2650
- var _rest = _objectWithoutPropertiesLoose(user, ["statistics"]);
2960
+ var _rest = _objectWithoutPropertiesLoose(user, _excluded2$1);
2651
2961
  emit('user_data', _rest);
2652
2962
  return;
2653
2963
  }
2654
2964
  emit('user_data', user);
2655
2965
  });
2656
2966
  };
2657
- var handlePush = function handlePush(_ref4, _ref5) {
2967
+ var handlePush$1 = function handlePush(_ref4, _ref5, parentStorage) {
2658
2968
  var emit = _ref4.emit,
2659
2969
  store = _ref4.store;
2660
2970
  var payload = _ref5.payload;
@@ -2673,7 +2983,7 @@
2673
2983
  emit('thread_properties_updated', payload.payload);
2674
2984
  return;
2675
2985
  case CUSTOMER_SIDE_STORAGE_UPDATED:
2676
- saveSideStorage(store, payload.payload.customer_side_storage);
2986
+ saveSideStorage(store, payload.payload.customer_side_storage, parentStorage);
2677
2987
  return;
2678
2988
  case CUSTOMER_DISCONNECTED:
2679
2989
  // each of those should currently lead to either reconnect or destroy call
@@ -2691,24 +3001,24 @@
2691
3001
  store.dispatch(reconnect(SMALL_RECONNECT_DELAY));
2692
3002
  emit('disconnected', payload.payload);
2693
3003
  break;
2694
- case CUSTOMER_BANNED:
3004
+ case CUSTOMER_BANNED$1:
2695
3005
  case CUSTOMER_TEMPORARILY_BLOCKED:
2696
3006
  case LICENSE_NOT_FOUND:
2697
3007
  case PRODUCT_VERSION_CHANGED:
2698
3008
  case TOO_MANY_CONNECTIONS:
2699
- case UNSUPPORTED_VERSION:
3009
+ case UNSUPPORTED_VERSION$1:
2700
3010
  case LOGGED_OUT_REMOTELY:
2701
3011
  // this also emits `disconnected` event - but it's handled in response to this action by destroy handler
2702
3012
  store.dispatch(destroy(payload.payload.reason));
2703
3013
  break;
2704
- case MISDIRECTED_CONNECTION$1:
2705
- failAllRequests(store, MISDIRECTED_CONNECTION);
3014
+ case MISDIRECTED_CONNECTION:
3015
+ failAllRequests(store, MISDIRECTED_CONNECTION$1);
2706
3016
  store.dispatch({
2707
3017
  type: CHANGE_REGION,
2708
3018
  payload: payload.payload.data
2709
3019
  });
2710
3020
  break;
2711
- case SERVICE_TEMPORARILY_UNAVAILABLE$1:
3021
+ case SERVICE_TEMPORARILY_UNAVAILABLE:
2712
3022
  case TOO_MANY_UNAUTHORIZED_CONNECTIONS:
2713
3023
  // this should only really fail a `login` request - as it's the only one sent before authorization
2714
3024
  // and login should reconnect on its own right now
@@ -2743,6 +3053,12 @@
2743
3053
  case INCOMING_TYPING_INDICATOR:
2744
3054
  emit(payload.action, payload.payload);
2745
3055
  return;
3056
+ case INCOMING_THINKING_INDICATOR:
3057
+ emit(payload.action, payload.payload);
3058
+ return;
3059
+ case INCOMING_EVENT_PREVIEW:
3060
+ emit(payload.action, payload.payload);
3061
+ return;
2746
3062
  case USER_ADDED_TO_CHAT:
2747
3063
  emitUsers(emit, [payload.payload.user]);
2748
3064
  emit(payload.action, payload.payload);
@@ -2752,7 +3068,7 @@
2752
3068
  return;
2753
3069
  }
2754
3070
  };
2755
- var handleResponse = function handleResponse(_ref6, _ref7) {
3071
+ var handleResponse$1 = function handleResponse(_ref6, _ref7) {
2756
3072
  var emit = _ref6.emit;
2757
3073
  var payload = _ref7.payload;
2758
3074
  switch (payload.action) {
@@ -2784,9 +3100,9 @@
2784
3100
  customerDataProvider = _ref8.customerDataProvider,
2785
3101
  emitter = _ref8.emitter,
2786
3102
  socket = _ref8.socket,
2787
- licenseId = _ref8.licenseId;
3103
+ parentStorage = _ref8.parentStorage;
2788
3104
  var emit = emitter.emit;
2789
- var loginTask = createLoginTask(auth, customerDataProvider, licenseId);
3105
+ var loginTask = createLoginTask(auth, customerDataProvider, parentStorage);
2790
3106
 
2791
3107
  // TODO: using Store type here is a lie, middleware only provides MiddlewareAPI here
2792
3108
  return function (action, store) {
@@ -2794,7 +3110,7 @@
2794
3110
  case CHANGE_REGION:
2795
3111
  socket.reinitialize();
2796
3112
  return;
2797
- case CHECK_GOALS:
3113
+ case CHECK_GOALS$1:
2798
3114
  checkGoals(store, auth, action.payload.sessionFields)["catch"](noop);
2799
3115
  return;
2800
3116
  case DESTROY:
@@ -2806,8 +3122,8 @@
2806
3122
  case 'manual':
2807
3123
  failAllRequests(store, SDK_DESTROYED);
2808
3124
  break;
2809
- case CUSTOMER_BANNED:
2810
- case LICENSE_EXPIRED:
3125
+ case CUSTOMER_BANNED$1:
3126
+ case LICENSE_EXPIRED$1:
2811
3127
  case PRODUCT_VERSION_CHANGED:
2812
3128
  case LOGGED_OUT_REMOTELY:
2813
3129
  // normalize those to CONNECTION_LOST as the handling on the consumer's side should be the same
@@ -2835,7 +3151,7 @@
2835
3151
  code: reason
2836
3152
  };
2837
3153
  rejects.forEach(function (reject) {
2838
- reject(createError$1(error));
3154
+ reject(createError(error));
2839
3155
  });
2840
3156
  return;
2841
3157
  }
@@ -2897,21 +3213,21 @@
2897
3213
  // TODO: this if doesn't seem to make much sense
2898
3214
  // I'm too afraid to remove it right now though
2899
3215
  if (action.payload.action === CUSTOMER_DISCONNECTED) {
2900
- handlePush({
3216
+ handlePush$1({
2901
3217
  emit: emit,
2902
3218
  store: store
2903
- }, action);
3219
+ }, action, parentStorage);
2904
3220
  return;
2905
3221
  }
2906
3222
  updateStateIfNeeded(store, action);
2907
- handlePush({
3223
+ handlePush$1({
2908
3224
  emit: emit,
2909
3225
  store: store
2910
- }, action);
3226
+ }, action, parentStorage);
2911
3227
  return;
2912
3228
  case PUSH_RESPONSE_RECEIVED:
2913
3229
  updateStateIfNeeded(store, action);
2914
- handleResponse({
3230
+ handleResponse$1({
2915
3231
  emit: emit
2916
3232
  }, action);
2917
3233
  return;
@@ -2924,12 +3240,12 @@
2924
3240
  var _action$payload3 = action.payload,
2925
3241
  reject = _action$payload3.reject,
2926
3242
  _error = _action$payload3.error;
2927
- reject(createError$1(_error));
3243
+ reject(createError(_error));
2928
3244
  return;
2929
3245
  }
2930
3246
  case RESPONSE_RECEIVED:
2931
3247
  updateStateIfNeeded(store, action);
2932
- handleResponse({
3248
+ handleResponse$1({
2933
3249
  emit: emit
2934
3250
  }, action);
2935
3251
  return;
@@ -2950,7 +3266,7 @@
2950
3266
  });
2951
3267
  return;
2952
3268
  }
2953
- sendRequest$1(socket, action);
3269
+ sendRequest(socket, action);
2954
3270
  }
2955
3271
  return;
2956
3272
  case SET_SELF_ID:
@@ -2982,11 +3298,14 @@
2982
3298
  socket.connect();
2983
3299
  store.dispatch(prefetchToken());
2984
3300
  return;
2985
- case UPDATE_CUSTOMER_PAGE:
3301
+ case UPDATE_CUSTOMER_PAGE$1:
2986
3302
  if (!isConnected(store.getState())) {
2987
3303
  return;
2988
3304
  }
2989
- sendRequestAction(store, sendRequest(UPDATE_CUSTOMER_PAGE$1, action.payload))["catch"](noop);
3305
+ sendRequestAction(store, sendRequest$1(UPDATE_CUSTOMER_PAGE, action.payload))["catch"](noop);
3306
+ return;
3307
+ case IDENTITY_CHANGED:
3308
+ emit('identity_changed', action.payload);
2990
3309
  return;
2991
3310
  default:
2992
3311
  return;
@@ -2994,91 +3313,6 @@
2994
3313
  };
2995
3314
  });
2996
3315
 
2997
- var HISTORY_EVENT_COUNT_TARGET = 25;
2998
- var createState = function createState() {
2999
- return {
3000
- status: 'idle',
3001
- queuedTasks: [],
3002
- nextPageId: null
3003
- };
3004
- };
3005
- var createChatHistoryIterator = function createChatHistoryIterator(sdk, chatId) {
3006
- var historyState = createState();
3007
- var next = function next(resolve, reject) {
3008
- switch (historyState.status) {
3009
- case 'idle':
3010
- historyState.status = 'fetching';
3011
- sdk.listThreads(historyState.nextPageId ? {
3012
- chatId: chatId,
3013
- pageId: historyState.nextPageId
3014
- } : {
3015
- chatId: chatId,
3016
- minEventsCount: HISTORY_EVENT_COUNT_TARGET
3017
- }).then(function (_ref) {
3018
- var threads = _ref.threads,
3019
- nextPageId = _ref.nextPageId;
3020
- historyState.nextPageId = nextPageId;
3021
- if (!historyState.nextPageId) {
3022
- historyState.status = 'done';
3023
- resolve({
3024
- value: {
3025
- threads: [].concat(threads).reverse()
3026
- },
3027
- done: true
3028
- });
3029
- } else {
3030
- historyState.status = 'idle';
3031
- resolve({
3032
- value: {
3033
- threads: [].concat(threads).reverse()
3034
- },
3035
- done: false
3036
- });
3037
- }
3038
- var queuedTask = historyState.queuedTasks.shift();
3039
- if (!queuedTask) {
3040
- return;
3041
- }
3042
- next(queuedTask.resolve, queuedTask.reject);
3043
- }, function (err) {
3044
- var queuedTasks = historyState.queuedTasks;
3045
- historyState.status = 'idle';
3046
- historyState.queuedTasks = [];
3047
- reject(err);
3048
- queuedTasks.forEach(function (queuedTask) {
3049
- return queuedTask.reject(err);
3050
- });
3051
- });
3052
- return;
3053
- case 'fetching':
3054
- historyState.queuedTasks.push({
3055
- resolve: resolve,
3056
- reject: reject
3057
- });
3058
- return;
3059
- case 'done':
3060
- resolve({
3061
- value: undefined,
3062
- done: true
3063
- });
3064
- return;
3065
- }
3066
- };
3067
- return {
3068
- next: function (_next) {
3069
- function next() {
3070
- return _next.apply(this, arguments);
3071
- }
3072
- next.toString = function () {
3073
- return _next.toString();
3074
- };
3075
- return next;
3076
- }(function () {
3077
- return new Promise(next);
3078
- })
3079
- };
3080
- };
3081
-
3082
3316
  // based on WebSocket's readyState - https://www.w3.org/TR/websockets/#the-websocket-interface
3083
3317
  var CONNECTING = 0;
3084
3318
  var OPEN = 1;
@@ -3307,9 +3541,9 @@
3307
3541
  var state = store.getState();
3308
3542
  var url = (getServerUrl(state) + "/rtm/ws").replace(/^https/, 'wss');
3309
3543
  return createPlatformClient(url, {
3310
- query: {
3544
+ query: _extends({
3311
3545
  organization_id: state.organizationId
3312
- },
3546
+ }, getRegionParam(state)),
3313
3547
  emitter: emitter
3314
3548
  });
3315
3549
  };
@@ -3331,6 +3565,8 @@
3331
3565
  });
3332
3566
  };
3333
3567
 
3568
+ var _excluded$2 = ["group_id"],
3569
+ _excluded2 = ["comment_label"];
3334
3570
  var parseChatPropertiesDeletedPush = function parseChatPropertiesDeletedPush(payload) {
3335
3571
  return {
3336
3572
  chatId: payload.chat_id,
@@ -3364,13 +3600,6 @@
3364
3600
  reason: payload.reason
3365
3601
  });
3366
3602
  };
3367
- var parseCustomerPageUpdatedPush = function parseCustomerPageUpdatedPush(payload) {
3368
- return {
3369
- url: payload.url,
3370
- title: payload.title,
3371
- openedAt: payload.opened_at
3372
- };
3373
- };
3374
3603
  var parseCustomerUpdatedPush = function parseCustomerUpdatedPush(payload) {
3375
3604
  return _extends({
3376
3605
  id: payload.id
@@ -3397,7 +3626,7 @@
3397
3626
  return {
3398
3627
  chatId: payload.chat_id,
3399
3628
  threadId: threadId,
3400
- event: parseEvent$1(threadId, payload.event)
3629
+ event: parseEvent(threadId, payload.event)
3401
3630
  };
3402
3631
  };
3403
3632
  var parseEventsMarkedAsSeenPush = function parseEventsMarkedAsSeenPush(payload) {
@@ -3428,7 +3657,7 @@
3428
3657
  var parseIncomingEventPush = function parseIncomingEventPush(payload) {
3429
3658
  return {
3430
3659
  chatId: payload.chat_id,
3431
- event: parseEvent$1(payload.thread_id, payload.event)
3660
+ event: parseEvent(payload.thread_id, payload.event)
3432
3661
  };
3433
3662
  };
3434
3663
  var parseIncomingGreetingPush = function parseIncomingGreetingPush(payload) {
@@ -3454,6 +3683,41 @@
3454
3683
  }
3455
3684
  };
3456
3685
  };
3686
+ var parseIncomingThinkingIndicatorPush = function parseIncomingThinkingIndicatorPush(payload) {
3687
+ var chatId = payload.chat_id,
3688
+ threadId = payload.thread_id,
3689
+ authorId = payload.author_id,
3690
+ sentAt = payload.sent_at,
3691
+ customId = payload.custom_id,
3692
+ title = payload.title,
3693
+ description = payload.description;
3694
+ return _extends({
3695
+ chatId: chatId,
3696
+ threadId: threadId,
3697
+ authorId: authorId,
3698
+ sentAt: sentAt
3699
+ }, customId && {
3700
+ customId: customId
3701
+ }, title && {
3702
+ title: title
3703
+ }, description && {
3704
+ description: description
3705
+ });
3706
+ };
3707
+ var parseIncomingEventPreviewPush = function parseIncomingEventPreviewPush(payload) {
3708
+ return {
3709
+ chatId: payload.chat_id,
3710
+ threadId: payload.thread_id,
3711
+ event: parseEvent(payload.thread_id, payload.event)
3712
+ };
3713
+ };
3714
+ var parseIncomingWelcomeMessagePush = function parseIncomingWelcomeMessagePush(payload) {
3715
+ return {
3716
+ id: payload.id,
3717
+ // threadId is typed as nonoptional string but for greetings it doesn't exist
3718
+ event: parseEvent(null, payload.event)
3719
+ };
3720
+ };
3457
3721
  var parseQueuePositionUpdatedPush = function parseQueuePositionUpdatedPush(payload) {
3458
3722
  return {
3459
3723
  chatId: payload.chat_id,
@@ -3485,7 +3749,8 @@
3485
3749
  var parseUserRemovedFromChatPush = function parseUserRemovedFromChatPush(payload) {
3486
3750
  return {
3487
3751
  chatId: payload.chat_id,
3488
- userId: payload.user_id
3752
+ userId: payload.user_id,
3753
+ reason: payload.reason
3489
3754
  };
3490
3755
  };
3491
3756
  var parseFields = function parseFields(fields) {
@@ -3495,7 +3760,7 @@
3495
3760
  return _extends({}, field, {
3496
3761
  options: field.options.map(function (_ref) {
3497
3762
  var groupId = _ref.group_id,
3498
- option = _objectWithoutPropertiesLoose(_ref, ["group_id"]);
3763
+ option = _objectWithoutPropertiesLoose(_ref, _excluded$2);
3499
3764
  return _extends({}, option, {
3500
3765
  groupId: groupId
3501
3766
  });
@@ -3504,7 +3769,7 @@
3504
3769
  case 'rating':
3505
3770
  {
3506
3771
  var commentLabel = field.comment_label,
3507
- parsed = _objectWithoutPropertiesLoose(field, ["comment_label"]);
3772
+ parsed = _objectWithoutPropertiesLoose(field, _excluded2);
3508
3773
  return _extends({}, parsed, {
3509
3774
  commentLabel: commentLabel
3510
3775
  });
@@ -3522,7 +3787,7 @@
3522
3787
  });
3523
3788
  return parseFields(withFakeIds);
3524
3789
  };
3525
- var parseForm$1 = function parseForm(form) {
3790
+ var parseForm = function parseForm(form) {
3526
3791
  var isTicketForm = !('id' in form.fields[0]);
3527
3792
  return {
3528
3793
  id: form.id,
@@ -3534,7 +3799,7 @@
3534
3799
  return payload;
3535
3800
  }
3536
3801
  return _extends({}, payload, {
3537
- form: parseForm$1(payload.form)
3802
+ form: parseForm(payload.form)
3538
3803
  });
3539
3804
  };
3540
3805
  var parseGetUrlInfoResponse = function parseGetUrlInfoResponse(payload) {
@@ -3556,6 +3821,24 @@
3556
3821
  }
3557
3822
  return urlInfo;
3558
3823
  };
3824
+ var parseRequestWelcomeMessageResponse = function parseRequestWelcomeMessageResponse(payload) {
3825
+ var id = payload.id,
3826
+ predicted_agent = payload.predicted_agent,
3827
+ queue = payload.queue;
3828
+ return {
3829
+ id: id,
3830
+ predictedAgent: {
3831
+ id: predicted_agent.id,
3832
+ type: predicted_agent.type,
3833
+ name: predicted_agent.name,
3834
+ avatar: predicted_agent.avatar,
3835
+ jobTitle: predicted_agent.job_title,
3836
+ isBot: predicted_agent.is_bot,
3837
+ botType: predicted_agent.bot_type
3838
+ },
3839
+ queue: queue
3840
+ };
3841
+ };
3559
3842
  var getAvailabilityBasedOnDynamicConfig = function getAvailabilityBasedOnDynamicConfig(_ref2) {
3560
3843
  var onlineGroups = _ref2.online_groups_ids,
3561
3844
  customerGroups = _ref2.customer_groups;
@@ -3591,7 +3874,7 @@
3591
3874
  return chatSummary;
3592
3875
  }
3593
3876
  chatSummary.lastEventsPerType = mapValues(function (lastEventPerType) {
3594
- return parseEvent$1(lastEventPerType.thread_id, lastEventPerType.event);
3877
+ return parseEvent(lastEventPerType.thread_id, lastEventPerType.event);
3595
3878
  }, lastEventsPerType);
3596
3879
  var refinedLastEventsPerType = lastEventsPerType;
3597
3880
  var lastEventSummariesArray = Object.keys(refinedLastEventsPerType).map(function (eventType) {
@@ -3689,11 +3972,6 @@
3689
3972
  action: push.action,
3690
3973
  payload: push.payload
3691
3974
  };
3692
- case CUSTOMER_PAGE_UPDATED:
3693
- return {
3694
- action: push.action,
3695
- payload: parseCustomerPageUpdatedPush(push.payload)
3696
- };
3697
3975
  case CUSTOMER_UPDATED:
3698
3976
  return {
3699
3977
  action: push.action,
@@ -3765,6 +4043,21 @@
3765
4043
  action: push.action,
3766
4044
  payload: parseIncomingTypingIndicatorPush(push.payload)
3767
4045
  };
4046
+ case INCOMING_THINKING_INDICATOR:
4047
+ return {
4048
+ action: push.action,
4049
+ payload: parseIncomingThinkingIndicatorPush(push.payload)
4050
+ };
4051
+ case INCOMING_EVENT_PREVIEW:
4052
+ return {
4053
+ action: push.action,
4054
+ payload: parseIncomingEventPreviewPush(push.payload)
4055
+ };
4056
+ case INCOMING_WELCOME_MESSAGE:
4057
+ return {
4058
+ action: push.action,
4059
+ payload: parseIncomingWelcomeMessagePush(push.payload)
4060
+ };
3768
4061
  case QUEUE_POSITION_UPDATED:
3769
4062
  return {
3770
4063
  action: push.action,
@@ -3836,11 +4129,6 @@
3836
4129
  action: response.action,
3837
4130
  payload: parseGetFormResponse(response.payload)
3838
4131
  };
3839
- case GET_PREDICTED_AGENT:
3840
- return {
3841
- action: response.action,
3842
- payload: parsePredictedAgent(response.payload)
3843
- };
3844
4132
  case GET_URL_INFO:
3845
4133
  return {
3846
4134
  action: response.action,
@@ -3871,6 +4159,11 @@
3871
4159
  action: response.action,
3872
4160
  payload: SUCCESS
3873
4161
  };
4162
+ case REQUEST_WELCOME_MESSAGE:
4163
+ return {
4164
+ action: response.action,
4165
+ payload: parseRequestWelcomeMessageResponse(response.payload)
4166
+ };
3874
4167
  case SEND_SNEAK_PEEK:
3875
4168
  return {
3876
4169
  action: response.action,
@@ -3881,6 +4174,11 @@
3881
4174
  action: response.action,
3882
4175
  payload: SUCCESS
3883
4176
  };
4177
+ case SEND_GREETING_BUTTON_CLICKED:
4178
+ return {
4179
+ action: response.action,
4180
+ payload: SUCCESS
4181
+ };
3884
4182
  case SEND_RICH_MESSAGE_POSTBACK:
3885
4183
  return {
3886
4184
  action: response.action,
@@ -3896,7 +4194,7 @@
3896
4194
  action: response.action,
3897
4195
  payload: SUCCESS
3898
4196
  };
3899
- case UPDATE_CUSTOMER_PAGE$1:
4197
+ case UPDATE_CUSTOMER_PAGE:
3900
4198
  return {
3901
4199
  action: response.action,
3902
4200
  payload: SUCCESS
@@ -3936,7 +4234,7 @@
3936
4234
  }
3937
4235
  });
3938
4236
  };
3939
- var handleResponse$1 = function handleResponse(_ref2, response) {
4237
+ var handleResponse = function handleResponse(_ref2, response) {
3940
4238
  var dispatch = _ref2.dispatch,
3941
4239
  getState = _ref2.getState;
3942
4240
  var requestId = response.request_id;
@@ -3974,7 +4272,7 @@
3974
4272
  }, parsedPush)
3975
4273
  });
3976
4274
  };
3977
- var handlePush$1 = function handlePush(store, push) {
4275
+ var handlePush = function handlePush(store, push) {
3978
4276
  var parsedPush = parsePush(push);
3979
4277
  if (!parsedPush) {
3980
4278
  // defensive measure against receiving unknown push
@@ -4005,7 +4303,7 @@
4005
4303
  // those are requests with indirect responses
4006
4304
  return;
4007
4305
  default:
4008
- handleResponse$1(store, message);
4306
+ handleResponse(store, message);
4009
4307
  return;
4010
4308
  }
4011
4309
  }
@@ -4018,7 +4316,7 @@
4018
4316
  return;
4019
4317
  }
4020
4318
  }
4021
- handlePush$1(store, message);
4319
+ handlePush(store, message);
4022
4320
  });
4023
4321
  socket.on('disconnect', function () {
4024
4322
  failAllRequests(store, CONNECTION_LOST);
@@ -4048,7 +4346,7 @@
4048
4346
  };
4049
4347
  var UPLOAD_FAILED = 'UPLOAD_FAILED';
4050
4348
  var UPLOAD_CANCELED = 'UPLOAD_CANCELED';
4051
- var uploadFile = function uploadFile(url, data, _temp) {
4349
+ var uploadFile$1 = function uploadFile(url, data, _temp) {
4052
4350
  var _ref = _temp === void 0 ? {} : _temp,
4053
4351
  headers = _ref.headers,
4054
4352
  _ref$method = _ref.method,
@@ -4130,14 +4428,14 @@
4130
4428
  };
4131
4429
  var validateFile = function validateFile(file) {
4132
4430
  if (file.size > SIZE_LIMIT) {
4133
- throw createError$1({
4431
+ throw createError({
4134
4432
  message: "The file is too big (max size is " + formatBytes(SIZE_LIMIT) + ").",
4135
4433
  code: TOO_BIG_FILE
4136
4434
  });
4137
4435
  }
4138
4436
  };
4139
4437
 
4140
- var uploadFile$1 = function uploadFile$1(_ref, _ref2) {
4438
+ var uploadFile = function uploadFile(_ref, _ref2) {
4141
4439
  var auth = _ref.auth,
4142
4440
  store = _ref.store;
4143
4441
  var file = _ref2.file,
@@ -4147,9 +4445,9 @@
4147
4445
  var send = new Promise(function (resolve, reject) {
4148
4446
  validateFile(file);
4149
4447
  var state = store.getState();
4150
- var query = buildQueryString({
4448
+ var query = buildQueryString(_extends({
4151
4449
  organization_id: state.organizationId
4152
- });
4450
+ }, getRegionParam(state)));
4153
4451
  var url = getServerUrl(state) + "/action/" + UPLOAD_FILE + "?" + query;
4154
4452
  var payload = {
4155
4453
  file: file
@@ -4159,7 +4457,7 @@
4159
4457
  reject(new Error('Upload cancelled.'));
4160
4458
  return;
4161
4459
  }
4162
- upload = uploadFile(url, payload, {
4460
+ upload = uploadFile$1(url, payload, {
4163
4461
  headers: {
4164
4462
  Authorization: token.tokenType + " " + token.accessToken
4165
4463
  },
@@ -4174,7 +4472,7 @@
4174
4472
  var _uploadError$response = uploadError.response.error,
4175
4473
  type = _uploadError$response.type,
4176
4474
  message = _uploadError$response.message;
4177
- reject(createError$1({
4475
+ reject(createError({
4178
4476
  message: message,
4179
4477
  code: type.toUpperCase()
4180
4478
  }));
@@ -4195,44 +4493,7 @@
4195
4493
  };
4196
4494
  };
4197
4495
 
4198
- var makeGraylogRequest = function makeGraylogRequest(url, body) {
4199
- return new Promise(function (resolve) {
4200
- var img = new Image();
4201
- img.src = url + "?" + body;
4202
- img.onerror = noop;
4203
- img.onload = function () {
4204
- return resolve();
4205
- };
4206
- });
4207
- };
4208
-
4209
- // eslint-disable-next-line local/no-livechat-package-direct-file-import
4210
- /**
4211
- * Logs event to Graylog with provided config data.
4212
- * Logging request is fired only when all of those conditions are true:
4213
- * 1. package is used in lc production environment
4214
- * 2. package is used standalone because only then "customer_sdk" will be set to customer_sdk
4215
- */
4216
- var log = function log(_ref) {
4217
- var env = _ref.env,
4218
- organizationId = _ref.organizationId,
4219
- eventName = _ref.eventName;
4220
- if (env !== 'production' || "customer_sdk" !== 'customer_sdk') {
4221
- return Promise.resolve();
4222
- }
4223
- var message = {
4224
- event_name: eventName,
4225
- severity: 'Informational',
4226
- sdkVersion: "4.0.2"
4227
- };
4228
- var body = {
4229
- organizationId: organizationId,
4230
- event_id: 'chat_widget_customer_sdk',
4231
- message: JSON.stringify(message)
4232
- };
4233
- return makeGraylogRequest('https://queue.livechatinc.com/logs', buildQueryString(body));
4234
- };
4235
-
4496
+ var _excluded$1 = ["on", "once", "off", "getChatHistory", "auth"];
4236
4497
  var LISTENER_IDENTITY = 'LISTENER_IDENTITY';
4237
4498
  var listenersMap = {};
4238
4499
  var createDebuggedMethods = function createDebuggedMethods(methods, prefix) {
@@ -4293,7 +4554,7 @@
4293
4554
  _off = sdk.off,
4294
4555
  _getChatHistory = sdk.getChatHistory,
4295
4556
  auth = sdk.auth,
4296
- rest = _objectWithoutPropertiesLoose(sdk, ["on", "once", "off", "getChatHistory", "auth"]);
4557
+ rest = _objectWithoutPropertiesLoose(sdk, _excluded$1);
4297
4558
  var methods = createDebuggedMethods(rest);
4298
4559
  return Object.freeze(_extends({
4299
4560
  auth: Object.freeze(createDebuggedMethods(auth, '.auth'))
@@ -4340,38 +4601,35 @@
4340
4601
  }));
4341
4602
  });
4342
4603
 
4343
- var ASC = 'asc';
4344
- var DESC = 'desc';
4345
-
4346
- var sortOrders = /*#__PURE__*/Object.freeze({
4347
- __proto__: null,
4348
- ASC: ASC,
4349
- DESC: DESC
4350
- });
4351
-
4604
+ var _excluded = ["autoConnect", "customerDataProvider", "identityProvider", "parentStorage", "env"];
4352
4605
  var CHATS_PAGINATION_MAX_LIMIT = 25;
4353
- var init = function init(config, env, licenseId) {
4354
- if (env === void 0) {
4355
- env = 'production';
4356
- }
4606
+ var init = function init(config) {
4357
4607
  validateConfig(config);
4358
- var _config$autoConnect = config.autoConnect,
4359
- autoConnect = _config$autoConnect === void 0 ? true : _config$autoConnect,
4360
- customerDataProvider = config.customerDataProvider,
4361
- identityProvider = config.identityProvider,
4362
- instanceConfig = _objectWithoutPropertiesLoose(config, ["autoConnect", "customerDataProvider", "identityProvider"]);
4608
+ var _ref = config,
4609
+ _ref$autoConnect = _ref.autoConnect,
4610
+ autoConnect = _ref$autoConnect === void 0 ? true : _ref$autoConnect,
4611
+ customerDataProvider = _ref.customerDataProvider,
4612
+ identityProvider = _ref.identityProvider,
4613
+ parentStorage = _ref.parentStorage,
4614
+ configEnv = _ref.env,
4615
+ instanceConfig = _objectWithoutPropertiesLoose(_ref, _excluded);
4616
+ var env = configEnv && ['labs', 'staging'].includes(configEnv) ? configEnv : 'production';
4363
4617
  var store = finalCreateStore(_extends({}, instanceConfig, {
4364
4618
  env: env
4365
4619
  }));
4366
4620
  var emitter = createMitt();
4367
4621
  var socket = createSocketClient(store);
4368
- var auth = typeof identityProvider === 'function' ? identityProvider() : createAuth(instanceConfig, licenseId, env);
4622
+ var hasCustomIdentityProvider = typeof identityProvider === 'function';
4623
+ var auth = hasCustomIdentityProvider ? identityProvider() : createAuth(_extends({}, instanceConfig, {
4624
+ env: env
4625
+ }), parentStorage);
4369
4626
  store.addSideEffectsHandler(createSideEffectsHandler({
4370
4627
  emitter: emitter,
4371
4628
  socket: socket,
4372
4629
  auth: auth,
4373
4630
  customerDataProvider: customerDataProvider,
4374
- licenseId: licenseId
4631
+ parentStorage: parentStorage,
4632
+ hasCustomIdentityProvider: hasCustomIdentityProvider
4375
4633
  }));
4376
4634
  socketListener(store, socket);
4377
4635
  var sendRequestAction$1 = sendRequestAction.bind(null, store);
@@ -4381,18 +4639,18 @@
4381
4639
  });
4382
4640
  };
4383
4641
  var api = Object.freeze({
4384
- acceptGreeting: function acceptGreeting(_ref) {
4385
- var greetingId = _ref.greetingId,
4386
- uniqueId = _ref.uniqueId;
4387
- return sendRequestAction$1(sendRequest(ACCEPT_GREETING, {
4642
+ acceptGreeting: function acceptGreeting(_ref2) {
4643
+ var greetingId = _ref2.greetingId,
4644
+ uniqueId = _ref2.uniqueId;
4645
+ return sendRequestAction$1(sendRequest$1(ACCEPT_GREETING, {
4388
4646
  greeting_id: greetingId,
4389
4647
  unique_id: uniqueId
4390
4648
  }));
4391
4649
  },
4392
4650
  auth: auth,
4393
- cancelGreeting: function cancelGreeting(_ref2) {
4394
- var uniqueId = _ref2.uniqueId;
4395
- return sendRequestAction$1(sendRequest(CANCEL_GREETING, {
4651
+ cancelGreeting: function cancelGreeting(_ref3) {
4652
+ var uniqueId = _ref3.uniqueId;
4653
+ return sendRequestAction$1(sendRequest$1(CANCEL_GREETING, {
4396
4654
  unique_id: uniqueId
4397
4655
  }));
4398
4656
  },
@@ -4402,10 +4660,10 @@
4402
4660
  properties = _params$properties === void 0 ? ['score'] : _params$properties;
4403
4661
  return api.listThreads({
4404
4662
  chatId: chatId
4405
- }).then(function (_ref3) {
4406
- var threads = _ref3.threads;
4663
+ }).then(function (_ref4) {
4664
+ var threads = _ref4.threads;
4407
4665
  if (!threads.length) {
4408
- throw createError$1({
4666
+ throw createError({
4409
4667
  message: "There is no thread in \"" + chatId + "\".",
4410
4668
  code: MISSING_CHAT_THREAD
4411
4669
  });
@@ -4420,37 +4678,37 @@
4420
4678
  });
4421
4679
  },
4422
4680
  connect: startConnection,
4423
- deactivateChat: function deactivateChat(_ref4) {
4424
- var id = _ref4.id;
4425
- return sendRequestAction$1(sendRequest(DEACTIVATE_CHAT, {
4681
+ deactivateChat: function deactivateChat(_ref5) {
4682
+ var id = _ref5.id;
4683
+ return sendRequestAction$1(sendRequest$1(DEACTIVATE_CHAT, {
4426
4684
  id: id
4427
4685
  }));
4428
4686
  },
4429
- deleteChatProperties: function deleteChatProperties(_ref5) {
4430
- var id = _ref5.id,
4431
- properties = _ref5.properties;
4432
- return sendRequestAction$1(sendRequest(DELETE_CHAT_PROPERTIES, {
4687
+ deleteChatProperties: function deleteChatProperties(_ref6) {
4688
+ var id = _ref6.id,
4689
+ properties = _ref6.properties;
4690
+ return sendRequestAction$1(sendRequest$1(DELETE_CHAT_PROPERTIES, {
4433
4691
  id: id,
4434
4692
  properties: properties
4435
4693
  }));
4436
4694
  },
4437
- deleteEventProperties: function deleteEventProperties(_ref6) {
4438
- var chatId = _ref6.chatId,
4439
- threadId = _ref6.threadId,
4440
- eventId = _ref6.eventId,
4441
- properties = _ref6.properties;
4442
- return sendRequestAction$1(sendRequest(DELETE_EVENT_PROPERTIES, {
4695
+ deleteEventProperties: function deleteEventProperties(_ref7) {
4696
+ var chatId = _ref7.chatId,
4697
+ threadId = _ref7.threadId,
4698
+ eventId = _ref7.eventId,
4699
+ properties = _ref7.properties;
4700
+ return sendRequestAction$1(sendRequest$1(DELETE_EVENT_PROPERTIES, {
4443
4701
  chat_id: chatId,
4444
4702
  thread_id: threadId,
4445
4703
  event_id: eventId,
4446
4704
  properties: properties
4447
4705
  }));
4448
4706
  },
4449
- deleteThreadProperties: function deleteThreadProperties(_ref7) {
4450
- var chatId = _ref7.chatId,
4451
- threadId = _ref7.threadId,
4452
- properties = _ref7.properties;
4453
- return sendRequestAction$1(sendRequest(DELETE_THREAD_PROPERTIES, {
4707
+ deleteThreadProperties: function deleteThreadProperties(_ref8) {
4708
+ var chatId = _ref8.chatId,
4709
+ threadId = _ref8.threadId,
4710
+ properties = _ref8.properties;
4711
+ return sendRequestAction$1(sendRequest$1(DELETE_THREAD_PROPERTIES, {
4454
4712
  chat_id: chatId,
4455
4713
  thread_id: threadId,
4456
4714
  properties: properties
@@ -4462,42 +4720,32 @@
4462
4720
  disconnect: function disconnect() {
4463
4721
  store.dispatch(pauseConnection('manual'));
4464
4722
  },
4465
- getChat: function getChat(_ref8) {
4466
- var chatId = _ref8.chatId,
4467
- threadId = _ref8.threadId;
4468
- return sendRequestAction$1(sendRequest(GET_CHAT, {
4723
+ getChat: function getChat(_ref9) {
4724
+ var chatId = _ref9.chatId,
4725
+ threadId = _ref9.threadId;
4726
+ return sendRequestAction$1(sendRequest$1(GET_CHAT, {
4469
4727
  chat_id: chatId,
4470
4728
  thread_id: threadId
4471
4729
  }));
4472
4730
  },
4473
- getChatHistory: function getChatHistory(_ref9) {
4474
- var chatId = _ref9.chatId;
4731
+ getChatHistory: function getChatHistory(_ref0) {
4732
+ var chatId = _ref0.chatId;
4475
4733
  return createChatHistoryIterator(api, chatId);
4476
4734
  },
4477
4735
  getCustomer: function getCustomer() {
4478
- return sendRequestAction$1(sendRequest(GET_CUSTOMER, {}));
4736
+ return sendRequestAction$1(sendRequest$1(GET_CUSTOMER, {}));
4479
4737
  },
4480
- getForm: function getForm(_ref10) {
4481
- var groupId = _ref10.groupId,
4482
- type = _ref10.type;
4483
- return sendRequestAction$1(sendRequest(GET_FORM, {
4738
+ getForm: function getForm(_ref1) {
4739
+ var groupId = _ref1.groupId,
4740
+ type = _ref1.type;
4741
+ return sendRequestAction$1(sendRequest$1(GET_FORM, {
4484
4742
  group_id: groupId,
4485
4743
  type: type
4486
4744
  }));
4487
4745
  },
4488
- getPredictedAgent: function getPredictedAgent(params) {
4489
- if (params === void 0) {
4490
- params = {};
4491
- }
4492
- var _params = params,
4493
- groupId = _params.groupId;
4494
- return sendRequestAction$1(sendRequest(GET_PREDICTED_AGENT, typeof groupId === 'number' ? {
4495
- group_id: groupId
4496
- } : {}));
4497
- },
4498
- getUrlInfo: function getUrlInfo(_ref11) {
4499
- var url = _ref11.url;
4500
- return sendRequestAction$1(sendRequest(GET_URL_INFO, {
4746
+ getUrlInfo: function getUrlInfo(_ref10) {
4747
+ var url = _ref10.url;
4748
+ return sendRequestAction$1(sendRequest$1(GET_URL_INFO, {
4501
4749
  url: url
4502
4750
  }));
4503
4751
  },
@@ -4508,23 +4756,23 @@
4508
4756
  if ('limit' in params && typeof params.limit === 'number' && params.limit > CHATS_PAGINATION_MAX_LIMIT) {
4509
4757
  return Promise.reject(new Error("Specified limit is too high (max " + CHATS_PAGINATION_MAX_LIMIT + ")."));
4510
4758
  }
4511
- return sendRequestAction$1(sendRequest(LIST_CHATS, params.pageId === undefined ? {
4759
+ return sendRequestAction$1(sendRequest$1(LIST_CHATS, params.pageId === undefined ? {
4512
4760
  limit: params.limit || 10
4513
4761
  } : {
4514
4762
  page_id: params.pageId
4515
4763
  }));
4516
4764
  },
4517
4765
  listGroupStatuses: function listGroupStatuses(_temp) {
4518
- var _ref12 = _temp === void 0 ? {} : _temp,
4519
- groupIds = _ref12.groupIds;
4520
- return sendRequestAction$1(sendRequest(LIST_GROUP_STATUSES, groupIds ? {
4766
+ var _ref11 = _temp === void 0 ? {} : _temp,
4767
+ groupIds = _ref11.groupIds;
4768
+ return sendRequestAction$1(sendRequest$1(LIST_GROUP_STATUSES, groupIds ? {
4521
4769
  group_ids: groupIds
4522
4770
  } : {
4523
4771
  all: true
4524
4772
  }));
4525
4773
  },
4526
4774
  listThreads: function listThreads(params) {
4527
- return sendRequestAction$1(sendRequest(LIST_THREADS, params.pageId === undefined ? {
4775
+ return sendRequestAction$1(sendRequest$1(LIST_THREADS, params.pageId === undefined ? {
4528
4776
  chat_id: params.chatId,
4529
4777
  sort_order: params.sortOrder,
4530
4778
  limit: params.limit,
@@ -4534,10 +4782,10 @@
4534
4782
  page_id: params.pageId
4535
4783
  }));
4536
4784
  },
4537
- markEventsAsSeen: function markEventsAsSeen(_ref13) {
4538
- var chatId = _ref13.chatId,
4539
- seenUpTo = _ref13.seenUpTo;
4540
- return sendRequestAction$1(sendRequest(MARK_EVENTS_AS_SEEN, {
4785
+ markEventsAsSeen: function markEventsAsSeen(_ref12) {
4786
+ var chatId = _ref12.chatId,
4787
+ seenUpTo = _ref12.seenUpTo;
4788
+ return sendRequestAction$1(sendRequest$1(MARK_EVENTS_AS_SEEN, {
4541
4789
  chat_id: chatId,
4542
4790
  seen_up_to: seenUpTo
4543
4791
  }));
@@ -4550,10 +4798,10 @@
4550
4798
  rating = params.rating;
4551
4799
  return api.listThreads({
4552
4800
  chatId: chatId
4553
- }).then(function (_ref14) {
4554
- var threads = _ref14.threads;
4801
+ }).then(function (_ref13) {
4802
+ var threads = _ref13.threads;
4555
4803
  if (!threads.length) {
4556
- throw createError$1({
4804
+ throw createError({
4557
4805
  message: "There is no thread in \"" + chatId + "\".",
4558
4806
  code: MISSING_CHAT_THREAD
4559
4807
  });
@@ -4567,31 +4815,42 @@
4567
4815
  });
4568
4816
  });
4569
4817
  },
4818
+ requestWelcomeMessage: function requestWelcomeMessage(_temp2) {
4819
+ var _ref14 = _temp2 === void 0 ? {} : _temp2,
4820
+ id = _ref14.id;
4821
+ return sendRequestAction$1(sendRequest$1(REQUEST_WELCOME_MESSAGE, id ? {
4822
+ id: id
4823
+ } : {}));
4824
+ },
4570
4825
  resumeChat: function resumeChat(data) {
4571
4826
  log({
4572
4827
  env: env,
4573
4828
  organizationId: config.organizationId,
4574
4829
  eventName: 'chat_started'
4575
4830
  });
4576
- return sendRequestAction$1(sendRequest(RESUME_CHAT, parseResumeChatData(data)));
4831
+ return sendRequestAction$1(sendRequest$1(RESUME_CHAT, parseResumeChatData(data)));
4577
4832
  },
4578
- sendEvent: function (_sendEvent) {
4579
- function sendEvent(_x) {
4580
- return _sendEvent.apply(this, arguments);
4581
- }
4582
- sendEvent.toString = function () {
4583
- return _sendEvent.toString();
4584
- };
4585
- return sendEvent;
4586
- }(function (params) {
4833
+ sendEvent: function sendEvent$1(params) {
4587
4834
  return sendRequestAction$1(sendEvent(params));
4588
- }),
4835
+ },
4836
+ sendGreetingButtonClicked: function sendGreetingButtonClicked$1(options) {
4837
+ return sendGreetingButtonClicked({
4838
+ auth: auth,
4839
+ store: store
4840
+ }, options);
4841
+ },
4842
+ sendCustomerActions: function sendCustomerActions$1(options) {
4843
+ return sendCustomerActions({
4844
+ auth: auth,
4845
+ store: store
4846
+ }, options);
4847
+ },
4589
4848
  sendRichMessagePostback: function sendRichMessagePostback(_ref15) {
4590
4849
  var chatId = _ref15.chatId,
4591
4850
  threadId = _ref15.threadId,
4592
4851
  eventId = _ref15.eventId,
4593
4852
  postback = _ref15.postback;
4594
- return sendRequestAction$1(sendRequest(SEND_RICH_MESSAGE_POSTBACK, {
4853
+ return sendRequestAction$1(sendRequest$1(SEND_RICH_MESSAGE_POSTBACK, {
4595
4854
  chat_id: chatId,
4596
4855
  event_id: eventId,
4597
4856
  thread_id: threadId,
@@ -4600,8 +4859,8 @@
4600
4859
  },
4601
4860
  setCustomerSessionFields: function setCustomerSessionFields(_ref16) {
4602
4861
  var sessionFields = _ref16.sessionFields;
4603
- return sendRequestAction$1(sendRequest(SET_CUSTOMER_SESSION_FIELDS, {
4604
- session_fields: parseCustomerSessionFields(sessionFields)
4862
+ return sendRequestAction$1(sendRequest$1(SET_CUSTOMER_SESSION_FIELDS, {
4863
+ session_fields: parseCustomerSessionFields$1(sessionFields)
4605
4864
  }));
4606
4865
  },
4607
4866
  setSneakPeek: function setSneakPeek(_ref17) {
@@ -4611,7 +4870,7 @@
4611
4870
  if (!isChatActive(state, chatId) || !isConnected(state)) {
4612
4871
  return;
4613
4872
  }
4614
- sendRequestAction$1(sendRequest(SEND_SNEAK_PEEK, {
4873
+ sendRequestAction$1(sendRequest$1(SEND_SNEAK_PEEK, {
4615
4874
  chat_id: chatId,
4616
4875
  sneak_peek_text: sneakPeekText
4617
4876
  }))["catch"](noop);
@@ -4625,22 +4884,22 @@
4625
4884
  organizationId: config.organizationId,
4626
4885
  eventName: 'chat_started'
4627
4886
  });
4628
- return sendRequestAction$1(sendRequest(START_CHAT, parseStartChatData(data)));
4887
+ return sendRequestAction$1(sendRequest$1(START_CHAT, parseStartChatData(data)));
4629
4888
  },
4630
4889
  updateChatProperties: function updateChatProperties(_ref18) {
4631
4890
  var id = _ref18.id,
4632
4891
  properties = _ref18.properties;
4633
- return sendRequestAction$1(sendRequest(UPDATE_CHAT_PROPERTIES, {
4892
+ return sendRequestAction$1(sendRequest$1(UPDATE_CHAT_PROPERTIES, {
4634
4893
  id: id,
4635
4894
  properties: properties
4636
4895
  }));
4637
4896
  },
4638
4897
  updateCustomer: function updateCustomer(update) {
4639
- return sendRequestAction$1(sendRequest(UPDATE_CUSTOMER, parseCustomerUpdate(update)));
4898
+ return sendRequestAction$1(sendRequest$1(UPDATE_CUSTOMER, parseCustomerUpdate(update)));
4640
4899
  },
4641
4900
  updateCustomerPage: function updateCustomerPage(page) {
4642
4901
  store.dispatch({
4643
- type: UPDATE_CUSTOMER_PAGE,
4902
+ type: UPDATE_CUSTOMER_PAGE$1,
4644
4903
  payload: pickOwn(['title', 'url'], page)
4645
4904
  });
4646
4905
  },
@@ -4649,7 +4908,7 @@
4649
4908
  threadId = _ref19.threadId,
4650
4909
  eventId = _ref19.eventId,
4651
4910
  properties = _ref19.properties;
4652
- return sendRequestAction$1(sendRequest(UPDATE_EVENT_PROPERTIES, {
4911
+ return sendRequestAction$1(sendRequest$1(UPDATE_EVENT_PROPERTIES, {
4653
4912
  chat_id: chatId,
4654
4913
  event_id: eventId,
4655
4914
  thread_id: threadId,
@@ -4660,14 +4919,14 @@
4660
4919
  var chatId = _ref20.chatId,
4661
4920
  threadId = _ref20.threadId,
4662
4921
  properties = _ref20.properties;
4663
- return sendRequestAction$1(sendRequest(UPDATE_THREAD_PROPERTIES, {
4922
+ return sendRequestAction$1(sendRequest$1(UPDATE_THREAD_PROPERTIES, {
4664
4923
  chat_id: chatId,
4665
4924
  thread_id: threadId,
4666
4925
  properties: properties
4667
4926
  }));
4668
4927
  },
4669
- uploadFile: function uploadFile(options) {
4670
- return uploadFile$1({
4928
+ uploadFile: function uploadFile$1(options) {
4929
+ return uploadFile({
4671
4930
  auth: auth,
4672
4931
  store: store
4673
4932
  }, options);
@@ -4677,7 +4936,7 @@
4677
4936
  startConnection();
4678
4937
  } else {
4679
4938
  store.dispatch({
4680
- type: CHECK_GOALS,
4939
+ type: CHECK_GOALS$1,
4681
4940
  payload: {
4682
4941
  sessionFields: typeof customerDataProvider === 'function' ? customerDataProvider().sessionFields : {}
4683
4942
  }
@@ -4691,10 +4950,10 @@
4691
4950
  exports.eventTypes = eventTypes;
4692
4951
  exports.init = init;
4693
4952
  exports.parseCustomEvent = parseCustomEvent;
4694
- exports.parseEvent = parseEvent$1;
4953
+ exports.parseEvent = parseEvent;
4695
4954
  exports.parseFile = parseFile;
4696
4955
  exports.parseFilledForm = parseFilledForm;
4697
- exports.parseForm = parseForm$1;
4956
+ exports.parseForm = parseForm;
4698
4957
  exports.parseGreeting = parseGreeting;
4699
4958
  exports.parseMessage = parseMessage;
4700
4959
  exports.parseRichMessage = parseRichMessage;
@@ -4707,4 +4966,4 @@
4707
4966
 
4708
4967
  Object.defineProperty(exports, '__esModule', { value: true });
4709
4968
 
4710
- })));
4969
+ }));