@microsoft/omnichannel-chat-widget 2.0.1-main.38e7390 → 2.0.1-main.5b375de

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.
Files changed (33) hide show
  1. package/README.md +57 -0
  2. package/lib/cjs/common/telemetry/TelemetryConstants.js +10 -0
  3. package/lib/cjs/common/telemetry/TelemetryHelper.js +8 -0
  4. package/lib/cjs/components/livechatwidget/LiveChatWidget.js +2 -0
  5. package/lib/cjs/components/livechatwidget/common/initWebChatComposer.js +31 -7
  6. package/lib/cjs/components/livechatwidget/common/reconnectChatHelper.js +29 -1
  7. package/lib/cjs/components/livechatwidget/common/recoveryEligibilityTelemetry.js +11 -1
  8. package/lib/cjs/components/livechatwidget/common/startChat.js +15 -7
  9. package/lib/cjs/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  10. package/lib/cjs/components/livechatwidget/common/useChatTokenRenewal.js +252 -0
  11. package/lib/cjs/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +5 -17
  12. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +159 -0
  13. package/lib/esm/common/telemetry/TelemetryConstants.js +10 -0
  14. package/lib/esm/common/telemetry/TelemetryHelper.js +8 -0
  15. package/lib/esm/components/livechatwidget/LiveChatWidget.js +3 -1
  16. package/lib/esm/components/livechatwidget/common/initWebChatComposer.js +28 -6
  17. package/lib/esm/components/livechatwidget/common/reconnectChatHelper.js +28 -1
  18. package/lib/esm/components/livechatwidget/common/recoveryEligibilityTelemetry.js +11 -1
  19. package/lib/esm/components/livechatwidget/common/startChat.js +15 -7
  20. package/lib/esm/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  21. package/lib/esm/components/livechatwidget/common/useChatTokenRenewal.js +245 -0
  22. package/lib/esm/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +6 -18
  23. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +153 -0
  24. package/lib/types/common/telemetry/TelemetryConstants.d.ts +5 -0
  25. package/lib/types/common/telemetry/TelemetryHelper.d.ts +6 -0
  26. package/lib/types/common/telemetry/definitions/Contracts.d.ts +6 -0
  27. package/lib/types/common/telemetry/definitions/Payload.d.ts +6 -0
  28. package/lib/types/components/livechatwidget/common/initWebChatComposer.d.ts +8 -0
  29. package/lib/types/components/livechatwidget/common/reconnectChatHelper.d.ts +6 -1
  30. package/lib/types/components/livechatwidget/common/startChat.d.ts +5 -1
  31. package/lib/types/components/livechatwidget/common/useChatTokenRenewal.d.ts +5 -0
  32. package/lib/types/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.d.ts +11 -0
  33. package/package.json +5 -6
@@ -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);
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getAdaptiveCardSpeak = exports.createAttachmentForScreenReaderMiddleware = void 0;
7
+ var _react = _interopRequireWildcard(require("react"));
8
+ var _Constants = require("../../../../../common/Constants");
9
+ var _botframeworkWebchat = require("botframework-webchat");
10
+ 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); }
11
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
12
+ 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."); }
13
+ 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; } }
14
+ 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; }
15
+ 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; } }
16
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /* eslint-disable @typescript-eslint/no-explicit-any */ /******
17
+ * AttachmentForScreenReaderMiddleware
18
+ *
19
+ * Web Chat reads an Adaptive Card to screen readers only from the card's `speak` property.
20
+ * A card without `speak` is announced as "A card" with no content.
21
+ * This middleware sets `speak` from the visible text of the card, then lets Web Chat render it as usual.
22
+ ******/
23
+ const useAdaptiveCardsPackage = _botframeworkWebchat.hooks.useAdaptiveCardsPackage,
24
+ useStyleOptions = _botframeworkWebchat.hooks.useStyleOptions;
25
+ const ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive";
26
+ const HTML_BLOCK_END = /<\/(p|li|h[1-6]|div|tr|td|th|blockquote|pre)>|<br\s*\/?>/gi;
27
+ // The "opens in a new window" icon of each link is left out: it describes the link target, not the content of the message.
28
+ const htmlToText = html => {
29
+ const body = new DOMParser().parseFromString(html.replace(HTML_BLOCK_END, "$& "), "text/html").body;
30
+ body.querySelectorAll(`script, style, template, img.${_Constants.Constants.OpenLinkIconCssClass}`).forEach(element => element.remove());
31
+ body.querySelectorAll("img").forEach(image => image.replaceWith(` ${image.getAttribute("alt") ?? ""} `));
32
+ return (body.textContent ?? "").replace(/\s+/g, " ").trim();
33
+ };
34
+
35
+ // Renders the element as the visible card does: Adaptive Cards formats {{DATE()}} and {{TIME()}}, then the Markdown is rendered.
36
+ // Web Chat sets the static Markdown handler before each visible render, and this restores the previous handler after rendering.
37
+ const getRenderedText = (element, AdaptiveCard, renderMarkdownAsHTML) => {
38
+ const previousOnProcessMarkdown = AdaptiveCard.onProcessMarkdown;
39
+ try {
40
+ AdaptiveCard.onProcessMarkdown = (text, result) => {
41
+ result.outputHtml = renderMarkdownAsHTML(text);
42
+ result.didProcess = true;
43
+ };
44
+ const renderedElement = element.render();
45
+ return renderedElement ? htmlToText(renderedElement.outerHTML) : "";
46
+ } catch {
47
+ var _element$asString;
48
+ return ((_element$asString = element.asString) === null || _element$asString === void 0 ? void 0 : _element$asString.call(element)) ?? "";
49
+ } finally {
50
+ AdaptiveCard.onProcessMarkdown = previousOnProcessMarkdown;
51
+ }
52
+ };
53
+
54
+ // Collects the visible text of the card in document order, after the parser has applied element fallbacks.
55
+ // Inputs and actions are not collected because Web Chat already lists them after the card text.
56
+ const getAdaptiveCardSpeak = (content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion) => {
57
+ const AdaptiveCard = adaptiveCardsPackage.AdaptiveCard,
58
+ FactSet = adaptiveCardsPackage.FactSet,
59
+ Image = adaptiveCardsPackage.Image,
60
+ RichTextBlock = adaptiveCardsPackage.RichTextBlock,
61
+ SerializationContext = adaptiveCardsPackage.SerializationContext,
62
+ TextBlock = adaptiveCardsPackage.TextBlock,
63
+ Version = adaptiveCardsPackage.Version;
64
+ const maxVersion = adaptiveCardsParserMaxVersion ? Version.parse(adaptiveCardsParserMaxVersion, new SerializationContext()) : undefined;
65
+ const card = new AdaptiveCard();
66
+ const texts = [];
67
+ card.parse(content, new SerializationContext(maxVersion !== null && maxVersion !== void 0 && maxVersion.isValid ? maxVersion : undefined));
68
+ const getFactText = (factSet, text) => {
69
+ const textBlock = new TextBlock(text);
70
+ textBlock.setParent(factSet);
71
+ return getRenderedText(textBlock, AdaptiveCard, renderMarkdownAsHTML);
72
+ };
73
+ const walk = element => {
74
+ if (!(element !== null && element !== void 0 && element.isVisible)) {
75
+ return;
76
+ }
77
+ if (element instanceof TextBlock || element instanceof RichTextBlock) {
78
+ texts.push(getRenderedText(element, AdaptiveCard, renderMarkdownAsHTML));
79
+ } else if (element instanceof FactSet) {
80
+ element.facts.forEach(_ref => {
81
+ let name = _ref.name,
82
+ value = _ref.value;
83
+ texts.push([name, value].map(text => text ? getFactText(element, text) : "").filter(Boolean).join(": "));
84
+ });
85
+ } else if (element instanceof Image) {
86
+ texts.push(element.altText);
87
+ }
88
+ if (element.getItemAt && element.getItemCount) {
89
+ for (let index = 0, count = element.getItemCount(); index < count; index++) {
90
+ walk(element.getItemAt(index));
91
+ }
92
+ }
93
+ };
94
+ walk(card);
95
+ return texts.filter(text => typeof text === "string" && text).join(" ").replace(/\s+/g, " ").trim();
96
+ };
97
+ exports.getAdaptiveCardSpeak = getAdaptiveCardSpeak;
98
+ const AdaptiveCardForScreenReader = _ref2 => {
99
+ let args = _ref2.args,
100
+ next = _ref2.next,
101
+ renderMarkdownAsHTML = _ref2.renderMarkdownAsHTML;
102
+ const _useAdaptiveCardsPack = useAdaptiveCardsPackage(),
103
+ _useAdaptiveCardsPack2 = _slicedToArray(_useAdaptiveCardsPack, 1),
104
+ adaptiveCardsPackage = _useAdaptiveCardsPack2[0];
105
+ const _useStyleOptions = useStyleOptions(),
106
+ _useStyleOptions2 = _slicedToArray(_useStyleOptions, 1),
107
+ adaptiveCardsParserMaxVersion = _useStyleOptions2[0].adaptiveCardsParserMaxVersion;
108
+ const _args = _slicedToArray(args, 1),
109
+ options = _args[0];
110
+ const attachment = options.attachment;
111
+
112
+ // The widget creates a new Markdown renderer on each render with the same settings, so the text is computed once for each attachment.
113
+ const contentWithSpeak = (0, _react.useMemo)(() => {
114
+ try {
115
+ const content = typeof attachment.content === "string" ? JSON.parse(attachment.content) : attachment.content;
116
+ if (!content || typeof content !== "object" || content.speak) {
117
+ return undefined;
118
+ }
119
+ const speak = getAdaptiveCardSpeak(content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion);
120
+ return speak ? {
121
+ ...content,
122
+ speak
123
+ } : undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }, [adaptiveCardsPackage, adaptiveCardsParserMaxVersion, attachment]);
128
+ const render = contentWithSpeak ? next({
129
+ ...options,
130
+ attachment: {
131
+ ...attachment,
132
+ content: contentWithSpeak
133
+ }
134
+ }, ...args.slice(1)) : next(...args);
135
+ return typeof render === "function" ? render() : null;
136
+ };
137
+ const createAttachmentForScreenReaderMiddleware = renderMarkdownAsHTML => {
138
+ const attachmentForScreenReaderMiddleware = () => next => function () {
139
+ var _args$;
140
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
141
+ args[_key] = arguments[_key];
142
+ }
143
+ const attachment = (_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.attachment;
144
+
145
+ // Web Chat renders nothing for a card without content, so it is left to Web Chat.
146
+ if ((attachment === null || attachment === void 0 ? void 0 : attachment.contentType) !== ADAPTIVE_CARD_CONTENT_TYPE || !attachment.content) {
147
+ return next(...args);
148
+ }
149
+
150
+ // eslint-disable-next-line react/display-name
151
+ return () => /*#__PURE__*/_react.default.createElement(AdaptiveCardForScreenReader, {
152
+ args: args,
153
+ next: next,
154
+ renderMarkdownAsHTML: renderMarkdownAsHTML
155
+ });
156
+ };
157
+ return attachmentForScreenReaderMiddleware;
158
+ };
159
+ exports.createAttachmentForScreenReaderMiddleware = createAttachmentForScreenReaderMiddleware;
@@ -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:
@@ -77,6 +77,14 @@ export let TelemetryHelper = /*#__PURE__*/function () {
77
77
  event.ExceptionDetails = JSON.stringify(payload.ExceptionDetails);
78
78
  event.Description = payload.Description;
79
79
  event.CustomProperties = JSON.stringify(payload.CustomProperties);
80
+ if (payload.Event === TelemetryEvent.RecoveryEligibilityEvaluated) {
81
+ event.conversationState = payload.conversationState;
82
+ event.hasReconnectId = payload.hasReconnectId;
83
+ event.hasLiveChatContext = payload.hasLiveChatContext;
84
+ event.hasRequestId = payload.hasRequestId;
85
+ event.eligible = payload.eligible;
86
+ event.reason = payload.reason;
87
+ }
80
88
  });
81
89
  }
82
90
  }, {
@@ -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, {
@@ -15,6 +15,7 @@ import createAttachmentSentAnnouncementMiddleware from "../../webchatcontainerst
15
15
  import channelDataMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/channelDataMiddleware";
16
16
  import { createActivityMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityMiddleware";
17
17
  import { createActivityStatusMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityStatusMiddleware";
18
+ import { createAttachmentForScreenReaderMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware";
18
19
  import { createAttachmentMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentMiddleware";
19
20
  import createAttachmentUploadValidatorMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware";
20
21
  import { createAvatarMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/avatarMiddleware";
@@ -42,6 +43,31 @@ import htmlPlayerMiddleware from "../../webchatcontainerstateful/webchatcontroll
42
43
  import htmlTextMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/htmlTextMiddleware";
43
44
  import preProcessingMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/preProcessingMiddleware";
44
45
  import sanitizationMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/sanitizationMiddleware";
46
+ const markdownSanitizeConfig = {
47
+ FORBID_TAGS: ["form", "button", "script", "div", "input"],
48
+ FORBID_ATTR: ["action"],
49
+ ADD_ATTR: ["target"]
50
+ };
51
+
52
+ /**
53
+ * Renders Markdown for the screen reader text of Adaptive Cards, from the same pieces as the visible card:
54
+ * the host renderMarkdown when set, the hyperlink text override, and the same sanitization.
55
+ * Markdown is always formatted, also when the widget shows Markdown unformatted, so that screen readers do not read the syntax.
56
+ * Styles are removed with their content because the card does not show them.
57
+ */
58
+ export const createScreenReaderMarkdownRenderer = webChatContainerProps => {
59
+ var _webChatContainerProp;
60
+ const hostRenderMarkdown = webChatContainerProps === null || webChatContainerProps === void 0 || (_webChatContainerProp = webChatContainerProps.webChatProps) === null || _webChatContainerProp === void 0 ? void 0 : _webChatContainerProp.renderMarkdown;
61
+ const markdown = createMarkdown(false, (webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.disableNewLineMarkdownSupport) ?? defaultWebChatContainerStatefulProps.disableNewLineMarkdownSupport, webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.opensMarkdownLinksInSameTab);
62
+ const hyperlinkTextOverrideRenderer = new HyperlinkTextOverrideRenderer((webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.hyperlinkTextOverride) ?? defaultWebChatContainerStatefulProps.hyperlinkTextOverride);
63
+ return text => {
64
+ const html = hostRenderMarkdown ? hostRenderMarkdown(text) : markdown.render(text);
65
+ return DOMPurify.sanitize(hyperlinkTextOverrideRenderer.render(html), {
66
+ ...markdownSanitizeConfig,
67
+ FORBID_TAGS: [...markdownSanitizeConfig.FORBID_TAGS, "style"]
68
+ });
69
+ };
70
+ };
45
71
 
46
72
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
73
  export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) => {
@@ -149,12 +175,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
149
175
  });
150
176
 
151
177
  // EXISTING sanitization (continues to work as before)
152
- const config = {
153
- FORBID_TAGS: ["form", "button", "script", "div", "input"],
154
- FORBID_ATTR: ["action"],
155
- ADD_ATTR: ["target"]
156
- };
157
- text = DOMPurify.sanitize(text, config);
178
+ text = DOMPurify.sanitize(text, markdownSanitizeConfig);
158
179
 
159
180
  // MONITOR-ONLY: Test what the stricter allowlist would remove (Phase 1)
160
181
  // This does NOT modify the text, only logs telemetry
@@ -358,6 +379,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
358
379
  store: webChatStore,
359
380
  activityMiddleware: (_props$webChatContain0 = props.webChatContainerProps) !== null && _props$webChatContain0 !== void 0 && (_props$webChatContain0 = _props$webChatContain0.renderingMiddlewareProps) !== null && _props$webChatContain0 !== void 0 && _props$webChatContain0.disableActivityMiddleware ? undefined : createActivityMiddleware(renderMarkdown, (_state$domainStates$r = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r === void 0 ? void 0 : _state$domainStates$r.systemMessageStyleProps, (_state$domainStates$r2 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r2 === void 0 ? void 0 : _state$domainStates$r2.userMessageStyleProps, localizedTexts),
360
381
  attachmentMiddleware: (_props$webChatContain1 = props.webChatContainerProps) !== null && _props$webChatContain1 !== void 0 && (_props$webChatContain1 = _props$webChatContain1.renderingMiddlewareProps) !== null && _props$webChatContain1 !== void 0 && _props$webChatContain1.disableAttachmentMiddleware ? undefined : createAttachmentMiddleware(((_state$domainStates$r3 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r3 === void 0 || (_state$domainStates$r3 = _state$domainStates$r3.attachmentProps) === null || _state$domainStates$r3 === void 0 ? void 0 : _state$domainStates$r3.enableInlinePlaying) ?? defaultAttachmentProps.enableInlinePlaying),
382
+ attachmentForScreenReaderMiddleware: createAttachmentForScreenReaderMiddleware(createScreenReaderMarkdownRenderer(props.webChatContainerProps)),
361
383
  activityStatusMiddleware: (_props$webChatContain10 = props.webChatContainerProps) !== null && _props$webChatContain10 !== void 0 && (_props$webChatContain10 = _props$webChatContain10.renderingMiddlewareProps) !== null && _props$webChatContain10 !== void 0 && _props$webChatContain10.disableActivityStatusMiddleware ? undefined : createActivityStatusMiddleware(getLocaleStringFromId((_state$domainStates$l5 = state.domainStates.liveChatConfig) === null || _state$domainStates$l5 === void 0 || (_state$domainStates$l5 = _state$domainStates$l5.ChatWidgetLanguage) === null || _state$domainStates$l5 === void 0 ? void 0 : _state$domainStates$l5.msdyn_localeid)),
362
384
  toastMiddleware: (_props$webChatContain11 = props.webChatContainerProps) !== null && _props$webChatContain11 !== void 0 && (_props$webChatContain11 = _props$webChatContain11.renderingMiddlewareProps) !== null && _props$webChatContain11 !== void 0 && _props$webChatContain11.disableToastMiddleware ? undefined : createToastMiddleware(props.notificationPaneProps, endChat),
363
385
  renderMarkdown,
@@ -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 };