@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
@@ -40,11 +40,21 @@ export const getRecoveryEligibilityTelemetryProperties = (state, eligible) => {
40
40
  reason
41
41
  };
42
42
  };
43
+ const getRecoveryEligibilityScalarTelemetryProperties = properties => ({
44
+ conversationState: properties.conversationState,
45
+ hasReconnectId: String(properties.hasReconnectId),
46
+ hasLiveChatContext: String(properties.hasLiveChatContext),
47
+ hasRequestId: String(properties.hasRequestId),
48
+ eligible: String(properties.eligible),
49
+ reason: properties.reason
50
+ });
43
51
  export const logRecoveryEligibilityTelemetry = (state, eligible) => {
44
52
  try {
53
+ const properties = getRecoveryEligibilityTelemetryProperties(state, eligible);
45
54
  TelemetryHelper.logActionEvent(LogLevel.INFO, {
46
55
  Event: TelemetryEvent.RecoveryEligibilityEvaluated,
47
- CustomProperties: getRecoveryEligibilityTelemetryProperties(state, eligible)
56
+ CustomProperties: properties,
57
+ ...getRecoveryEligibilityScalarTelemetryProperties(properties)
48
58
  });
49
59
  } catch (error) {
50
60
  console.warn(error);
@@ -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);
@@ -0,0 +1,153 @@
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
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ /******
9
+ * AttachmentForScreenReaderMiddleware
10
+ *
11
+ * Web Chat reads an Adaptive Card to screen readers only from the card's `speak` property.
12
+ * A card without `speak` is announced as "A card" with no content.
13
+ * This middleware sets `speak` from the visible text of the card, then lets Web Chat render it as usual.
14
+ ******/
15
+
16
+ import React, { useMemo } from "react";
17
+ import { Constants } from "../../../../../common/Constants";
18
+ import { hooks } from "botframework-webchat";
19
+ const useAdaptiveCardsPackage = hooks.useAdaptiveCardsPackage,
20
+ useStyleOptions = hooks.useStyleOptions;
21
+ const ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive";
22
+ const HTML_BLOCK_END = /<\/(p|li|h[1-6]|div|tr|td|th|blockquote|pre)>|<br\s*\/?>/gi;
23
+ // The "opens in a new window" icon of each link is left out: it describes the link target, not the content of the message.
24
+ const htmlToText = html => {
25
+ const body = new DOMParser().parseFromString(html.replace(HTML_BLOCK_END, "$& "), "text/html").body;
26
+ body.querySelectorAll(`script, style, template, img.${Constants.OpenLinkIconCssClass}`).forEach(element => element.remove());
27
+ body.querySelectorAll("img").forEach(image => image.replaceWith(` ${image.getAttribute("alt") ?? ""} `));
28
+ return (body.textContent ?? "").replace(/\s+/g, " ").trim();
29
+ };
30
+
31
+ // Renders the element as the visible card does: Adaptive Cards formats {{DATE()}} and {{TIME()}}, then the Markdown is rendered.
32
+ // Web Chat sets the static Markdown handler before each visible render, and this restores the previous handler after rendering.
33
+ const getRenderedText = (element, AdaptiveCard, renderMarkdownAsHTML) => {
34
+ const previousOnProcessMarkdown = AdaptiveCard.onProcessMarkdown;
35
+ try {
36
+ AdaptiveCard.onProcessMarkdown = (text, result) => {
37
+ result.outputHtml = renderMarkdownAsHTML(text);
38
+ result.didProcess = true;
39
+ };
40
+ const renderedElement = element.render();
41
+ return renderedElement ? htmlToText(renderedElement.outerHTML) : "";
42
+ } catch {
43
+ var _element$asString;
44
+ return ((_element$asString = element.asString) === null || _element$asString === void 0 ? void 0 : _element$asString.call(element)) ?? "";
45
+ } finally {
46
+ AdaptiveCard.onProcessMarkdown = previousOnProcessMarkdown;
47
+ }
48
+ };
49
+
50
+ // Collects the visible text of the card in document order, after the parser has applied element fallbacks.
51
+ // Inputs and actions are not collected because Web Chat already lists them after the card text.
52
+ export const getAdaptiveCardSpeak = (content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion) => {
53
+ const AdaptiveCard = adaptiveCardsPackage.AdaptiveCard,
54
+ FactSet = adaptiveCardsPackage.FactSet,
55
+ Image = adaptiveCardsPackage.Image,
56
+ RichTextBlock = adaptiveCardsPackage.RichTextBlock,
57
+ SerializationContext = adaptiveCardsPackage.SerializationContext,
58
+ TextBlock = adaptiveCardsPackage.TextBlock,
59
+ Version = adaptiveCardsPackage.Version;
60
+ const maxVersion = adaptiveCardsParserMaxVersion ? Version.parse(adaptiveCardsParserMaxVersion, new SerializationContext()) : undefined;
61
+ const card = new AdaptiveCard();
62
+ const texts = [];
63
+ card.parse(content, new SerializationContext(maxVersion !== null && maxVersion !== void 0 && maxVersion.isValid ? maxVersion : undefined));
64
+ const getFactText = (factSet, text) => {
65
+ const textBlock = new TextBlock(text);
66
+ textBlock.setParent(factSet);
67
+ return getRenderedText(textBlock, AdaptiveCard, renderMarkdownAsHTML);
68
+ };
69
+ const walk = element => {
70
+ if (!(element !== null && element !== void 0 && element.isVisible)) {
71
+ return;
72
+ }
73
+ if (element instanceof TextBlock || element instanceof RichTextBlock) {
74
+ texts.push(getRenderedText(element, AdaptiveCard, renderMarkdownAsHTML));
75
+ } else if (element instanceof FactSet) {
76
+ element.facts.forEach(_ref => {
77
+ let name = _ref.name,
78
+ value = _ref.value;
79
+ texts.push([name, value].map(text => text ? getFactText(element, text) : "").filter(Boolean).join(": "));
80
+ });
81
+ } else if (element instanceof Image) {
82
+ texts.push(element.altText);
83
+ }
84
+ if (element.getItemAt && element.getItemCount) {
85
+ for (let index = 0, count = element.getItemCount(); index < count; index++) {
86
+ walk(element.getItemAt(index));
87
+ }
88
+ }
89
+ };
90
+ walk(card);
91
+ return texts.filter(text => typeof text === "string" && text).join(" ").replace(/\s+/g, " ").trim();
92
+ };
93
+ const AdaptiveCardForScreenReader = _ref2 => {
94
+ let args = _ref2.args,
95
+ next = _ref2.next,
96
+ renderMarkdownAsHTML = _ref2.renderMarkdownAsHTML;
97
+ const _useAdaptiveCardsPack = useAdaptiveCardsPackage(),
98
+ _useAdaptiveCardsPack2 = _slicedToArray(_useAdaptiveCardsPack, 1),
99
+ adaptiveCardsPackage = _useAdaptiveCardsPack2[0];
100
+ const _useStyleOptions = useStyleOptions(),
101
+ _useStyleOptions2 = _slicedToArray(_useStyleOptions, 1),
102
+ adaptiveCardsParserMaxVersion = _useStyleOptions2[0].adaptiveCardsParserMaxVersion;
103
+ const _args = _slicedToArray(args, 1),
104
+ options = _args[0];
105
+ const attachment = options.attachment;
106
+
107
+ // The widget creates a new Markdown renderer on each render with the same settings, so the text is computed once for each attachment.
108
+ const contentWithSpeak = useMemo(() => {
109
+ try {
110
+ const content = typeof attachment.content === "string" ? JSON.parse(attachment.content) : attachment.content;
111
+ if (!content || typeof content !== "object" || content.speak) {
112
+ return undefined;
113
+ }
114
+ const speak = getAdaptiveCardSpeak(content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion);
115
+ return speak ? {
116
+ ...content,
117
+ speak
118
+ } : undefined;
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ }, [adaptiveCardsPackage, adaptiveCardsParserMaxVersion, attachment]);
123
+ const render = contentWithSpeak ? next({
124
+ ...options,
125
+ attachment: {
126
+ ...attachment,
127
+ content: contentWithSpeak
128
+ }
129
+ }, ...args.slice(1)) : next(...args);
130
+ return typeof render === "function" ? render() : null;
131
+ };
132
+ export const createAttachmentForScreenReaderMiddleware = renderMarkdownAsHTML => {
133
+ const attachmentForScreenReaderMiddleware = () => next => function () {
134
+ var _args$;
135
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
136
+ args[_key] = arguments[_key];
137
+ }
138
+ const attachment = (_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.attachment;
139
+
140
+ // Web Chat renders nothing for a card without content, so it is left to Web Chat.
141
+ if ((attachment === null || attachment === void 0 ? void 0 : attachment.contentType) !== ADAPTIVE_CARD_CONTENT_TYPE || !attachment.content) {
142
+ return next(...args);
143
+ }
144
+
145
+ // eslint-disable-next-line react/display-name
146
+ return () => /*#__PURE__*/React.createElement(AdaptiveCardForScreenReader, {
147
+ args: args,
148
+ next: next,
149
+ renderMarkdownAsHTML: renderMarkdownAsHTML
150
+ });
151
+ };
152
+ return attachmentForScreenReaderMiddleware;
153
+ };
@@ -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",
@@ -13,6 +13,12 @@ export interface TelemetryEventWrapper {
13
13
  ElapsedTimeInMilliseconds?: number;
14
14
  Data?: any;
15
15
  CustomProperties?: any;
16
+ conversationState?: string;
17
+ hasReconnectId?: string;
18
+ hasLiveChatContext?: string;
19
+ hasRequestId?: string;
20
+ eligible?: string;
21
+ reason?: string;
16
22
  }
17
23
  export declare class TelemetryHelper {
18
24
  static callId: string;