@microsoft/omnichannel-chat-widget 2.0.1-main.b1649f1 → 2.0.1-main.d7b3891

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,7 @@
13
13
  1. [Installation](#installation)
14
14
  1. [WebChat dependency constraint](#webchat-dependency-constraint)
15
15
  1. [Example Usage](#example-usage)
16
+ 1. [Bot authentication and the sign-in card](#bot-authentication-and-the-sign-in-card)
16
17
  1. [Components](#components)
17
18
  1. [See Also](#see-also)
18
19
 
@@ -144,6 +145,60 @@ A typescript sample widget can be found [here](https://github.com/microsoft/omni
144
145
 
145
146
  ```react-scripts``` has deprecated to build the sample project, please refer to vite building instructions: [BuildingUsingVite.md](https://github.com/microsoft/omnichannel-chat-widget/blob/main/docs/BuildingUsingVite.md)
146
147
 
148
+ ## Bot authentication and the sign-in card
149
+
150
+ A bot that uses single sign-on (SSO) can send a sign-in (OAuth) card. The host page decides whether the widget shows the card. It passes a callback to the Omnichannel SDK method [`setBotAuthTokenProvider`](https://learn.microsoft.com/dynamics365/customer-service/develop/reference/methods/setbotauthtokenprovider), and the callback calls `callback({show: false})` for a customer who is already signed in.
151
+
152
+ When a sign-in card arrives, the widget asks the host for this result. It tries `fetchBotAuthConfigRetries` times (default `3`), `fetchBotAuthConfigRetryInterval` milliseconds apart (default `1000`), so it waits about 2 seconds by default. If the host doesn't answer in that time, `fallbackShowSignInCard` decides what happens:
153
+
154
+ | `fallbackShowSignInCard` | Card when the host doesn't answer in time | Telemetry |
155
+ | --- | --- | --- |
156
+ | Not set (default) | Shown | `SetBotAuthProviderNotFound` (with the error) |
157
+ | `false` | Hidden | `SetBotAuthProviderNotFound` (with the fallback value), then `SetBotAuthProviderHideCard` |
158
+ | `true` | Shown | `SetBotAuthProviderNotFound` (with the fallback value), then `SetBotAuthProviderDisplayCard` |
159
+
160
+ Which value to use:
161
+
162
+ | Your setup | `fallbackShowSignInCard` |
163
+ | --- | --- |
164
+ | Your page signs the customer in, and your `setBotAuthTokenProvider` callback passes the token to the bot (bot SSO) | `false` |
165
+ | You want the card to show whenever the callback is late, and you want this logged as a decision | `true` |
166
+ | Customers sign in through the sign-in card itself | Leave it unset |
167
+
168
+ ```js
169
+ const liveChatWidgetProps = {
170
+ chatSDK: chatSDK, // mandatory
171
+ chatConfig: chatConfig, // mandatory
172
+ webChatContainerProps: {
173
+ botAuthConfig: {
174
+ fallbackShowSignInCard: false // hide the card if the host doesn't answer in time
175
+ }
176
+ }
177
+ };
178
+ ```
179
+
180
+ If you use the live chat widget 2.0 script instead of this package, the function that the script's `data-customization-callback` attribute references must return a root props object that contains the setting, for example `{ webChatContainerProps: { botAuthConfig: { fallbackShowSignInCard: false } } }`. See [Develop a custom live chat widget](https://learn.microsoft.com/dynamics365/customer-service/develop/develop-live-chat-widget).
181
+
182
+ What the customer sees:
183
+
184
+ | Situation | Card |
185
+ | --- | --- |
186
+ | The host answers `callback({show: false})` in time | Hidden (`SetBotAuthProviderHideCard`) |
187
+ | The host answers `callback({show: true})` in time | Shown (`SetBotAuthProviderDisplayCard`) |
188
+ | The host doesn't answer in time (slow request, error, or no `callback(...)` call) | Depends on `fallbackShowSignInCard` (see the previous table) |
189
+ | The widget can't extract a sign-in ID from the card, or can't get a token exchange URL (from the card or from the Bot Framework token service) | Shown. The widget doesn't ask the host. |
190
+
191
+ `fallbackShowSignInCard` changes only what happens when the host doesn't answer in time. It isn't a substitute for a working `setBotAuthTokenProvider` callback. If you set it to `false` and the callback fails for a customer who isn't signed in, that customer doesn't see the card and can't sign in.
192
+
193
+ **Troubleshooting: a signed-in customer sometimes sees the sign-in card.** The `setBotAuthTokenProvider` callback probably didn't answer in time. Look for `SetBotAuthProviderNotFound` in the widget telemetry. To fix it:
194
+
195
+ 1. Call `callback(...)` on every code path of the function, including error paths. If the function throws before it calls `callback(...)`, the widget gets no answer.
196
+ 1. Make the whole function finish quickly. With the live chat widget 2.0 script, the widget gets the `callback(...)` value only after the function finishes, so slow work after `callback(...)` still delays the answer. For a sign-in card that your page already completed, call `callback({show: false})` and return at once. Otherwise, complete the token exchange, then call `callback(...)` with its result.
197
+ 1. If the function is correct but can't finish in about 2 seconds, increase `fetchBotAuthConfigRetries` or `fetchBotAuthConfigRetryInterval`.
198
+ 1. If your function passes a token to the bot for every customer before the chat needs it (bot SSO works), set `fallbackShowSignInCard: false`. Signing the customer in to your page, or using authenticated chat, doesn't by itself sign the customer in to the bot.
199
+
200
+ For the host-side callback, see [Pass authentication token to bot during single sign-on in live chat](https://learn.microsoft.com/dynamics365/customer-service/develop/pass-auth-token-sso-live-chat).
201
+
147
202
  ## Components
148
203
 
149
204
  For a detailed guide on how to customize each component with sample usages, please see our new [Developer Guide](https://github.com/microsoft/omnichannel-chat-widget/blob/main/docs/customizations/getstarted.md).
@@ -114,6 +114,11 @@ let TelemetryEvent = exports.TelemetryEvent = /*#__PURE__*/function (TelemetryEv
114
114
  TelemetryEvent["RecoveryEligibilityEvaluated"] = "RecoveryEligibilityEvaluated";
115
115
  TelemetryEvent["GetConversationDetailsCallStarted"] = "GetConversationDetailsCallStarted";
116
116
  TelemetryEvent["GetConversationDetailsCallFailed"] = "GetConversationDetailsCallFailed";
117
+ TelemetryEvent["UpdateTelemetryDataFailed"] = "UpdateTelemetryDataFailed";
118
+ TelemetryEvent["ChatTokenRenewalStateSyncFailed"] = "ChatTokenRenewalStateSyncFailed";
119
+ TelemetryEvent["ChatTokenRenewalStateSynced"] = "ChatTokenRenewalStateSynced";
120
+ TelemetryEvent["ChatTokenRenewalStateSyncSkipped"] = "ChatTokenRenewalStateSyncSkipped";
121
+ TelemetryEvent["ChatTokenRenewalStateSyncDeferred"] = "ChatTokenRenewalStateSyncDeferred";
117
122
  TelemetryEvent["EndChatSDKCallFailed"] = "EndChatSDKCallFailed";
118
123
  TelemetryEvent["DisconnectEndChatSDKCallFailed"] = "DisconnectEndChatSDKCallFailed";
119
124
  TelemetryEvent["GetChatReconnectContextSDKCallStarted"] = "GetChatReconnectContextSDKCallStarted";
@@ -430,6 +435,11 @@ let TelemetryConstants = exports.TelemetryConstants = /*#__PURE__*/function () {
430
435
  case TelemetryEvent.OnNewMessageFailed:
431
436
  case TelemetryEvent.OnNewMessageAudioNotificationFailed:
432
437
  case TelemetryEvent.GetConversationDetailsCallFailed:
438
+ case TelemetryEvent.UpdateTelemetryDataFailed:
439
+ case TelemetryEvent.ChatTokenRenewalStateSyncFailed:
440
+ case TelemetryEvent.ChatTokenRenewalStateSynced:
441
+ case TelemetryEvent.ChatTokenRenewalStateSyncSkipped:
442
+ case TelemetryEvent.ChatTokenRenewalStateSyncDeferred:
433
443
  case TelemetryEvent.EndChatSDKCall:
434
444
  case TelemetryEvent.EndChatEventReceived:
435
445
  case TelemetryEvent.EndChatSDKCallFailed:
@@ -18,6 +18,7 @@ var _utils = require("../../common/utils");
18
18
  var _liveChatConfigUtils = require("./common/liveChatConfigUtils");
19
19
  var _overridePropsOnMockIfApplicable = _interopRequireDefault(require("./common/overridePropsOnMockIfApplicable"));
20
20
  var _registerTelemetryLoggers = require("./common/registerTelemetryLoggers");
21
+ var _useChatTokenRenewal = require("./common/useChatTokenRenewal");
21
22
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
22
23
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
23
24
  function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
@@ -73,6 +74,7 @@ const LiveChatWidget = props => {
73
74
  (0, _react.useEffect)(() => {
74
75
  (0, _registerTelemetryLoggers.registerTelemetryLoggers)(props, dispatch);
75
76
  }, [dispatch]);
77
+ (0, _useChatTokenRenewal.useChatTokenRenewal)(facadeChatSDK, state, dispatch, (0, _utils.getWidgetCacheIdfromProps)(props));
76
78
  return /*#__PURE__*/_react.default.createElement(_FacadeChatSDKStore.FacadeChatSDKStore.Provider, {
77
79
  value: [facadeChatSDK, setFacadeChatSDK]
78
80
  }, /*#__PURE__*/_react.default.createElement(_ChatSDKStore.ChatSDKStore.Provider, {
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.isReconnectEnabled = exports.isPersistentEnabled = exports.handleChatReconnect = exports.getChatReconnectContext = void 0;
6
+ exports.isReconnectTriggered = exports.isReconnectEnabled = exports.isPersistentEnabled = exports.handleChatReconnect = exports.getChatReconnectContext = void 0;
7
7
  require("regenerator-runtime/runtime");
8
8
  var _TelemetryConstants = require("../../../common/telemetry/TelemetryConstants");
9
9
  var _Constants = require("../../../common/Constants");
@@ -13,6 +13,7 @@ var _omnichannelChatComponents = require("@microsoft/omnichannel-chat-components
13
13
  var _ConversationState = require("../../../contexts/common/ConversationState");
14
14
  var _LiveChatWidgetActionType = require("../../../contexts/common/LiveChatWidgetActionType");
15
15
  var _TelemetryHelper = require("../../../common/telemetry/TelemetryHelper");
16
+ var _createReducer = require("../../../contexts/createReducer");
16
17
  var _startChatErrorHandler = require("./startChatErrorHandler");
17
18
  // Return value: should start normal chat flow when reconnect is enabled
18
19
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -55,8 +56,35 @@ const handleChatReconnect = async (facadeChatSDK, props, dispatch, setAdapter, i
55
56
  return true;
56
57
  };
57
58
 
59
+ /**
60
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
61
+ * In that case the caller must not start another chat.
62
+ */
58
63
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
64
  exports.handleChatReconnect = handleChatReconnect;
65
+ const isReconnectTriggered = async (facadeChatSDK, props, dispatch, setAdapter, initStartChat, state) => {
66
+ if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
67
+ let reconnectChatStarted = false;
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ const initStartChatAndTrack = async function () {
70
+ reconnectChatStarted = await initStartChat(...arguments);
71
+ };
72
+ const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChatAndTrack, state);
73
+ // initStartChat resolves before React renders Active, so the in-memory state can still read Loading here.
74
+ // Its result tells whether reconnect started the chat; the in-memory state covers the reconnect pane.
75
+ const inMemoryState = (0, _createReducer.executeReducer)(state, {
76
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
77
+ payload: null
78
+ });
79
+ if (!noValidReconnectId && (reconnectChatStarted || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.Active || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.ReconnectChat)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ };
85
+
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ exports.isReconnectTriggered = isReconnectTriggered;
60
88
  const getChatReconnectContext = async (facadeChatSDK, chatConfig, props, isAuthenticatedChat, dispatch) => {
61
89
  try {
62
90
  var _props$reconnectChatP4;
@@ -68,7 +68,7 @@ const getGuard = (guards, facadeChatSDK) => {
68
68
  * Runs `operation` only if no other invocation for the same widget instance is already in
69
69
  * flight. Concurrent invocations are dropped (and reported through telemetry) rather than
70
70
  * awaiting the in-flight promise, so a future re-entrant call can never deadlock on itself.
71
- * No caller acts on the resolved value, so dropping is safe.
71
+ * A dropped invocation resolves to `undefined`.
72
72
  *
73
73
  * `blockedBy` lets an operation also yield to a different, already running operation for the
74
74
  * same widget instance without claiming that operation's lock.
@@ -84,14 +84,14 @@ const runExclusively = async (guards, facadeChatSDK, description, operation, pro
84
84
  WidgetCacheId: props ? (0, _utils.getWidgetCacheIdfromProps)(props) : undefined
85
85
  }
86
86
  });
87
- return;
87
+ return undefined;
88
88
  }
89
89
 
90
90
  // Claim the lock before invoking the operation, so a re-entrant call made from the
91
91
  // operation's synchronous preamble (before its first await) cannot slip past the check above.
92
92
  guard.inFlight = true;
93
93
  try {
94
- await operation();
94
+ return await operation();
95
95
  } finally {
96
96
  guard.inFlight = false;
97
97
  }
@@ -228,10 +228,15 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
228
228
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
229
229
  };
230
230
 
231
+ /**
232
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
233
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
234
+ */
231
235
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
232
236
  exports.setPreChatAndInitiateChat = setPreChatAndInitiateChat;
233
237
  const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
234
- return runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
238
+ const chatStarted = await runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
239
+ return chatStarted === true;
235
240
  };
236
241
 
237
242
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -346,7 +351,7 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
346
351
  (0, _startChatErrorHandler.logWidgetLoadComplete)(_Constants.WidgetLoadTelemetryMessage.PersistedStateRetrievedMessage);
347
352
  // Set post chat context in state, load in background to do not block the load
348
353
  (0, _setPostChatContextAndLoadSurvey.setPostChatContextAndLoadSurvey)(facadeChatSDK, dispatch, true);
349
- return;
354
+ return true;
350
355
  }
351
356
 
352
357
  // Persistent Chat relies on the `reconnectId` retrieved from reconnectablechats API to reconnect upon start chat and not `liveChatContext`
@@ -362,10 +367,13 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
362
367
  (0, _startChatErrorHandler.logWidgetLoadComplete)();
363
368
  // Set post chat context in state, load in background to do not block the load
364
369
  (0, _setPostChatContextAndLoadSurvey.setPostChatContextAndLoadSurvey)(facadeChatSDK, dispatch);
365
- // Updating chat session detail for telemetry
366
- await (0, _updateSessionDataForTelemetry.updateTelemetryData)(facadeChatSDK, dispatch);
370
+ // Updating chat session detail for telemetry, in background: getConversationDetails retries until the
371
+ // live work item exists (several seconds), and awaiting it would hold the start chat locks and drop the next start chat
372
+ (0, _updateSessionDataForTelemetry.updateTelemetryData)(facadeChatSDK, dispatch);
373
+ return true;
367
374
  } catch (ex) {
368
375
  (0, _startChatErrorHandler.handleStartChatError)(dispatch, facadeChatSDK, props, ex, isStartChatSuccessful);
376
+ return false;
369
377
  }
370
378
  };
371
379
 
@@ -12,16 +12,42 @@ var _TelemetryManager = require("../../../common/telemetry/TelemetryManager");
12
12
  var _utils = require("../../../common/utils");
13
13
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
14
  const updateTelemetryData = async (facadeChatSDK, dispatch) => {
15
- // load it concurrently, this will reduce the load time
16
- await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch), updateConversationDataForTelemetry(facadeChatSDK, dispatch)]);
15
+ var _facadeChatSDK$getCha;
16
+ // startChat no longer waits for this, so the next chat can start (chatSDKStateCleanUp assigns a new requestId)
17
+ // before these calls resolve. Results for an earlier chat must not overwrite the current chat's data.
18
+ // endChat also assigns a new requestId, so the chat that just ended still applies its own results.
19
+ const requestId = facadeChatSDK === null || facadeChatSDK === void 0 || (_facadeChatSDK$getCha = facadeChatSDK.getChatSDK()) === null || _facadeChatSDK$getCha === void 0 ? void 0 : _facadeChatSDK$getCha.requestId;
20
+ try {
21
+ // load it concurrently, this will reduce the load time
22
+ await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch, requestId), updateConversationDataForTelemetry(facadeChatSDK, dispatch, requestId)]);
23
+ } catch (error) {
24
+ _TelemetryHelper.TelemetryHelper.logSDKEvent(_TelemetryConstants.LogLevel.ERROR, {
25
+ Event: _TelemetryConstants.TelemetryEvent.UpdateTelemetryDataFailed,
26
+ ExceptionDetails: {
27
+ exception: `Update telemetry data failed: ${error}`
28
+ }
29
+ });
30
+ }
17
31
  };
18
32
 
19
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ // The requestId alone isn't enough: endChat also replaces it. Only the next chat's startChat gets a new chat token
34
+ // (endChat and chatSDKStateCleanUp clear it), so drop the result only when the SDK holds that next chat.
20
35
  exports.updateTelemetryData = updateTelemetryData;
21
- const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
36
+ const isFromEarlierChat = (facadeChatSDK, requestId) => {
37
+ var _chatSDK$chatToken;
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ const chatSDK = facadeChatSDK.getChatSDK();
40
+ return (chatSDK === null || chatSDK === void 0 ? void 0 : chatSDK.requestId) !== requestId && !!(chatSDK !== null && chatSDK !== void 0 && (_chatSDK$chatToken = chatSDK.chatToken) !== null && _chatSDK$chatToken !== void 0 && _chatSDK$chatToken.chatId);
41
+ };
42
+
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
22
45
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
23
46
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
47
  const chatSession = await facadeChatSDK.getCurrentLiveChatContext();
48
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
49
+ return;
50
+ }
25
51
  const telemetryData = _TelemetryHelper.TelemetryHelper.addSessionDataToTelemetry(chatSession, _TelemetryManager.TelemetryManager.InternalTelemetryData);
26
52
  dispatch({
27
53
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -37,10 +63,13 @@ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
37
63
  };
38
64
 
39
65
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch) => {
66
+ const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
41
67
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
42
68
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
69
  const liveWorkItem = await (0, _utils.getConversationDetailsCall)(facadeChatSDK);
70
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
71
+ return;
72
+ }
44
73
  const telemetryData = _TelemetryHelper.TelemetryHelper.addConversationDataToTelemetry(liveWorkItem, _TelemetryManager.TelemetryManager.InternalTelemetryData);
45
74
  dispatch({
46
75
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useChatTokenRenewal = void 0;
7
+ var _react = require("react");
8
+ var _omnichannelChatComponents = require("@microsoft/omnichannel-chat-components");
9
+ var _TelemetryConstants = require("../../../common/telemetry/TelemetryConstants");
10
+ var _Constants = require("../../../common/Constants");
11
+ var _ConversationState = require("../../../contexts/common/ConversationState");
12
+ var _LiveChatWidgetActionType = require("../../../contexts/common/LiveChatWidgetActionType");
13
+ var _TelemetryHelper = require("../../../common/telemetry/TelemetryHelper");
14
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
15
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
16
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
17
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
18
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
19
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
20
+ const logSyncFailure = description => {
21
+ try {
22
+ _TelemetryHelper.TelemetryHelper.logSDKEvent(_TelemetryConstants.LogLevel.ERROR, {
23
+ Event: _TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncFailed,
24
+ Description: description
25
+ });
26
+ } catch {
27
+ // A telemetry listener must not interrupt token recovery or teardown.
28
+ }
29
+ };
30
+ const logSyncInfo = (event, reason) => {
31
+ try {
32
+ _TelemetryHelper.TelemetryHelper.logSDKEvent(_TelemetryConstants.LogLevel.INFO, {
33
+ Event: event,
34
+ Description: reason
35
+ });
36
+ } catch {
37
+ // Telemetry must not interrupt credential synchronization.
38
+ }
39
+ };
40
+ const useChatTokenRenewal = (facade, state, dispatch, widgetCacheId) => {
41
+ var _previous$state$domai, _state$domainStates$l, _previous$state$domai2, _state$domainStates$l2, _previous$state$domai3, _state$domainStates$c, _previous$state$domai4, _state$domainStates$c2, _state$domainStates$c3, _state$domainStates$l3;
42
+ const current = (0, _react.useRef)({
43
+ facade,
44
+ state,
45
+ generation: 0,
46
+ lifecycle: 0
47
+ });
48
+ const pending = (0, _react.useRef)();
49
+ const reconcile = (0, _react.useRef)();
50
+ const supersededTokens = (0, _react.useRef)(new Set());
51
+ const previous = current.current;
52
+ let generation = previous.generation;
53
+ const lifecycleChanged = previous.facade !== facade || previous.state.appStates.conversationState !== state.appStates.conversationState || previous.state.appStates.conversationEndedBy !== state.appStates.conversationEndedBy;
54
+ if (lifecycleChanged || ((_previous$state$domai = previous.state.domainStates.liveChatContext) === null || _previous$state$domai === void 0 ? void 0 : _previous$state$domai.requestId) !== ((_state$domainStates$l = state.domainStates.liveChatContext) === null || _state$domainStates$l === void 0 ? void 0 : _state$domainStates$l.requestId) || ((_previous$state$domai2 = previous.state.domainStates.liveChatContext) === null || _previous$state$domai2 === void 0 ? void 0 : _previous$state$domai2.sessionId) !== ((_state$domainStates$l2 = state.domainStates.liveChatContext) === null || _state$domainStates$l2 === void 0 ? void 0 : _state$domainStates$l2.sessionId) || ((_previous$state$domai3 = previous.state.domainStates.chatToken) === null || _previous$state$domai3 === void 0 ? void 0 : _previous$state$domai3.requestId) !== ((_state$domainStates$c = state.domainStates.chatToken) === null || _state$domainStates$c === void 0 ? void 0 : _state$domainStates$c.requestId) || ((_previous$state$domai4 = previous.state.domainStates.chatToken) === null || _previous$state$domai4 === void 0 ? void 0 : _previous$state$domai4.chatId) !== ((_state$domainStates$c2 = state.domainStates.chatToken) === null || _state$domainStates$c2 === void 0 ? void 0 : _state$domainStates$c2.chatId)) {
55
+ generation++;
56
+ }
57
+ current.current = {
58
+ facade,
59
+ state,
60
+ generation,
61
+ lifecycle: previous.lifecycle + (lifecycleChanged ? 1 : 0)
62
+ };
63
+ (0, _react.useEffect)(() => {
64
+ if (!facade) {
65
+ return;
66
+ }
67
+ let disposed = false;
68
+ let revision = 0;
69
+ let unsubscribe;
70
+ let stateSubscription;
71
+ const refresh = async () => {
72
+ const renewal = ++revision;
73
+ const owner = current.current;
74
+ try {
75
+ var _savedContext$chatTok, _liveChatContext$chat, _liveChatContext$chat2;
76
+ const endedBy = owner.state.appStates.conversationEndedBy;
77
+ if (disposed || owner.facade !== facade || endedBy !== undefined && endedBy !== _Constants.ConversationEndEntity.NotSet) {
78
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "endedOrDisposed");
79
+ return;
80
+ }
81
+ const sdk = facade.getChatSDK();
82
+ const requestId = sdk.requestId;
83
+ const sessionId = sdk.sessionId;
84
+ if (owner.state.appStates.conversationState === _ConversationState.ConversationState.Loading) {
85
+ // A saved-state restore can replace post-start state with the old snapshot.
86
+ // Defer this notification until that same loading session becomes active.
87
+ if (pending.current) {
88
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededDeferredRenewal");
89
+ }
90
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncDeferred, "restoringSession");
91
+ pending.current = async () => {
92
+ // Let Active and the subsequent saved snapshot finish dispatching first.
93
+ await Promise.resolve();
94
+ try {
95
+ if (!disposed && renewal === revision && current.current.facade === facade && current.current.lifecycle === owner.lifecycle + 1 && facade.getChatSDK() === sdk && sdk.requestId === requestId && sdk.sessionId === sessionId) {
96
+ await refresh();
97
+ } else {
98
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "deferredSessionChanged");
99
+ }
100
+ } catch {
101
+ logSyncFailure("Unable to synchronize deferred renewed chat state");
102
+ }
103
+ };
104
+ return;
105
+ }
106
+ if (owner.state.appStates.conversationState !== _ConversationState.ConversationState.Active) {
107
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "inactiveSession");
108
+ return;
109
+ }
110
+ const savedContext = owner.state.domainStates.liveChatContext;
111
+ const savedToken = owner.state.domainStates.chatToken;
112
+ const previousToken = savedToken === null || savedToken === void 0 ? void 0 : savedToken.token;
113
+ const previousContextToken = savedContext === null || savedContext === void 0 || (_savedContext$chatTok = savedContext.chatToken) === null || _savedContext$chatTok === void 0 ? void 0 : _savedContext$chatTok.token;
114
+ const chatId = savedToken === null || savedToken === void 0 ? void 0 : savedToken.chatId;
115
+ if (!requestId || !chatId || savedToken.requestId && savedToken.requestId !== requestId || savedContext && (savedContext.requestId !== requestId || savedContext.sessionId && savedContext.sessionId !== sessionId)) {
116
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "savedSessionMismatch");
117
+ return;
118
+ }
119
+ const isCurrent = () => !disposed && renewal === revision && current.current.facade === facade && current.current.generation === owner.generation && facade.getChatSDK() === sdk && sdk.requestId === requestId && sdk.sessionId === sessionId;
120
+ if (!isCurrent()) {
121
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededOrSessionChanged");
122
+ return;
123
+ }
124
+ const _await$Promise$all = await Promise.all([facade.getCurrentLiveChatContext(), facade.getChatToken()]),
125
+ _await$Promise$all2 = _slicedToArray(_await$Promise$all, 2),
126
+ context = _await$Promise$all2[0],
127
+ chatToken = _await$Promise$all2[1];
128
+ if (!isCurrent()) {
129
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededOrSessionChanged");
130
+ return;
131
+ }
132
+ const liveChatContext = context;
133
+ if ((liveChatContext === null || liveChatContext === void 0 ? void 0 : liveChatContext.requestId) !== requestId || liveChatContext.sessionId && liveChatContext.sessionId !== sessionId || (chatToken === null || chatToken === void 0 ? void 0 : chatToken.chatId) !== chatId || ((_liveChatContext$chat = liveChatContext.chatToken) === null || _liveChatContext$chat === void 0 ? void 0 : _liveChatContext$chat.chatId) !== chatId || ((_liveChatContext$chat2 = liveChatContext.chatToken) === null || _liveChatContext$chat2 === void 0 ? void 0 : _liveChatContext$chat2.token) !== chatToken.token) {
134
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "renewedSessionMismatch");
135
+ return;
136
+ }
137
+ // The normal state publisher/cache writer owns persistence, scope and TTL.
138
+ // Persistent chat keeps using reconnectId instead of creating a live context.
139
+ // A late saved-state restore must not replace this same session's renewal.
140
+ if (previousToken) {
141
+ supersededTokens.current.add(previousToken);
142
+ }
143
+ if (previousContextToken) {
144
+ supersededTokens.current.add(previousContextToken);
145
+ }
146
+ reconcile.current = snapshot => {
147
+ var _snapshot$appStates, _snapshot$domainState, _snapshot$domainState2, _snapshot$domainState3, _latest$liveChatConte, _latest$chatToken;
148
+ if (!isCurrent()) {
149
+ return;
150
+ }
151
+ if (snapshot && (((_snapshot$appStates = snapshot.appStates) === null || _snapshot$appStates === void 0 ? void 0 : _snapshot$appStates.conversationState) !== _ConversationState.ConversationState.Active || snapshot.appStates.conversationEndedBy !== undefined && snapshot.appStates.conversationEndedBy !== _Constants.ConversationEndEntity.NotSet || ((_snapshot$domainState = snapshot.domainStates) === null || _snapshot$domainState === void 0 || (_snapshot$domainState = _snapshot$domainState.chatToken) === null || _snapshot$domainState === void 0 ? void 0 : _snapshot$domainState.chatId) !== chatId || snapshot.domainStates.chatToken.requestId && snapshot.domainStates.chatToken.requestId !== requestId || snapshot.domainStates.liveChatContext && (snapshot.domainStates.liveChatContext.requestId !== requestId || snapshot.domainStates.liveChatContext.sessionId && snapshot.domainStates.liveChatContext.sessionId !== sessionId))) {
152
+ return;
153
+ }
154
+ // Another window may publish a newer credential we have never replaced.
155
+ if (snapshot && (snapshot.domainStates.chatToken.token !== chatToken.token && !supersededTokens.current.has(snapshot.domainStates.chatToken.token) || snapshot.domainStates.liveChatContext && ((_snapshot$domainState2 = snapshot.domainStates.liveChatContext.chatToken) === null || _snapshot$domainState2 === void 0 ? void 0 : _snapshot$domainState2.token) !== chatToken.token && !supersededTokens.current.has((_snapshot$domainState3 = snapshot.domainStates.liveChatContext.chatToken) === null || _snapshot$domainState3 === void 0 ? void 0 : _snapshot$domainState3.token))) {
156
+ return;
157
+ }
158
+ const latest = (snapshot ?? current.current.state).domainStates;
159
+ if (savedContext && ((_latest$liveChatConte = latest.liveChatContext) === null || _latest$liveChatConte === void 0 || (_latest$liveChatConte = _latest$liveChatConte.chatToken) === null || _latest$liveChatConte === void 0 ? void 0 : _latest$liveChatConte.token) !== chatToken.token) {
160
+ dispatch({
161
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_LIVE_CHAT_CONTEXT,
162
+ payload: liveChatContext
163
+ });
164
+ }
165
+ if (((_latest$chatToken = latest.chatToken) === null || _latest$chatToken === void 0 ? void 0 : _latest$chatToken.token) !== chatToken.token) {
166
+ dispatch({
167
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_CHAT_TOKEN,
168
+ payload: chatToken
169
+ });
170
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSynced, "republished");
171
+ }
172
+ };
173
+ if (savedContext) {
174
+ dispatch({
175
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_LIVE_CHAT_CONTEXT,
176
+ payload: liveChatContext
177
+ });
178
+ }
179
+ dispatch({
180
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_CHAT_TOKEN,
181
+ payload: chatToken
182
+ });
183
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSynced, "dispatched");
184
+ } catch {
185
+ logSyncFailure("Unable to synchronize renewed chat state");
186
+ }
187
+ };
188
+ try {
189
+ var _sdk$onChatTokenRenew;
190
+ const sdk = facade.getChatSDK();
191
+ unsubscribe = (_sdk$onChatTokenRenew = sdk.onChatTokenRenewed) === null || _sdk$onChatTokenRenew === void 0 ? void 0 : _sdk$onChatTokenRenew.call(sdk, () => {
192
+ void refresh();
193
+ });
194
+ } catch {
195
+ logSyncFailure("Unable to subscribe to chat token renewal");
196
+ }
197
+ try {
198
+ // Delayed broadcast retries can overwrite storage after React state is current.
199
+ stateSubscription = _omnichannelChatComponents.BroadcastService.getMessageByEventName(widgetCacheId).subscribe(message => {
200
+ var _reconcile$current;
201
+ return (_reconcile$current = reconcile.current) === null || _reconcile$current === void 0 ? void 0 : _reconcile$current.call(reconcile, message.payload);
202
+ });
203
+ } catch {
204
+ logSyncFailure("Unable to subscribe to renewed chat state publication");
205
+ }
206
+ return () => {
207
+ disposed = true;
208
+ revision++;
209
+ if (pending.current) {
210
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "subscriptionDisposed");
211
+ }
212
+ pending.current = undefined;
213
+ reconcile.current = undefined;
214
+ supersededTokens.current.clear();
215
+ try {
216
+ var _unsubscribe;
217
+ (_unsubscribe = unsubscribe) === null || _unsubscribe === void 0 || _unsubscribe();
218
+ } catch {
219
+ logSyncFailure("Unable to unsubscribe from chat token renewal");
220
+ }
221
+ try {
222
+ var _stateSubscription;
223
+ (_stateSubscription = stateSubscription) === null || _stateSubscription === void 0 || _stateSubscription.unsubscribe();
224
+ } catch {
225
+ logSyncFailure("Unable to unsubscribe from renewed chat state publication");
226
+ }
227
+ };
228
+ }, [facade, dispatch, widgetCacheId]);
229
+ (0, _react.useEffect)(() => {
230
+ if (state.appStates.conversationState === _ConversationState.ConversationState.Active) {
231
+ const refresh = pending.current;
232
+ pending.current = undefined;
233
+ try {
234
+ var _reconcile$current2;
235
+ refresh === null || refresh === void 0 || refresh();
236
+ (_reconcile$current2 = reconcile.current) === null || _reconcile$current2 === void 0 || _reconcile$current2.call(reconcile);
237
+ } catch {
238
+ logSyncFailure("Unable to synchronize renewed chat state");
239
+ }
240
+ } else {
241
+ reconcile.current = undefined;
242
+ supersededTokens.current.clear();
243
+ if (state.appStates.conversationState !== _ConversationState.ConversationState.Loading) {
244
+ if (pending.current) {
245
+ logSyncInfo(_TelemetryConstants.TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "inactiveSession");
246
+ }
247
+ pending.current = undefined;
248
+ }
249
+ }
250
+ }, [facade, state.appStates.conversationState, (_state$domainStates$c3 = state.domainStates.chatToken) === null || _state$domainStates$c3 === void 0 ? void 0 : _state$domainStates$c3.token, (_state$domainStates$l3 = state.domainStates.liveChatContext) === null || _state$domainStates$l3 === void 0 || (_state$domainStates$l3 = _state$domainStates$l3.chatToken) === null || _state$domainStates$l3 === void 0 ? void 0 : _state$domainStates$l3.token]);
251
+ };
252
+ exports.useChatTokenRenewal = useChatTokenRenewal;
@@ -163,20 +163,6 @@ const LiveChatWidgetStateful = props => {
163
163
 
164
164
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
165
165
  const startChat = async (props, localState) => {
166
- const isReconnectTriggered = async () => {
167
- if ((0, _reconnectChatHelper.isReconnectEnabled)(props.chatConfig) === true && !(0, _reconnectChatHelper.isPersistentEnabled)(props.chatConfig)) {
168
- const noValidReconnectId = await (0, _reconnectChatHelper.handleChatReconnect)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
169
- const inMemoryState = (0, _createReducer.executeReducer)(state, {
170
- type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
171
- payload: null
172
- });
173
- // If chat reconnect has kicked in chat state will become Active or Reconnect. So just exit, else go next
174
- if (!noValidReconnectId && (inMemoryState.appStates.conversationState === _ConversationState.ConversationState.Active || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.ReconnectChat)) {
175
- return true;
176
- }
177
- }
178
- return false;
179
- };
180
166
  let isChatValid = false;
181
167
  //Start a chat from cache/reconnectid
182
168
  if (activeCachedChatExist === true) {
@@ -188,7 +174,7 @@ const LiveChatWidgetStateful = props => {
188
174
  //Check if conversation state is not in wrapup or closed state
189
175
  isChatValid = await (0, _startChat.checkIfConversationStillValid)(facadeChatSDK, dispatch, state);
190
176
  if (isChatValid === true) {
191
- const reconnectTriggered = await isReconnectTriggered();
177
+ const reconnectTriggered = await (0, _reconnectChatHelper.isReconnectTriggered)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
192
178
  if (!reconnectTriggered) {
193
179
  await (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
194
180
  }
@@ -204,7 +190,7 @@ const LiveChatWidgetStateful = props => {
204
190
  if (isChatValid === false) {
205
191
  if (localState) {
206
192
  // adding the reconnect logic for the case when customer tries to reconnect from a new browser or InPrivate browser
207
- const reconnectTriggered = await isReconnectTriggered();
193
+ const reconnectTriggered = await (0, _reconnectChatHelper.isReconnectTriggered)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
208
194
  if (!reconnectTriggered) {
209
195
  const inMemoryState = (0, _createReducer.executeReducer)(state, {
210
196
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
@@ -1000,7 +986,9 @@ const LiveChatWidgetStateful = props => {
1000
986
  const endChatRelay = (adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab) => (0, _endChat.endChat)(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab);
1001
987
  const prepareStartChatRelay = () => (0, _startChat.prepareStartChat)(props, facadeChatSDK, state, dispatch, setAdapter);
1002
988
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1003
- const initStartChatRelay = (optionalParams, persistedState) => (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
989
+ const initStartChatRelay = async (optionalParams, persistedState) => {
990
+ await (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
991
+ };
1004
992
  const confirmationPaneProps = (0, _initConfirmationPropsComposer.initConfirmationPropsComposer)(props);
1005
993
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1006
994
  const prepareEndChatRelay = () => (0, _endChat.prepareEndChat)(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter);
@@ -112,6 +112,11 @@ export let TelemetryEvent = /*#__PURE__*/function (TelemetryEvent) {
112
112
  TelemetryEvent["RecoveryEligibilityEvaluated"] = "RecoveryEligibilityEvaluated";
113
113
  TelemetryEvent["GetConversationDetailsCallStarted"] = "GetConversationDetailsCallStarted";
114
114
  TelemetryEvent["GetConversationDetailsCallFailed"] = "GetConversationDetailsCallFailed";
115
+ TelemetryEvent["UpdateTelemetryDataFailed"] = "UpdateTelemetryDataFailed";
116
+ TelemetryEvent["ChatTokenRenewalStateSyncFailed"] = "ChatTokenRenewalStateSyncFailed";
117
+ TelemetryEvent["ChatTokenRenewalStateSynced"] = "ChatTokenRenewalStateSynced";
118
+ TelemetryEvent["ChatTokenRenewalStateSyncSkipped"] = "ChatTokenRenewalStateSyncSkipped";
119
+ TelemetryEvent["ChatTokenRenewalStateSyncDeferred"] = "ChatTokenRenewalStateSyncDeferred";
115
120
  TelemetryEvent["EndChatSDKCallFailed"] = "EndChatSDKCallFailed";
116
121
  TelemetryEvent["DisconnectEndChatSDKCallFailed"] = "DisconnectEndChatSDKCallFailed";
117
122
  TelemetryEvent["GetChatReconnectContextSDKCallStarted"] = "GetChatReconnectContextSDKCallStarted";
@@ -428,6 +433,11 @@ export let TelemetryConstants = /*#__PURE__*/function () {
428
433
  case TelemetryEvent.OnNewMessageFailed:
429
434
  case TelemetryEvent.OnNewMessageAudioNotificationFailed:
430
435
  case TelemetryEvent.GetConversationDetailsCallFailed:
436
+ case TelemetryEvent.UpdateTelemetryDataFailed:
437
+ case TelemetryEvent.ChatTokenRenewalStateSyncFailed:
438
+ case TelemetryEvent.ChatTokenRenewalStateSynced:
439
+ case TelemetryEvent.ChatTokenRenewalStateSyncSkipped:
440
+ case TelemetryEvent.ChatTokenRenewalStateSyncDeferred:
431
441
  case TelemetryEvent.EndChatSDKCall:
432
442
  case TelemetryEvent.EndChatEventReceived:
433
443
  case TelemetryEvent.EndChatSDKCallFailed:
@@ -14,10 +14,11 @@ import LiveChatWidgetStateful from "./livechatwidgetstateful/LiveChatWidgetState
14
14
  import { createReducer } from "../../contexts/createReducer";
15
15
  import { getLiveChatWidgetContextInitialState } from "../../contexts/common/LiveChatWidgetContextInitialState";
16
16
  import { getMockChatSDKIfApplicable } from "./common/getMockChatSDKIfApplicable";
17
- import { isNullOrUndefined } from "../../common/utils";
17
+ import { getWidgetCacheIdfromProps, isNullOrUndefined } from "../../common/utils";
18
18
  import { isPersistentChatEnabled } from "./common/liveChatConfigUtils";
19
19
  import overridePropsOnMockIfApplicable from "./common/overridePropsOnMockIfApplicable";
20
20
  import { registerTelemetryLoggers } from "./common/registerTelemetryLoggers";
21
+ import { useChatTokenRenewal } from "./common/useChatTokenRenewal";
21
22
  export const LiveChatWidget = props => {
22
23
  var _props$featureConfigP, _props$chatConfig, _props$chatConfig2;
23
24
  const reducer = createReducer();
@@ -65,6 +66,7 @@ export const LiveChatWidget = props => {
65
66
  useEffect(() => {
66
67
  registerTelemetryLoggers(props, dispatch);
67
68
  }, [dispatch]);
69
+ useChatTokenRenewal(facadeChatSDK, state, dispatch, getWidgetCacheIdfromProps(props));
68
70
  return /*#__PURE__*/React.createElement(FacadeChatSDKStore.Provider, {
69
71
  value: [facadeChatSDK, setFacadeChatSDK]
70
72
  }, /*#__PURE__*/React.createElement(ChatSDKStore.Provider, {
@@ -7,6 +7,7 @@ import { BroadcastService } from "@microsoft/omnichannel-chat-components";
7
7
  import { ConversationState } from "../../../contexts/common/ConversationState";
8
8
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
9
9
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
10
+ import { executeReducer } from "../../../contexts/createReducer";
10
11
  import { handleStartChatError } from "./startChatErrorHandler";
11
12
 
12
13
  // Return value: should start normal chat flow when reconnect is enabled
@@ -50,6 +51,32 @@ const handleChatReconnect = async (facadeChatSDK, props, dispatch, setAdapter, i
50
51
  return true;
51
52
  };
52
53
 
54
+ /**
55
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
56
+ * In that case the caller must not start another chat.
57
+ */
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ const isReconnectTriggered = async (facadeChatSDK, props, dispatch, setAdapter, initStartChat, state) => {
60
+ if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
61
+ let reconnectChatStarted = false;
62
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
63
+ const initStartChatAndTrack = async function () {
64
+ reconnectChatStarted = await initStartChat(...arguments);
65
+ };
66
+ const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChatAndTrack, state);
67
+ // initStartChat resolves before React renders Active, so the in-memory state can still read Loading here.
68
+ // Its result tells whether reconnect started the chat; the in-memory state covers the reconnect pane.
69
+ const inMemoryState = executeReducer(state, {
70
+ type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
71
+ payload: null
72
+ });
73
+ if (!noValidReconnectId && (reconnectChatStarted || inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ };
79
+
53
80
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
81
  const getChatReconnectContext = async (facadeChatSDK, chatConfig, props, isAuthenticatedChat, dispatch) => {
55
82
  try {
@@ -143,4 +170,4 @@ const isPersistentEnabled = chatConfig => {
143
170
  const hasReconnectId = reconnectAvailabilityResponse => {
144
171
  return reconnectAvailabilityResponse && !isNullOrUndefined(reconnectAvailabilityResponse.reconnectId);
145
172
  };
146
- export { handleChatReconnect, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
173
+ export { handleChatReconnect, isReconnectTriggered, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
@@ -62,7 +62,7 @@ const getGuard = (guards, facadeChatSDK) => {
62
62
  * Runs `operation` only if no other invocation for the same widget instance is already in
63
63
  * flight. Concurrent invocations are dropped (and reported through telemetry) rather than
64
64
  * awaiting the in-flight promise, so a future re-entrant call can never deadlock on itself.
65
- * No caller acts on the resolved value, so dropping is safe.
65
+ * A dropped invocation resolves to `undefined`.
66
66
  *
67
67
  * `blockedBy` lets an operation also yield to a different, already running operation for the
68
68
  * same widget instance without claiming that operation's lock.
@@ -78,14 +78,14 @@ const runExclusively = async (guards, facadeChatSDK, description, operation, pro
78
78
  WidgetCacheId: props ? getWidgetCacheIdfromProps(props) : undefined
79
79
  }
80
80
  });
81
- return;
81
+ return undefined;
82
82
  }
83
83
 
84
84
  // Claim the lock before invoking the operation, so a re-entrant call made from the
85
85
  // operation's synchronous preamble (before its first await) cannot slip past the check above.
86
86
  guard.inFlight = true;
87
87
  try {
88
- await operation();
88
+ return await operation();
89
89
  } finally {
90
90
  guard.inFlight = false;
91
91
  }
@@ -221,9 +221,14 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
221
221
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
222
222
  };
223
223
 
224
+ /**
225
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
226
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
227
+ */
224
228
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
225
229
  const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
226
- return runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
230
+ const chatStarted = await runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
231
+ return chatStarted === true;
227
232
  };
228
233
 
229
234
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -337,7 +342,7 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
337
342
  logWidgetLoadComplete(WidgetLoadTelemetryMessage.PersistedStateRetrievedMessage);
338
343
  // Set post chat context in state, load in background to do not block the load
339
344
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch, true);
340
- return;
345
+ return true;
341
346
  }
342
347
 
343
348
  // Persistent Chat relies on the `reconnectId` retrieved from reconnectablechats API to reconnect upon start chat and not `liveChatContext`
@@ -353,10 +358,13 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
353
358
  logWidgetLoadComplete();
354
359
  // Set post chat context in state, load in background to do not block the load
355
360
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch);
356
- // Updating chat session detail for telemetry
357
- await updateTelemetryData(facadeChatSDK, dispatch);
361
+ // Updating chat session detail for telemetry, in background: getConversationDetails retries until the
362
+ // live work item exists (several seconds), and awaiting it would hold the start chat locks and drop the next start chat
363
+ updateTelemetryData(facadeChatSDK, dispatch);
364
+ return true;
358
365
  } catch (ex) {
359
366
  handleStartChatError(dispatch, facadeChatSDK, props, ex, isStartChatSuccessful);
367
+ return false;
360
368
  }
361
369
  };
362
370
 
@@ -1,4 +1,4 @@
1
- import { BroadcastEvent } from "../../../common/telemetry/TelemetryConstants";
1
+ import { BroadcastEvent, LogLevel, TelemetryEvent } from "../../../common/telemetry/TelemetryConstants";
2
2
  import { BroadcastService } from "@microsoft/omnichannel-chat-components";
3
3
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
4
4
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
@@ -7,15 +7,41 @@ import { getConversationDetailsCall } from "../../../common/utils";
7
7
 
8
8
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
9
  export const updateTelemetryData = async (facadeChatSDK, dispatch) => {
10
- // load it concurrently, this will reduce the load time
11
- await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch), updateConversationDataForTelemetry(facadeChatSDK, dispatch)]);
10
+ var _facadeChatSDK$getCha;
11
+ // startChat no longer waits for this, so the next chat can start (chatSDKStateCleanUp assigns a new requestId)
12
+ // before these calls resolve. Results for an earlier chat must not overwrite the current chat's data.
13
+ // endChat also assigns a new requestId, so the chat that just ended still applies its own results.
14
+ const requestId = facadeChatSDK === null || facadeChatSDK === void 0 || (_facadeChatSDK$getCha = facadeChatSDK.getChatSDK()) === null || _facadeChatSDK$getCha === void 0 ? void 0 : _facadeChatSDK$getCha.requestId;
15
+ try {
16
+ // load it concurrently, this will reduce the load time
17
+ await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch, requestId), updateConversationDataForTelemetry(facadeChatSDK, dispatch, requestId)]);
18
+ } catch (error) {
19
+ TelemetryHelper.logSDKEvent(LogLevel.ERROR, {
20
+ Event: TelemetryEvent.UpdateTelemetryDataFailed,
21
+ ExceptionDetails: {
22
+ exception: `Update telemetry data failed: ${error}`
23
+ }
24
+ });
25
+ }
26
+ };
27
+
28
+ // The requestId alone isn't enough: endChat also replaces it. Only the next chat's startChat gets a new chat token
29
+ // (endChat and chatSDKStateCleanUp clear it), so drop the result only when the SDK holds that next chat.
30
+ const isFromEarlierChat = (facadeChatSDK, requestId) => {
31
+ var _chatSDK$chatToken;
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const chatSDK = facadeChatSDK.getChatSDK();
34
+ return (chatSDK === null || chatSDK === void 0 ? void 0 : chatSDK.requestId) !== requestId && !!(chatSDK !== null && chatSDK !== void 0 && (_chatSDK$chatToken = chatSDK.chatToken) !== null && _chatSDK$chatToken !== void 0 && _chatSDK$chatToken.chatId);
12
35
  };
13
36
 
14
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
- const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
38
+ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
16
39
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
17
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
41
  const chatSession = await facadeChatSDK.getCurrentLiveChatContext();
42
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
43
+ return;
44
+ }
19
45
  const telemetryData = TelemetryHelper.addSessionDataToTelemetry(chatSession, TelemetryManager.InternalTelemetryData);
20
46
  dispatch({
21
47
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -31,10 +57,13 @@ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
31
57
  };
32
58
 
33
59
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
- const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch) => {
60
+ const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
35
61
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
36
62
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
63
  const liveWorkItem = await getConversationDetailsCall(facadeChatSDK);
64
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
65
+ return;
66
+ }
38
67
  const telemetryData = TelemetryHelper.addConversationDataToTelemetry(liveWorkItem, TelemetryManager.InternalTelemetryData);
39
68
  dispatch({
40
69
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -0,0 +1,245 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ import { useEffect, useRef } from "react";
8
+ import { BroadcastService } from "@microsoft/omnichannel-chat-components";
9
+ import { LogLevel, TelemetryEvent } from "../../../common/telemetry/TelemetryConstants";
10
+ import { ConversationEndEntity } from "../../../common/Constants";
11
+ import { ConversationState } from "../../../contexts/common/ConversationState";
12
+ import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
13
+ import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
14
+ const logSyncFailure = description => {
15
+ try {
16
+ TelemetryHelper.logSDKEvent(LogLevel.ERROR, {
17
+ Event: TelemetryEvent.ChatTokenRenewalStateSyncFailed,
18
+ Description: description
19
+ });
20
+ } catch {
21
+ // A telemetry listener must not interrupt token recovery or teardown.
22
+ }
23
+ };
24
+ const logSyncInfo = (event, reason) => {
25
+ try {
26
+ TelemetryHelper.logSDKEvent(LogLevel.INFO, {
27
+ Event: event,
28
+ Description: reason
29
+ });
30
+ } catch {
31
+ // Telemetry must not interrupt credential synchronization.
32
+ }
33
+ };
34
+ export const useChatTokenRenewal = (facade, state, dispatch, widgetCacheId) => {
35
+ var _previous$state$domai, _state$domainStates$l, _previous$state$domai2, _state$domainStates$l2, _previous$state$domai3, _state$domainStates$c, _previous$state$domai4, _state$domainStates$c2, _state$domainStates$c3, _state$domainStates$l3;
36
+ const current = useRef({
37
+ facade,
38
+ state,
39
+ generation: 0,
40
+ lifecycle: 0
41
+ });
42
+ const pending = useRef();
43
+ const reconcile = useRef();
44
+ const supersededTokens = useRef(new Set());
45
+ const previous = current.current;
46
+ let generation = previous.generation;
47
+ const lifecycleChanged = previous.facade !== facade || previous.state.appStates.conversationState !== state.appStates.conversationState || previous.state.appStates.conversationEndedBy !== state.appStates.conversationEndedBy;
48
+ if (lifecycleChanged || ((_previous$state$domai = previous.state.domainStates.liveChatContext) === null || _previous$state$domai === void 0 ? void 0 : _previous$state$domai.requestId) !== ((_state$domainStates$l = state.domainStates.liveChatContext) === null || _state$domainStates$l === void 0 ? void 0 : _state$domainStates$l.requestId) || ((_previous$state$domai2 = previous.state.domainStates.liveChatContext) === null || _previous$state$domai2 === void 0 ? void 0 : _previous$state$domai2.sessionId) !== ((_state$domainStates$l2 = state.domainStates.liveChatContext) === null || _state$domainStates$l2 === void 0 ? void 0 : _state$domainStates$l2.sessionId) || ((_previous$state$domai3 = previous.state.domainStates.chatToken) === null || _previous$state$domai3 === void 0 ? void 0 : _previous$state$domai3.requestId) !== ((_state$domainStates$c = state.domainStates.chatToken) === null || _state$domainStates$c === void 0 ? void 0 : _state$domainStates$c.requestId) || ((_previous$state$domai4 = previous.state.domainStates.chatToken) === null || _previous$state$domai4 === void 0 ? void 0 : _previous$state$domai4.chatId) !== ((_state$domainStates$c2 = state.domainStates.chatToken) === null || _state$domainStates$c2 === void 0 ? void 0 : _state$domainStates$c2.chatId)) {
49
+ generation++;
50
+ }
51
+ current.current = {
52
+ facade,
53
+ state,
54
+ generation,
55
+ lifecycle: previous.lifecycle + (lifecycleChanged ? 1 : 0)
56
+ };
57
+ useEffect(() => {
58
+ if (!facade) {
59
+ return;
60
+ }
61
+ let disposed = false;
62
+ let revision = 0;
63
+ let unsubscribe;
64
+ let stateSubscription;
65
+ const refresh = async () => {
66
+ const renewal = ++revision;
67
+ const owner = current.current;
68
+ try {
69
+ var _savedContext$chatTok, _liveChatContext$chat, _liveChatContext$chat2;
70
+ const endedBy = owner.state.appStates.conversationEndedBy;
71
+ if (disposed || owner.facade !== facade || endedBy !== undefined && endedBy !== ConversationEndEntity.NotSet) {
72
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "endedOrDisposed");
73
+ return;
74
+ }
75
+ const sdk = facade.getChatSDK();
76
+ const requestId = sdk.requestId;
77
+ const sessionId = sdk.sessionId;
78
+ if (owner.state.appStates.conversationState === ConversationState.Loading) {
79
+ // A saved-state restore can replace post-start state with the old snapshot.
80
+ // Defer this notification until that same loading session becomes active.
81
+ if (pending.current) {
82
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededDeferredRenewal");
83
+ }
84
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncDeferred, "restoringSession");
85
+ pending.current = async () => {
86
+ // Let Active and the subsequent saved snapshot finish dispatching first.
87
+ await Promise.resolve();
88
+ try {
89
+ if (!disposed && renewal === revision && current.current.facade === facade && current.current.lifecycle === owner.lifecycle + 1 && facade.getChatSDK() === sdk && sdk.requestId === requestId && sdk.sessionId === sessionId) {
90
+ await refresh();
91
+ } else {
92
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "deferredSessionChanged");
93
+ }
94
+ } catch {
95
+ logSyncFailure("Unable to synchronize deferred renewed chat state");
96
+ }
97
+ };
98
+ return;
99
+ }
100
+ if (owner.state.appStates.conversationState !== ConversationState.Active) {
101
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "inactiveSession");
102
+ return;
103
+ }
104
+ const savedContext = owner.state.domainStates.liveChatContext;
105
+ const savedToken = owner.state.domainStates.chatToken;
106
+ const previousToken = savedToken === null || savedToken === void 0 ? void 0 : savedToken.token;
107
+ const previousContextToken = savedContext === null || savedContext === void 0 || (_savedContext$chatTok = savedContext.chatToken) === null || _savedContext$chatTok === void 0 ? void 0 : _savedContext$chatTok.token;
108
+ const chatId = savedToken === null || savedToken === void 0 ? void 0 : savedToken.chatId;
109
+ if (!requestId || !chatId || savedToken.requestId && savedToken.requestId !== requestId || savedContext && (savedContext.requestId !== requestId || savedContext.sessionId && savedContext.sessionId !== sessionId)) {
110
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "savedSessionMismatch");
111
+ return;
112
+ }
113
+ const isCurrent = () => !disposed && renewal === revision && current.current.facade === facade && current.current.generation === owner.generation && facade.getChatSDK() === sdk && sdk.requestId === requestId && sdk.sessionId === sessionId;
114
+ if (!isCurrent()) {
115
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededOrSessionChanged");
116
+ return;
117
+ }
118
+ const _await$Promise$all = await Promise.all([facade.getCurrentLiveChatContext(), facade.getChatToken()]),
119
+ _await$Promise$all2 = _slicedToArray(_await$Promise$all, 2),
120
+ context = _await$Promise$all2[0],
121
+ chatToken = _await$Promise$all2[1];
122
+ if (!isCurrent()) {
123
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "supersededOrSessionChanged");
124
+ return;
125
+ }
126
+ const liveChatContext = context;
127
+ if ((liveChatContext === null || liveChatContext === void 0 ? void 0 : liveChatContext.requestId) !== requestId || liveChatContext.sessionId && liveChatContext.sessionId !== sessionId || (chatToken === null || chatToken === void 0 ? void 0 : chatToken.chatId) !== chatId || ((_liveChatContext$chat = liveChatContext.chatToken) === null || _liveChatContext$chat === void 0 ? void 0 : _liveChatContext$chat.chatId) !== chatId || ((_liveChatContext$chat2 = liveChatContext.chatToken) === null || _liveChatContext$chat2 === void 0 ? void 0 : _liveChatContext$chat2.token) !== chatToken.token) {
128
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "renewedSessionMismatch");
129
+ return;
130
+ }
131
+ // The normal state publisher/cache writer owns persistence, scope and TTL.
132
+ // Persistent chat keeps using reconnectId instead of creating a live context.
133
+ // A late saved-state restore must not replace this same session's renewal.
134
+ if (previousToken) {
135
+ supersededTokens.current.add(previousToken);
136
+ }
137
+ if (previousContextToken) {
138
+ supersededTokens.current.add(previousContextToken);
139
+ }
140
+ reconcile.current = snapshot => {
141
+ var _snapshot$appStates, _snapshot$domainState, _snapshot$domainState2, _snapshot$domainState3, _latest$liveChatConte, _latest$chatToken;
142
+ if (!isCurrent()) {
143
+ return;
144
+ }
145
+ if (snapshot && (((_snapshot$appStates = snapshot.appStates) === null || _snapshot$appStates === void 0 ? void 0 : _snapshot$appStates.conversationState) !== ConversationState.Active || snapshot.appStates.conversationEndedBy !== undefined && snapshot.appStates.conversationEndedBy !== ConversationEndEntity.NotSet || ((_snapshot$domainState = snapshot.domainStates) === null || _snapshot$domainState === void 0 || (_snapshot$domainState = _snapshot$domainState.chatToken) === null || _snapshot$domainState === void 0 ? void 0 : _snapshot$domainState.chatId) !== chatId || snapshot.domainStates.chatToken.requestId && snapshot.domainStates.chatToken.requestId !== requestId || snapshot.domainStates.liveChatContext && (snapshot.domainStates.liveChatContext.requestId !== requestId || snapshot.domainStates.liveChatContext.sessionId && snapshot.domainStates.liveChatContext.sessionId !== sessionId))) {
146
+ return;
147
+ }
148
+ // Another window may publish a newer credential we have never replaced.
149
+ if (snapshot && (snapshot.domainStates.chatToken.token !== chatToken.token && !supersededTokens.current.has(snapshot.domainStates.chatToken.token) || snapshot.domainStates.liveChatContext && ((_snapshot$domainState2 = snapshot.domainStates.liveChatContext.chatToken) === null || _snapshot$domainState2 === void 0 ? void 0 : _snapshot$domainState2.token) !== chatToken.token && !supersededTokens.current.has((_snapshot$domainState3 = snapshot.domainStates.liveChatContext.chatToken) === null || _snapshot$domainState3 === void 0 ? void 0 : _snapshot$domainState3.token))) {
150
+ return;
151
+ }
152
+ const latest = (snapshot ?? current.current.state).domainStates;
153
+ if (savedContext && ((_latest$liveChatConte = latest.liveChatContext) === null || _latest$liveChatConte === void 0 || (_latest$liveChatConte = _latest$liveChatConte.chatToken) === null || _latest$liveChatConte === void 0 ? void 0 : _latest$liveChatConte.token) !== chatToken.token) {
154
+ dispatch({
155
+ type: LiveChatWidgetActionType.SET_LIVE_CHAT_CONTEXT,
156
+ payload: liveChatContext
157
+ });
158
+ }
159
+ if (((_latest$chatToken = latest.chatToken) === null || _latest$chatToken === void 0 ? void 0 : _latest$chatToken.token) !== chatToken.token) {
160
+ dispatch({
161
+ type: LiveChatWidgetActionType.SET_CHAT_TOKEN,
162
+ payload: chatToken
163
+ });
164
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSynced, "republished");
165
+ }
166
+ };
167
+ if (savedContext) {
168
+ dispatch({
169
+ type: LiveChatWidgetActionType.SET_LIVE_CHAT_CONTEXT,
170
+ payload: liveChatContext
171
+ });
172
+ }
173
+ dispatch({
174
+ type: LiveChatWidgetActionType.SET_CHAT_TOKEN,
175
+ payload: chatToken
176
+ });
177
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSynced, "dispatched");
178
+ } catch {
179
+ logSyncFailure("Unable to synchronize renewed chat state");
180
+ }
181
+ };
182
+ try {
183
+ var _sdk$onChatTokenRenew;
184
+ const sdk = facade.getChatSDK();
185
+ unsubscribe = (_sdk$onChatTokenRenew = sdk.onChatTokenRenewed) === null || _sdk$onChatTokenRenew === void 0 ? void 0 : _sdk$onChatTokenRenew.call(sdk, () => {
186
+ void refresh();
187
+ });
188
+ } catch {
189
+ logSyncFailure("Unable to subscribe to chat token renewal");
190
+ }
191
+ try {
192
+ // Delayed broadcast retries can overwrite storage after React state is current.
193
+ stateSubscription = BroadcastService.getMessageByEventName(widgetCacheId).subscribe(message => {
194
+ var _reconcile$current;
195
+ return (_reconcile$current = reconcile.current) === null || _reconcile$current === void 0 ? void 0 : _reconcile$current.call(reconcile, message.payload);
196
+ });
197
+ } catch {
198
+ logSyncFailure("Unable to subscribe to renewed chat state publication");
199
+ }
200
+ return () => {
201
+ disposed = true;
202
+ revision++;
203
+ if (pending.current) {
204
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "subscriptionDisposed");
205
+ }
206
+ pending.current = undefined;
207
+ reconcile.current = undefined;
208
+ supersededTokens.current.clear();
209
+ try {
210
+ var _unsubscribe;
211
+ (_unsubscribe = unsubscribe) === null || _unsubscribe === void 0 || _unsubscribe();
212
+ } catch {
213
+ logSyncFailure("Unable to unsubscribe from chat token renewal");
214
+ }
215
+ try {
216
+ var _stateSubscription;
217
+ (_stateSubscription = stateSubscription) === null || _stateSubscription === void 0 || _stateSubscription.unsubscribe();
218
+ } catch {
219
+ logSyncFailure("Unable to unsubscribe from renewed chat state publication");
220
+ }
221
+ };
222
+ }, [facade, dispatch, widgetCacheId]);
223
+ useEffect(() => {
224
+ if (state.appStates.conversationState === ConversationState.Active) {
225
+ const refresh = pending.current;
226
+ pending.current = undefined;
227
+ try {
228
+ var _reconcile$current2;
229
+ refresh === null || refresh === void 0 || refresh();
230
+ (_reconcile$current2 = reconcile.current) === null || _reconcile$current2 === void 0 || _reconcile$current2.call(reconcile);
231
+ } catch {
232
+ logSyncFailure("Unable to synchronize renewed chat state");
233
+ }
234
+ } else {
235
+ reconcile.current = undefined;
236
+ supersededTokens.current.clear();
237
+ if (state.appStates.conversationState !== ConversationState.Loading) {
238
+ if (pending.current) {
239
+ logSyncInfo(TelemetryEvent.ChatTokenRenewalStateSyncSkipped, "inactiveSession");
240
+ }
241
+ pending.current = undefined;
242
+ }
243
+ }
244
+ }, [facade, state.appStates.conversationState, (_state$domainStates$c3 = state.domainStates.chatToken) === null || _state$domainStates$c3 === void 0 ? void 0 : _state$domainStates$c3.token, (_state$domainStates$l3 = state.domainStates.liveChatContext) === null || _state$domainStates$l3 === void 0 || (_state$domainStates$l3 = _state$domainStates$l3.chatToken) === null || _state$domainStates$l3 === void 0 ? void 0 : _state$domainStates$l3.token]);
245
+ };
@@ -17,7 +17,7 @@ import { checkIfConversationStillValid, initStartChat, prepareStartChat, setPreC
17
17
  import { createTimer, getBroadcastChannelName, getConversationDetailsCall, getLocaleDirection, getStateFromCache, getWidgetCacheIdfromProps, getWidgetEndChatEventName, isNullOrEmptyString, isNullOrUndefined, isThisSessionPopout, isUndefinedOrEmpty, setAriaHiddenForSiblings, setOcUserAgent } from "../../../common/utils";
18
18
  import { customEventCallback, subscribeToSendCustomEvent } from "../common/customEventHandler";
19
19
  import { defaultClientDataStoreProvider, isCookieAllowed } from "../../../common/storage/default/defaultClientDataStoreProvider";
20
- import { handleChatReconnect, isPersistentEnabled, isReconnectEnabled } from "../common/reconnectChatHelper";
20
+ import { isPersistentEnabled, isReconnectTriggered } from "../common/reconnectChatHelper";
21
21
  import { shouldShowCallingContainer, shouldShowChatButton, shouldShowConfirmationPane, shouldShowEmailTranscriptPane, shouldShowHeader, shouldShowLoadingPane, shouldShowOutOfOfficeHoursPane, shouldShowPostChatLoadingPane, shouldShowPostChatSurveyPane, shouldShowPreChatSurveyPane, shouldShowProactiveChatPane, shouldShowReconnectChatPane, shouldShowStartChatErrorPane, shouldShowWebChatContainer } from "../../../controller/componentController";
22
22
  import { ActivityStreamHandler } from "../common/ActivityStreamHandler";
23
23
  import CallingContainerStateful from "../../callingcontainerstateful/CallingContainerStateful";
@@ -156,20 +156,6 @@ export const LiveChatWidgetStateful = props => {
156
156
 
157
157
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
158
  const startChat = async (props, localState) => {
159
- const isReconnectTriggered = async () => {
160
- if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
161
- const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
162
- const inMemoryState = executeReducer(state, {
163
- type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
164
- payload: null
165
- });
166
- // If chat reconnect has kicked in chat state will become Active or Reconnect. So just exit, else go next
167
- if (!noValidReconnectId && (inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
168
- return true;
169
- }
170
- }
171
- return false;
172
- };
173
159
  let isChatValid = false;
174
160
  //Start a chat from cache/reconnectid
175
161
  if (activeCachedChatExist === true) {
@@ -181,7 +167,7 @@ export const LiveChatWidgetStateful = props => {
181
167
  //Check if conversation state is not in wrapup or closed state
182
168
  isChatValid = await checkIfConversationStillValid(facadeChatSDK, dispatch, state);
183
169
  if (isChatValid === true) {
184
- const reconnectTriggered = await isReconnectTriggered();
170
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
185
171
  if (!reconnectTriggered) {
186
172
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
187
173
  }
@@ -197,7 +183,7 @@ export const LiveChatWidgetStateful = props => {
197
183
  if (isChatValid === false) {
198
184
  if (localState) {
199
185
  // adding the reconnect logic for the case when customer tries to reconnect from a new browser or InPrivate browser
200
- const reconnectTriggered = await isReconnectTriggered();
186
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
201
187
  if (!reconnectTriggered) {
202
188
  const inMemoryState = executeReducer(state, {
203
189
  type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
@@ -993,7 +979,9 @@ export const LiveChatWidgetStateful = props => {
993
979
  const endChatRelay = (adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab) => endChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab);
994
980
  const prepareStartChatRelay = () => prepareStartChat(props, facadeChatSDK, state, dispatch, setAdapter);
995
981
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
996
- const initStartChatRelay = (optionalParams, persistedState) => initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
982
+ const initStartChatRelay = async (optionalParams, persistedState) => {
983
+ await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
984
+ };
997
985
  const confirmationPaneProps = initConfirmationPropsComposer(props);
998
986
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
999
987
  const prepareEndChatRelay = () => prepareEndChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter);
@@ -98,6 +98,11 @@ export declare enum TelemetryEvent {
98
98
  RecoveryEligibilityEvaluated = "RecoveryEligibilityEvaluated",
99
99
  GetConversationDetailsCallStarted = "GetConversationDetailsCallStarted",
100
100
  GetConversationDetailsCallFailed = "GetConversationDetailsCallFailed",
101
+ UpdateTelemetryDataFailed = "UpdateTelemetryDataFailed",
102
+ ChatTokenRenewalStateSyncFailed = "ChatTokenRenewalStateSyncFailed",
103
+ ChatTokenRenewalStateSynced = "ChatTokenRenewalStateSynced",
104
+ ChatTokenRenewalStateSyncSkipped = "ChatTokenRenewalStateSyncSkipped",
105
+ ChatTokenRenewalStateSyncDeferred = "ChatTokenRenewalStateSyncDeferred",
101
106
  EndChatSDKCallFailed = "EndChatSDKCallFailed",
102
107
  DisconnectEndChatSDKCallFailed = "DisconnectEndChatSDKCallFailed",
103
108
  GetChatReconnectContextSDKCallStarted = "GetChatReconnectContextSDKCallStarted",
@@ -6,7 +6,12 @@ import { ILiveChatWidgetAction } from "../../../contexts/common/ILiveChatWidgetA
6
6
  import { ILiveChatWidgetContext } from "../../../contexts/common/ILiveChatWidgetContext";
7
7
  import { ILiveChatWidgetProps } from "../interfaces/ILiveChatWidgetProps";
8
8
  declare const handleChatReconnect: (facadeChatSDK: FacadeChatSDK, props: ILiveChatWidgetProps, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, initStartChat: any, state: ILiveChatWidgetContext) => Promise<boolean>;
9
+ /**
10
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
11
+ * In that case the caller must not start another chat.
12
+ */
13
+ declare const isReconnectTriggered: (facadeChatSDK: FacadeChatSDK, props: ILiveChatWidgetProps, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, initStartChat: any, state: ILiveChatWidgetContext) => Promise<boolean>;
9
14
  declare const getChatReconnectContext: (facadeChatSDK: FacadeChatSDK, chatConfig: ChatConfig, props: any, isAuthenticatedChat: boolean, dispatch: Dispatch<ILiveChatWidgetAction>) => Promise<import("@microsoft/omnichannel-chat-sdk/lib/core/ChatReconnectContext").default | undefined>;
10
15
  declare const isReconnectEnabled: (chatConfig?: ChatConfig) => boolean;
11
16
  declare const isPersistentEnabled: (chatConfig?: ChatConfig) => boolean;
12
- export { handleChatReconnect, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
17
+ export { handleChatReconnect, isReconnectTriggered, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
@@ -6,6 +6,10 @@ import { ILiveChatWidgetProps } from "../interfaces/ILiveChatWidgetProps";
6
6
  import StartChatOptionalParams from "@microsoft/omnichannel-chat-sdk/lib/core/StartChatOptionalParams";
7
7
  declare const prepareStartChat: (props: ILiveChatWidgetProps, facadeChatSDK: FacadeChatSDK, state: ILiveChatWidgetContext, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any) => Promise<void>;
8
8
  declare const setPreChatAndInitiateChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, isProactiveChat?: boolean | false, proactiveChatEnablePrechatState?: boolean | false, state?: ILiveChatWidgetContext, props?: ILiveChatWidgetProps) => Promise<void>;
9
- declare const initStartChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, state: ILiveChatWidgetContext | undefined, props?: ILiveChatWidgetProps, params?: StartChatOptionalParams, persistedState?: any) => Promise<void>;
9
+ /**
10
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
11
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
12
+ */
13
+ declare const initStartChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, state: ILiveChatWidgetContext | undefined, props?: ILiveChatWidgetProps, params?: StartChatOptionalParams, persistedState?: any) => Promise<boolean>;
10
14
  declare const checkIfConversationStillValid: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, state: ILiveChatWidgetContext) => Promise<boolean>;
11
15
  export { prepareStartChat, initStartChat, setPreChatAndInitiateChat, checkIfConversationStillValid };
@@ -0,0 +1,5 @@
1
+ import { Dispatch } from "react";
2
+ import { FacadeChatSDK } from "../../../common/facades/FacadeChatSDK";
3
+ import { ILiveChatWidgetAction } from "../../../contexts/common/ILiveChatWidgetAction";
4
+ import { ILiveChatWidgetContext } from "../../../contexts/common/ILiveChatWidgetContext";
5
+ export declare const useChatTokenRenewal: (facade: FacadeChatSDK | undefined, state: ILiveChatWidgetContext, dispatch: Dispatch<ILiveChatWidgetAction>, widgetCacheId: string) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/omnichannel-chat-widget",
3
- "version": "2.0.1-main.b1649f1",
3
+ "version": "2.0.1-main.d7b3891",
4
4
  "description": "Microsoft Omnichannel Chat Widget",
5
5
  "main": "lib/cjs/index.js",
6
6
  "types": "lib/types/index.d.ts",
@@ -93,7 +93,7 @@
93
93
  "@azure/core-tracing": "^1.2.0",
94
94
  "@microsoft/applicationinsights-web": "^3.3.6",
95
95
  "@microsoft/omnichannel-chat-components": "1.2.0",
96
- "@microsoft/omnichannel-chat-sdk": "2.0.2-main.8b19159",
96
+ "@microsoft/omnichannel-chat-sdk": "2.0.2-main.355218f",
97
97
  "@opentelemetry/api": "^1.9.0",
98
98
  "abort-controller": "^3",
99
99
  "botframework-webchat": "4.18.1-hotfix.20260308.b15b405",