@memori.ai/memori-react 9.0.0-alpha.5 → 9.0.0-alpha.7

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 (286) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/components/AgeVerificationModal/AgeVerificationModal.js +8 -3
  3. package/dist/components/AgeVerificationModal/AgeVerificationModal.js.map +1 -1
  4. package/dist/components/Auth/Auth.js +3 -1
  5. package/dist/components/Auth/Auth.js.map +1 -1
  6. package/dist/components/Avatar/Avatar.js +5 -10
  7. package/dist/components/Avatar/Avatar.js.map +1 -1
  8. package/dist/components/Avatar/AvatarView/AvatarComponent/components/FullbodyAvatar/fullbodyAvatar.js +8 -1
  9. package/dist/components/Avatar/AvatarView/AvatarComponent/components/FullbodyAvatar/fullbodyAvatar.js.map +1 -1
  10. package/dist/components/Avatar/AvatarView/AvatarComponent/components/controllers/MorphTargetController.js +1 -1
  11. package/dist/components/Avatar/AvatarView/AvatarComponent/components/controllers/MorphTargetController.js.map +1 -1
  12. package/dist/components/Avatar/AvatarView/AvatarComponent/constants.d.ts +2 -0
  13. package/dist/components/Avatar/AvatarView/AvatarComponent/constants.js +14 -5
  14. package/dist/components/Avatar/AvatarView/AvatarComponent/constants.js.map +1 -1
  15. package/dist/components/Chat/Chat.js +3 -1
  16. package/dist/components/Chat/Chat.js.map +1 -1
  17. package/dist/components/ChatBubble/ChatBubble.js +21 -15
  18. package/dist/components/ChatBubble/ChatBubble.js.map +1 -1
  19. package/dist/components/ChatHistoryDrawer/ChatHistory.js +3 -1
  20. package/dist/components/ChatHistoryDrawer/ChatHistory.js.map +1 -1
  21. package/dist/components/CompletionProviderStatus/CompletionProviderStatus.js +6 -3
  22. package/dist/components/CompletionProviderStatus/CompletionProviderStatus.js.map +1 -1
  23. package/dist/components/ContentPreviewModal/ContentPreviewModal.js +3 -1
  24. package/dist/components/ContentPreviewModal/ContentPreviewModal.js.map +1 -1
  25. package/dist/components/DateSelector/DateSelector.d.ts +2 -1
  26. package/dist/components/DateSelector/DateSelector.js +17 -7
  27. package/dist/components/DateSelector/DateSelector.js.map +1 -1
  28. package/dist/components/ExpertsDrawer/ExpertsDrawer.js +3 -1
  29. package/dist/components/ExpertsDrawer/ExpertsDrawer.js.map +1 -1
  30. package/dist/components/FilePreview/FilePreview.js +22 -5
  31. package/dist/components/FilePreview/FilePreview.js.map +1 -1
  32. package/dist/components/KnownFacts/KnownFacts.js +5 -3
  33. package/dist/components/KnownFacts/KnownFacts.js.map +1 -1
  34. package/dist/components/LoginDrawer/LoginDrawer.js +3 -1
  35. package/dist/components/LoginDrawer/LoginDrawer.js.map +1 -1
  36. package/dist/components/MediaWidget/MediaItemWidget.js +14 -12
  37. package/dist/components/MediaWidget/MediaItemWidget.js.map +1 -1
  38. package/dist/components/MediaWidget/MediaItemWidget.utils.d.ts +3 -2
  39. package/dist/components/MediaWidget/MediaItemWidget.utils.js +28 -6
  40. package/dist/components/MediaWidget/MediaItemWidget.utils.js.map +1 -1
  41. package/dist/components/MediaWidget/MediaPreviewModal.js +6 -7
  42. package/dist/components/MediaWidget/MediaPreviewModal.js.map +1 -1
  43. package/dist/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.css +19 -5
  44. package/dist/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js +4 -1
  45. package/dist/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js.map +1 -1
  46. package/dist/components/MemoriWidget/MemoriWidget.css +4 -2
  47. package/dist/components/MemoriWidget/MemoriWidget.js +760 -404
  48. package/dist/components/MemoriWidget/MemoriWidget.js.map +1 -1
  49. package/dist/components/SettingsDrawer/SettingsDrawer.js +3 -1
  50. package/dist/components/SettingsDrawer/SettingsDrawer.js.map +1 -1
  51. package/dist/components/StartPanel/StartPanel.js +3 -1
  52. package/dist/components/StartPanel/StartPanel.js.map +1 -1
  53. package/dist/components/UploadButton/UploadButton.js +21 -5
  54. package/dist/components/UploadButton/UploadButton.js.map +1 -1
  55. package/dist/components/UploadButton/UploadDocuments/UploadDocuments.js +126 -60
  56. package/dist/components/UploadButton/UploadDocuments/UploadDocuments.js.map +1 -1
  57. package/dist/components/UploadButton/UploadImages/UploadImages.js +3 -1
  58. package/dist/components/UploadButton/UploadImages/UploadImages.js.map +1 -1
  59. package/dist/components/WhyThisAnswer/WhyThisAnswer.js +3 -1
  60. package/dist/components/WhyThisAnswer/WhyThisAnswer.js.map +1 -1
  61. package/dist/components/layouts/WebsiteAssistant/WebsiteAssistant.js +3 -1
  62. package/dist/components/layouts/WebsiteAssistant/WebsiteAssistant.js.map +1 -1
  63. package/dist/components/layouts/WebsiteAssistant/website-assistant.css +21 -1
  64. package/dist/components/layouts/chat.css +2 -1
  65. package/dist/components/layouts/fullpage.css +31 -8
  66. package/dist/components/layouts/hidden-chat.css +1 -0
  67. package/dist/components/layouts/totem.css +2 -1
  68. package/dist/components/layouts/zoomed-full-body.css +32 -7
  69. package/dist/context/widgetSurfaceContext.d.ts +3 -0
  70. package/dist/context/widgetSurfaceContext.js +11 -0
  71. package/dist/context/widgetSurfaceContext.js.map +1 -0
  72. package/dist/helpers/constants.d.ts +3 -0
  73. package/dist/helpers/constants.js +27 -1
  74. package/dist/helpers/constants.js.map +1 -1
  75. package/dist/helpers/credits.d.ts +5 -2
  76. package/dist/helpers/credits.js +5 -1
  77. package/dist/helpers/credits.js.map +1 -1
  78. package/dist/helpers/message.d.ts +1 -1
  79. package/dist/helpers/message.js +4 -4
  80. package/dist/helpers/message.js.map +1 -1
  81. package/dist/helpers/nats/getNatsConfig.d.ts +9 -0
  82. package/dist/helpers/nats/getNatsConfig.js +65 -0
  83. package/dist/helpers/nats/getNatsConfig.js.map +1 -0
  84. package/dist/helpers/nats/isSessionExpiredError.d.ts +3 -0
  85. package/dist/helpers/nats/isSessionExpiredError.js +36 -0
  86. package/dist/helpers/nats/isSessionExpiredError.js.map +1 -0
  87. package/dist/helpers/nats/useNats.d.ts +12 -0
  88. package/dist/helpers/nats/useNats.js +75 -0
  89. package/dist/helpers/nats/useNats.js.map +1 -0
  90. package/dist/helpers/nats/useNatsSession.d.ts +28 -0
  91. package/dist/helpers/nats/useNatsSession.js +212 -0
  92. package/dist/helpers/nats/useNatsSession.js.map +1 -0
  93. package/dist/helpers/utils.d.ts +21 -0
  94. package/dist/helpers/utils.js +75 -4
  95. package/dist/helpers/utils.js.map +1 -1
  96. package/dist/locales/de.json +1 -0
  97. package/dist/locales/en.json +1 -0
  98. package/dist/locales/es.json +1 -0
  99. package/dist/locales/fr.json +1 -0
  100. package/dist/locales/it.json +1 -0
  101. package/dist/styles.css +1 -1
  102. package/dist/types/integration.d.ts +3 -0
  103. package/dist/types/integration.js +16 -0
  104. package/dist/types/integration.js.map +1 -0
  105. package/dist/version.d.ts +1 -1
  106. package/dist/version.js +1 -1
  107. package/esm/components/AgeVerificationModal/AgeVerificationModal.js +8 -3
  108. package/esm/components/AgeVerificationModal/AgeVerificationModal.js.map +1 -1
  109. package/esm/components/Auth/Auth.js +3 -1
  110. package/esm/components/Auth/Auth.js.map +1 -1
  111. package/esm/components/Avatar/Avatar.js +5 -10
  112. package/esm/components/Avatar/Avatar.js.map +1 -1
  113. package/esm/components/Avatar/AvatarView/AvatarComponent/components/FullbodyAvatar/fullbodyAvatar.js +9 -2
  114. package/esm/components/Avatar/AvatarView/AvatarComponent/components/FullbodyAvatar/fullbodyAvatar.js.map +1 -1
  115. package/esm/components/Avatar/AvatarView/AvatarComponent/components/controllers/MorphTargetController.js +2 -2
  116. package/esm/components/Avatar/AvatarView/AvatarComponent/components/controllers/MorphTargetController.js.map +1 -1
  117. package/esm/components/Avatar/AvatarView/AvatarComponent/constants.d.ts +2 -0
  118. package/esm/components/Avatar/AvatarView/AvatarComponent/constants.js +13 -4
  119. package/esm/components/Avatar/AvatarView/AvatarComponent/constants.js.map +1 -1
  120. package/esm/components/Chat/Chat.js +3 -1
  121. package/esm/components/Chat/Chat.js.map +1 -1
  122. package/esm/components/ChatBubble/ChatBubble.js +21 -15
  123. package/esm/components/ChatBubble/ChatBubble.js.map +1 -1
  124. package/esm/components/ChatHistoryDrawer/ChatHistory.js +3 -1
  125. package/esm/components/ChatHistoryDrawer/ChatHistory.js.map +1 -1
  126. package/esm/components/CompletionProviderStatus/CompletionProviderStatus.js +6 -3
  127. package/esm/components/CompletionProviderStatus/CompletionProviderStatus.js.map +1 -1
  128. package/esm/components/ContentPreviewModal/ContentPreviewModal.js +3 -1
  129. package/esm/components/ContentPreviewModal/ContentPreviewModal.js.map +1 -1
  130. package/esm/components/DateSelector/DateSelector.d.ts +2 -1
  131. package/esm/components/DateSelector/DateSelector.js +17 -7
  132. package/esm/components/DateSelector/DateSelector.js.map +1 -1
  133. package/esm/components/ExpertsDrawer/ExpertsDrawer.js +3 -1
  134. package/esm/components/ExpertsDrawer/ExpertsDrawer.js.map +1 -1
  135. package/esm/components/FilePreview/FilePreview.js +24 -7
  136. package/esm/components/FilePreview/FilePreview.js.map +1 -1
  137. package/esm/components/KnownFacts/KnownFacts.js +5 -3
  138. package/esm/components/KnownFacts/KnownFacts.js.map +1 -1
  139. package/esm/components/LoginDrawer/LoginDrawer.js +3 -1
  140. package/esm/components/LoginDrawer/LoginDrawer.js.map +1 -1
  141. package/esm/components/MediaWidget/MediaItemWidget.js +16 -14
  142. package/esm/components/MediaWidget/MediaItemWidget.js.map +1 -1
  143. package/esm/components/MediaWidget/MediaItemWidget.utils.d.ts +3 -2
  144. package/esm/components/MediaWidget/MediaItemWidget.utils.js +27 -6
  145. package/esm/components/MediaWidget/MediaItemWidget.utils.js.map +1 -1
  146. package/esm/components/MediaWidget/MediaPreviewModal.js +6 -7
  147. package/esm/components/MediaWidget/MediaPreviewModal.js.map +1 -1
  148. package/esm/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.css +19 -5
  149. package/esm/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js +4 -1
  150. package/esm/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.js.map +1 -1
  151. package/esm/components/MemoriWidget/MemoriWidget.css +4 -2
  152. package/esm/components/MemoriWidget/MemoriWidget.js +760 -404
  153. package/esm/components/MemoriWidget/MemoriWidget.js.map +1 -1
  154. package/esm/components/SettingsDrawer/SettingsDrawer.js +3 -1
  155. package/esm/components/SettingsDrawer/SettingsDrawer.js.map +1 -1
  156. package/esm/components/StartPanel/StartPanel.js +3 -1
  157. package/esm/components/StartPanel/StartPanel.js.map +1 -1
  158. package/esm/components/UploadButton/UploadButton.js +21 -5
  159. package/esm/components/UploadButton/UploadButton.js.map +1 -1
  160. package/esm/components/UploadButton/UploadDocuments/UploadDocuments.js +126 -60
  161. package/esm/components/UploadButton/UploadDocuments/UploadDocuments.js.map +1 -1
  162. package/esm/components/UploadButton/UploadImages/UploadImages.js +3 -1
  163. package/esm/components/UploadButton/UploadImages/UploadImages.js.map +1 -1
  164. package/esm/components/WhyThisAnswer/WhyThisAnswer.js +3 -1
  165. package/esm/components/WhyThisAnswer/WhyThisAnswer.js.map +1 -1
  166. package/esm/components/layouts/WebsiteAssistant/WebsiteAssistant.js +3 -1
  167. package/esm/components/layouts/WebsiteAssistant/WebsiteAssistant.js.map +1 -1
  168. package/esm/components/layouts/WebsiteAssistant/website-assistant.css +21 -1
  169. package/esm/components/layouts/chat.css +2 -1
  170. package/esm/components/layouts/fullpage.css +31 -8
  171. package/esm/components/layouts/hidden-chat.css +1 -0
  172. package/esm/components/layouts/totem.css +2 -1
  173. package/esm/components/layouts/zoomed-full-body.css +32 -7
  174. package/esm/context/widgetSurfaceContext.d.ts +3 -0
  175. package/esm/context/widgetSurfaceContext.js +7 -0
  176. package/esm/context/widgetSurfaceContext.js.map +1 -0
  177. package/esm/helpers/constants.d.ts +3 -0
  178. package/esm/helpers/constants.js +26 -0
  179. package/esm/helpers/constants.js.map +1 -1
  180. package/esm/helpers/credits.d.ts +5 -2
  181. package/esm/helpers/credits.js +5 -1
  182. package/esm/helpers/credits.js.map +1 -1
  183. package/esm/helpers/message.d.ts +1 -1
  184. package/esm/helpers/message.js +2 -2
  185. package/esm/helpers/message.js.map +1 -1
  186. package/esm/helpers/nats/getNatsConfig.d.ts +9 -0
  187. package/esm/helpers/nats/getNatsConfig.js +61 -0
  188. package/esm/helpers/nats/getNatsConfig.js.map +1 -0
  189. package/esm/helpers/nats/isSessionExpiredError.d.ts +3 -0
  190. package/esm/helpers/nats/isSessionExpiredError.js +32 -0
  191. package/esm/helpers/nats/isSessionExpiredError.js.map +1 -0
  192. package/esm/helpers/nats/useNats.d.ts +12 -0
  193. package/esm/helpers/nats/useNats.js +72 -0
  194. package/esm/helpers/nats/useNats.js.map +1 -0
  195. package/esm/helpers/nats/useNatsSession.d.ts +28 -0
  196. package/esm/helpers/nats/useNatsSession.js +208 -0
  197. package/esm/helpers/nats/useNatsSession.js.map +1 -0
  198. package/esm/helpers/utils.d.ts +21 -0
  199. package/esm/helpers/utils.js +68 -3
  200. package/esm/helpers/utils.js.map +1 -1
  201. package/esm/locales/de.json +1 -0
  202. package/esm/locales/en.json +1 -0
  203. package/esm/locales/es.json +1 -0
  204. package/esm/locales/fr.json +1 -0
  205. package/esm/locales/it.json +1 -0
  206. package/esm/styles.css +1 -1
  207. package/esm/types/integration.d.ts +3 -0
  208. package/esm/types/integration.js +11 -0
  209. package/esm/types/integration.js.map +1 -0
  210. package/esm/version.d.ts +1 -1
  211. package/esm/version.js +1 -1
  212. package/package.json +5 -3
  213. package/src/components/AgeVerificationModal/AgeVerificationModal.tsx +9 -1
  214. package/src/components/Auth/Auth.tsx +3 -0
  215. package/src/components/Avatar/Avatar.stories.tsx +45 -28
  216. package/src/components/Avatar/Avatar.test.tsx +54 -0
  217. package/src/components/Avatar/Avatar.tsx +8 -12
  218. package/src/components/Avatar/AvatarView/AvatarComponent/components/FullbodyAvatar/fullbodyAvatar.tsx +12 -5
  219. package/src/components/Avatar/AvatarView/AvatarComponent/components/controllers/MorphTargetController.ts +2 -1
  220. package/src/components/Avatar/AvatarView/AvatarComponent/constants.ts +16 -4
  221. package/src/components/Avatar/__snapshots__/Avatar.test.tsx.snap +164 -0
  222. package/src/components/Chat/Chat.tsx +3 -0
  223. package/src/components/ChatBubble/ChatBubble.tsx +40 -12
  224. package/src/components/ChatHistoryDrawer/ChatHistory.tsx +3 -0
  225. package/src/components/CompletionProviderStatus/CompletionProviderStatus.tsx +8 -4
  226. package/src/components/ContentPreviewModal/ContentPreviewModal.tsx +3 -0
  227. package/src/components/DateSelector/DateSelector.stories.tsx +11 -2
  228. package/src/components/DateSelector/DateSelector.tsx +28 -9
  229. package/src/components/ExpertsDrawer/ExpertsDrawer.tsx +3 -0
  230. package/src/components/FilePreview/FilePreview.tsx +28 -7
  231. package/src/components/KnownFacts/KnownFacts.tsx +5 -0
  232. package/src/components/LoginDrawer/LoginDrawer.tsx +3 -0
  233. package/src/components/MediaWidget/MediaItemWidget.tsx +26 -13
  234. package/src/components/MediaWidget/MediaItemWidget.utils.test.ts +45 -2
  235. package/src/components/MediaWidget/MediaItemWidget.utils.ts +39 -6
  236. package/src/components/MediaWidget/MediaPreviewModal.tsx +9 -7
  237. package/src/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.css +19 -5
  238. package/src/components/MemoriArtifactSystem/components/ArtifactDrawer/ArtifactDrawer.tsx +4 -0
  239. package/src/components/MemoriWidget/MemoriWidget.css +4 -2
  240. package/src/components/MemoriWidget/MemoriWidget.tsx +818 -349
  241. package/src/components/SettingsDrawer/SettingsDrawer.tsx +3 -0
  242. package/src/components/StartPanel/StartPanel.stories.tsx +22 -0
  243. package/src/components/StartPanel/StartPanel.test.tsx +64 -1
  244. package/src/components/StartPanel/StartPanel.tsx +3 -0
  245. package/src/components/StartPanel/__snapshots__/StartPanel.test.tsx.snap +261 -0
  246. package/src/components/UploadButton/UploadButton.tsx +30 -11
  247. package/src/components/UploadButton/UploadDocuments/UploadDocuments.tsx +151 -61
  248. package/src/components/UploadButton/UploadImages/UploadImages.tsx +3 -0
  249. package/src/components/UploadButton/__snapshots__/UploadButton.test.tsx.snap +2 -2
  250. package/src/components/WhyThisAnswer/WhyThisAnswer.tsx +3 -0
  251. package/src/components/layouts/WebsiteAssistant/WebsiteAssistant.tsx +4 -0
  252. package/src/components/layouts/WebsiteAssistant/__snapshots__/WebsiteAssistant.test.tsx.snap +48 -44
  253. package/src/components/layouts/WebsiteAssistant/website-assistant.css +21 -1
  254. package/src/components/layouts/__snapshots__/Chat.test.tsx.snap +533 -529
  255. package/src/components/layouts/__snapshots__/FullPage.test.tsx.snap +1058 -1050
  256. package/src/components/layouts/__snapshots__/HiddenChat.test.tsx.snap +443 -439
  257. package/src/components/layouts/__snapshots__/Totem.test.tsx.snap +584 -580
  258. package/src/components/layouts/__snapshots__/ZoomedFullBody.test.tsx.snap +528 -524
  259. package/src/components/layouts/chat.css +2 -1
  260. package/src/components/layouts/fullpage.css +31 -8
  261. package/src/components/layouts/hidden-chat.css +1 -0
  262. package/src/components/layouts/layouts.stories.tsx +131 -12
  263. package/src/components/layouts/totem.css +2 -1
  264. package/src/components/layouts/zoomed-full-body.css +32 -7
  265. package/src/context/widgetSurfaceContext.tsx +14 -0
  266. package/src/helpers/constants.ts +32 -1
  267. package/src/helpers/credits.ts +16 -1
  268. package/src/helpers/message.test.ts +28 -1
  269. package/src/helpers/message.ts +4 -4
  270. package/src/helpers/nats/getNatsConfig.ts +145 -0
  271. package/src/helpers/nats/isSessionExpiredError.test.ts +38 -0
  272. package/src/helpers/nats/isSessionExpiredError.ts +51 -0
  273. package/src/helpers/nats/useNats.ts +124 -0
  274. package/src/helpers/nats/useNatsSession.ts +394 -0
  275. package/src/helpers/utils.test.ts +162 -0
  276. package/src/helpers/utils.ts +108 -3
  277. package/src/index.stories.tsx +32 -0
  278. package/src/locales/de.json +1 -0
  279. package/src/locales/en.json +1 -0
  280. package/src/locales/es.json +1 -0
  281. package/src/locales/fr.json +1 -0
  282. package/src/locales/it.json +1 -0
  283. package/src/styles.css +61 -1
  284. package/src/types/integration.test.ts +32 -0
  285. package/src/types/integration.ts +31 -0
  286. package/src/version.ts +1 -1
@@ -7,6 +7,7 @@ import memoriApiClient from '@memori.ai/memori-api-client';
7
7
  import cx from 'classnames';
8
8
  import { DateTime } from 'luxon';
9
9
  import { useAlertManager, createAlertOptions, MemoriUIProvider, } from '@memori.ai/ui';
10
+ import { WidgetSurfaceProvider } from '../../context/widgetSurfaceContext';
10
11
  import MemoriAuth from '../Auth/Auth';
11
12
  import Chat from '../Chat/Chat';
12
13
  import StartPanel from '../StartPanel/StartPanel';
@@ -37,6 +38,8 @@ import { sanitizeText } from '../../helpers/sanitizer';
37
38
  import { useTTS } from '../../helpers/tts/useTTS';
38
39
  import ChatHistoryDrawer from '../ChatHistoryDrawer/ChatHistory';
39
40
  import { useSTT } from '../../helpers/stt/useSTT';
41
+ import { useNats } from '../../helpers/nats/useNats';
42
+ import { isSessionExpiredNatsError, isSessionExpiredNatsResponse, } from '../../helpers/nats/isSessionExpiredError';
40
43
  const getMemoriState = (integrationId) => {
41
44
  var _a, _b, _c, _d, _f;
42
45
  let widget = integrationId
@@ -58,12 +61,23 @@ const getMemoriState = (integrationId) => {
58
61
  loginToken,
59
62
  };
60
63
  };
64
+ const resolveLoginTokenValue = (loginToken, userTokenRef, callAdditionalInfoLoginToken, additionalInfoLoginToken, authTokenProp) => {
65
+ var _a, _b, _c;
66
+ return (_c = (_b = (_a = loginToken !== null && loginToken !== void 0 ? loginToken : userTokenRef) !== null && _a !== void 0 ? _a : callAdditionalInfoLoginToken) !== null && _b !== void 0 ? _b : additionalInfoLoginToken) !== null && _c !== void 0 ? _c : authTokenProp;
67
+ };
61
68
  const NULL_PLACE_SPEC = {
62
69
  placeName: null,
63
70
  latitude: null,
64
71
  longitude: null,
65
72
  uncertaintyKm: null,
66
73
  };
74
+ const logWidgetError = (context, detail) => {
75
+ console.error(`[MemoriWidget] ${context}`, detail !== null && detail !== void 0 ? detail : '');
76
+ };
77
+ function readCorrelationID(response) {
78
+ const value = response.correlationID;
79
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
80
+ }
67
81
  const typeMessage = (message, waitForPrevious = true, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false) => {
68
82
  const e = new CustomEvent('MemoriTextEntered', {
69
83
  detail: {
@@ -159,7 +173,6 @@ window.typeMessageHidden = typeMessageHidden;
159
173
  window.typeBatchMessages = typeBatchMessages;
160
174
  let audioContext;
161
175
  let memoriPassword;
162
- let userToken;
163
176
  export function getChatStyles(config) {
164
177
  var _a;
165
178
  const primary = config === null || config === void 0 ? void 0 : config.buttonBgColor;
@@ -193,10 +206,11 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
193
206
  setIsClient(true);
194
207
  }, []);
195
208
  const client = memoriApiClient(apiURL, engineURL);
196
- const { initSession, deleteSession, postTextEnteredEvent, postPlaceChangedEvent, postDateChangedEvent, postTagChangedEvent, getSession, getExpertReferences, getSessionChatLogs, } = client;
209
+ const { initSession, deleteSession, postEnterTextAsync, postTextEnteredEvent, postPlaceChangedEvent, postDateChangedEvent, postTagChangedEvent, getSession, getExpertReferences, getSessionChatLogs, } = client;
197
210
  const [instruct, setInstruct] = useState(false);
198
211
  const [enableFocusChatInput, setEnableFocusChatInput] = useState(true);
199
212
  const [widgetRootEl, setWidgetRootEl] = useState(null);
213
+ const [widgetSurfaceEl, setWidgetSurfaceEl] = useState(null);
200
214
  const [isDarkTheme, setIsDarkTheme] = useState(false);
201
215
  useEffect(() => {
202
216
  var _a;
@@ -216,35 +230,64 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
216
230
  return () => observer.disconnect();
217
231
  }, [widgetRootEl]);
218
232
  const [loginToken, setLoginToken] = useState((_a = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _a !== void 0 ? _a : authToken);
233
+ const userTokenRef = useRef((_b = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _b !== void 0 ? _b : authToken);
234
+ const prevPropsLoginTokenRef = useRef((_c = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _c !== void 0 ? _c : authToken);
219
235
  const [user, setUser] = useState({
220
236
  avatarURL: typeof userAvatar === 'string' ? userAvatar : undefined,
221
237
  });
238
+ const resolveLoginToken = useCallback((callAdditionalInfoLoginToken) => resolveLoginTokenValue(loginToken, userTokenRef.current, callAdditionalInfoLoginToken, additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken, authToken), [loginToken, additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken, authToken]);
222
239
  useEffect(() => {
223
- if (loginToken &&
224
- !(user === null || user === void 0 ? void 0 : user.userID) &&
225
- (showLogin || memori.requireLoginToken)) {
226
- client.backend
227
- .pwlGetCurrentUser(loginToken)
228
- .then(({ user, resultCode }) => {
229
- if (user && resultCode === 0) {
230
- setUser(user);
231
- setLocalConfig('loginToken', loginToken);
232
- if (!birthDate && user.birthDate) {
233
- setBirthDate(user.birthDate);
234
- setLocalConfig('birthDate', user.birthDate);
235
- }
236
- }
237
- else {
238
- removeLocalConfig('loginToken');
239
- }
240
- });
240
+ var _a;
241
+ const incomingToken = (_a = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _a !== void 0 ? _a : authToken;
242
+ const prevPropsToken = prevPropsLoginTokenRef.current;
243
+ prevPropsLoginTokenRef.current = incomingToken;
244
+ if (incomingToken !== prevPropsToken) {
245
+ setLoginToken(incomingToken);
246
+ userTokenRef.current = incomingToken;
247
+ if (!incomingToken) {
248
+ removeLocalConfig('loginToken');
249
+ setUser(undefined);
250
+ }
241
251
  }
242
- }, [loginToken, user === null || user === void 0 ? void 0 : user.userID]);
252
+ }, [additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken, authToken]);
253
+ useEffect(() => {
254
+ if (!loginToken || !(showLogin || memori.requireLoginToken)) {
255
+ return;
256
+ }
257
+ let cancelled = false;
258
+ client.backend
259
+ .pwlGetCurrentUser(loginToken)
260
+ .then(({ user: fetchedUser, resultCode }) => {
261
+ if (cancelled)
262
+ return;
263
+ if (fetchedUser && resultCode === 0) {
264
+ setUser(fetchedUser);
265
+ setLocalConfig('loginToken', loginToken);
266
+ userTokenRef.current = loginToken;
267
+ if (!birthDate && fetchedUser.birthDate) {
268
+ setBirthDate(fetchedUser.birthDate);
269
+ setLocalConfig('birthDate', fetchedUser.birthDate);
270
+ }
271
+ }
272
+ else {
273
+ setLoginToken(undefined);
274
+ userTokenRef.current = undefined;
275
+ setUser(undefined);
276
+ removeLocalConfig('loginToken');
277
+ }
278
+ });
279
+ return () => {
280
+ cancelled = true;
281
+ };
282
+ }, [loginToken, showLogin, memori.requireLoginToken]);
243
283
  const [showLoginDrawer, setShowLoginDrawer] = useState(false);
244
284
  const [clickedStart, setClickedStart] = useState(false);
245
285
  const [gotErrorInOpening, setGotErrorInOpening] = useState(false);
246
- const language = ((_d = (_c = (_b = memori.culture) === null || _b === void 0 ? void 0 : _b.split('-')) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.toUpperCase()) ||
247
- ((_j = (_h = (_g = (_f = memoriConfigs === null || memoriConfigs === void 0 ? void 0 : memoriConfigs.find(c => c.memoriConfigID === memori.memoriConfigurationID)) === null || _f === void 0 ? void 0 : _f.culture) === null || _g === void 0 ? void 0 : _g.split('-')) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.toUpperCase());
286
+ const sessionStartingRef = useRef(false);
287
+ const needsCredits = tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation;
288
+ const [hasEnoughCredits, setHasEnoughCredits] = useState(true);
289
+ const language = ((_g = (_f = (_d = memori.culture) === null || _d === void 0 ? void 0 : _d.split('-')) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.toUpperCase()) ||
290
+ ((_l = (_k = (_j = (_h = memoriConfigs === null || memoriConfigs === void 0 ? void 0 : memoriConfigs.find(c => c.memoriConfigID === memori.memoriConfigurationID)) === null || _h === void 0 ? void 0 : _h.culture) === null || _j === void 0 ? void 0 : _j.split('-')) === null || _k === void 0 ? void 0 : _k[0]) === null || _l === void 0 ? void 0 : _l.toUpperCase());
248
291
  const integrationConfig = (integration === null || integration === void 0 ? void 0 : integration.customData)
249
292
  ? JSON.parse(integration.customData)
250
293
  : null;
@@ -252,7 +295,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
252
295
  ? multilingual
253
296
  : !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.multilanguage);
254
297
  const forcedTimeout = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.forcedTimeout;
255
- const [userLang, setUserLang] = useState((_p = (_o = (_m = (_l = (_k = spokenLang !== null && spokenLang !== void 0 ? spokenLang : memoriLang) !== null && _k !== void 0 ? _k : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.lang) !== null && _l !== void 0 ? _l : language) !== null && _m !== void 0 ? _m : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.uiLang) !== null && _o !== void 0 ? _o : i18n.language) !== null && _p !== void 0 ? _p : 'IT');
298
+ const [userLang, setUserLang] = useState((_r = (_q = (_p = (_o = (_m = spokenLang !== null && spokenLang !== void 0 ? spokenLang : memoriLang) !== null && _m !== void 0 ? _m : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.lang) !== null && _o !== void 0 ? _o : language) !== null && _p !== void 0 ? _p : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.uiLang) !== null && _q !== void 0 ? _q : i18n.language) !== null && _r !== void 0 ? _r : 'IT');
256
299
  useEffect(() => {
257
300
  if (spokenLang != null) {
258
301
  setUserLang(spokenLang);
@@ -278,6 +321,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
278
321
  const [loading, setLoading] = useState(false);
279
322
  const [memoriTyping, setMemoriTyping] = useState(false);
280
323
  const [typingText, setTypingText] = useState();
324
+ const pendingEnterTextRef = useRef(new Map());
325
+ const bufferedNatsResponsesRef = useRef(new Map());
281
326
  const layoutName = typeof layout === 'string'
282
327
  ? layout
283
328
  : layout &&
@@ -288,7 +333,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
288
333
  ? layout.name
289
334
  : typeof (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === 'string'
290
335
  ? integrationConfig.layout
291
- : (_q = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _q === void 0 ? void 0 : _q.name;
336
+ : (_s = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _s === void 0 ? void 0 : _s.name;
292
337
  const selectedLayout = (() => {
293
338
  if (typeof layoutName === 'string') {
294
339
  const lower = layoutName.toLowerCase();
@@ -316,14 +361,14 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
316
361
  typeof layout === 'object' &&
317
362
  layout !== null &&
318
363
  'piiDetection' in layout &&
319
- ((_r = layout.piiDetection) === null || _r === void 0 ? void 0 : _r.enabled)
364
+ ((_t = layout.piiDetection) === null || _t === void 0 ? void 0 : _t.enabled)
320
365
  ? layout.piiDetection
321
366
  : typeof (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === 'object' &&
322
367
  (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) !== null &&
323
- ((_t = (_s = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _s === void 0 ? void 0 : _s.piiDetection) === null || _t === void 0 ? void 0 : _t.enabled)
368
+ ((_v = (_u = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _u === void 0 ? void 0 : _u.piiDetection) === null || _v === void 0 ? void 0 : _v.enabled)
324
369
  ? integrationConfig.layout.piiDetection
325
370
  : undefined;
326
- const defaultEnableAudio = (_u = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _u !== void 0 ? _u : true;
371
+ const defaultEnableAudio = (_w = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _w !== void 0 ? _w : true;
327
372
  const [hasUserActivatedListening, setHasUserActivatedListening] = useState(false);
328
373
  const [hasUserTypedMessage, setHasUserTypedMessage] = useState(false);
329
374
  const [positionPopoverOpen, setPositionPopoverOpenState] = useState(false);
@@ -366,7 +411,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
366
411
  setRuntimeShowMessageConsumption(getLocalConfig('showMessageConsumption', (_a = showMessageConsumption !== null && showMessageConsumption !== void 0 ? showMessageConsumption : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showMessageConsumption) !== null && _a !== void 0 ? _a : false));
367
412
  if (!(additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) && !authToken) {
368
413
  setLoginToken(getLocalConfig('loginToken', undefined));
369
- userToken = getLocalConfig('loginToken', undefined);
414
+ userTokenRef.current = getLocalConfig('loginToken', undefined);
370
415
  setBirthDate(getLocalConfig('birthDate', undefined));
371
416
  }
372
417
  if (!((_b = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _b !== void 0 ? _b : true)) {
@@ -464,8 +509,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
464
509
  });
465
510
  };
466
511
  const [chatLogID, setChatLogID] = useState(undefined);
467
- const sendMessage = async (text, media, newSessionId, translate = true, translatedText, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false) => {
468
- var _a, _b, _c, _d, _f, _g;
512
+ const sendMessage = async (text, media, newSessionId, translate = true, translatedText, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false, skipHistoryPush = false) => {
513
+ var _a, _b;
469
514
  const sessionID = newSessionId ||
470
515
  sessionId ||
471
516
  ((_a = window.getMemoriState()) === null || _a === void 0 ? void 0 : _a.sessionID);
@@ -509,7 +554,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
509
554
  return;
510
555
  }
511
556
  }
512
- if (!hidden)
557
+ if (!hidden && !skipHistoryPush)
513
558
  pushMessage({
514
559
  text: text,
515
560
  translatedText,
@@ -519,12 +564,10 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
519
564
  ? !!newSessionId && newSessionId !== sessionId
520
565
  : !!newSessionId,
521
566
  });
522
- setMemoriTyping(true);
523
- setTypingText(typingText);
524
567
  let gotError = false;
525
568
  try {
526
569
  const placeSpec = getPlaceSpecForEnterText(position);
527
- const { currentState, ...response } = await postTextEnteredEvent({
570
+ const response = await postEnterTextAsync({
528
571
  sessionId: sessionID,
529
572
  text: msg,
530
573
  ...(memori.needsDateTime && {
@@ -532,65 +575,37 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
532
575
  }),
533
576
  ...(placeSpec !== undefined && { place: placeSpec }),
534
577
  });
535
- if (response.resultCode === 0 && currentState) {
536
- setChatLogID(undefined);
537
- const emission = useLoaderTextAsMsg && typingText
538
- ? typingText
539
- : (_c = currentState.emission) !== null && _c !== void 0 ? _c : currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.emission;
540
- if (userLang.toLowerCase() !== language.toLowerCase() &&
541
- emission &&
542
- isMultilanguageEnabled) {
543
- currentState.emission = emission;
544
- translateDialogState(currentState, userLang, msg).then(ts => {
545
- let text = ts.translatedEmission || ts.emission;
546
- if (text && shouldPlayAudio(text)) {
547
- handleSpeak(text);
548
- }
549
- });
550
- }
551
- else {
552
- setCurrentDialogState({
553
- ...currentState,
554
- emission,
555
- });
556
- if (emission) {
557
- pushMessage({
558
- text: emission,
559
- emitter: currentState.emitter,
560
- media: (_d = currentState.emittedMedia) !== null && _d !== void 0 ? _d : currentState.media,
561
- llmUsage: currentState.llmUsage,
562
- fromUser: false,
563
- questionAnswered: msg,
564
- generatedByAI: !!currentState.completion,
565
- contextVars: currentState.contextVars,
566
- date: currentState.currentDate,
567
- placeName: currentState.currentPlaceName,
568
- placeLatitude: currentState.currentLatitude,
569
- placeLongitude: currentState.currentLongitude,
570
- placeUncertaintyKm: currentState.currentUncertaintyKm,
571
- tag: currentState.currentTag,
572
- memoryTags: currentState.memoryTags,
573
- });
574
- if (emission && shouldPlayAudio(emission)) {
575
- handleSpeak(emission);
576
- }
577
- }
578
- }
578
+ const correlationID = readCorrelationID(response);
579
+ if (response.resultCode === 0 && correlationID) {
580
+ registerPendingEnterText(correlationID, {
581
+ msg,
582
+ text,
583
+ media,
584
+ translate,
585
+ translatedText,
586
+ hidden,
587
+ typingText,
588
+ useLoaderTextAsMsg,
589
+ hasBatchQueued,
590
+ });
591
+ setMemoriTyping(true);
592
+ setTypingText(typingText);
593
+ }
594
+ else if (response.resultCode === 0) {
595
+ logWidgetError('enter-text missing correlationID', response);
579
596
  }
580
597
  else if (response.resultCode === 404) {
581
- setHistory(h => [...h.slice(0, h.length - 1)]);
582
- reopenSession(true, memoriPwd || memori.secretToken, memoriTokens, undefined, undefined, {
583
- LANG: userLang,
584
- PATHNAME: window.location.pathname,
585
- ROUTE: ((_g = (_f = window.location.pathname) === null || _f === void 0 ? void 0 : _f.split('/')) === null || _g === void 0 ? void 0 : _g.pop()) || '',
586
- ...(initialContextVars || {}),
587
- }, initialQuestion, undefined, undefined, undefined, undefined, true).then(state => {
588
- console.info('session timeout');
589
- if (state === null || state === void 0 ? void 0 : state.sessionID) {
590
- setTimeout(() => {
591
- sendMessage(text, media, state === null || state === void 0 ? void 0 : state.sessionID);
592
- }, 500);
593
- }
598
+ retryAfterExpiredSessionRef.current({
599
+ text,
600
+ media,
601
+ translate,
602
+ translatedText,
603
+ hidden,
604
+ typingText,
605
+ useLoaderTextAsMsg,
606
+ hasBatchQueued,
607
+ expiredSessionID: sessionID,
608
+ continueFromChatLogID: chatLogID,
594
609
  });
595
610
  }
596
611
  else if (response.resultCode === 500 && response.resultMessage) {
@@ -607,18 +622,12 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
607
622
  ]);
608
623
  }
609
624
  else {
610
- console.warn('[SEND_MESSAGE]', response);
611
625
  return Promise.reject(response);
612
626
  }
613
627
  }
614
628
  catch (error) {
615
- console.log('error', error);
616
- console.error(error);
617
629
  gotError = true;
618
- setTypingText(undefined);
619
- setMemoriTyping(false);
620
- }
621
- if (!hasBatchQueued) {
630
+ logWidgetError('sendMessage failed', error);
622
631
  setTypingText(undefined);
623
632
  setMemoriTyping(false);
624
633
  }
@@ -700,7 +709,6 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
700
709
  }
701
710
  }
702
711
  catch (error) {
703
- console.error('[TRANSLATE] Error during translation:', error);
704
712
  translatedState = { ...state, emission };
705
713
  translatedMsg = {
706
714
  text: emission,
@@ -808,7 +816,6 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
808
816
  try {
809
817
  setTimeout(() => {
810
818
  var _a;
811
- console.log('snippet', s);
812
819
  new Function((_a = s.content) !== null && _a !== void 0 ? _a : '')();
813
820
  setTimeout(() => {
814
821
  var _a, _b, _c;
@@ -817,8 +824,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
817
824
  }, 400);
818
825
  }, 1000);
819
826
  }
820
- catch (e) {
821
- console.warn(e);
827
+ catch (_a) {
822
828
  }
823
829
  });
824
830
  };
@@ -829,7 +835,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
829
835
  }
830
836
  }, [initialSessionID]);
831
837
  const fetchSession = async (params) => {
832
- var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l;
838
+ var _a, _b, _c, _d, _f, _g, _h;
833
839
  let storageBirthDate = getLocalConfig('birthDate', undefined);
834
840
  let userBirthDate = (_a = birthDate !== null && birthDate !== void 0 ? birthDate : params.birthDate) !== null && _a !== void 0 ? _a : storageBirthDate;
835
841
  if (!userBirthDate && !!minAge) {
@@ -843,6 +849,9 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
843
849
  setAuthModalState('password');
844
850
  return;
845
851
  }
852
+ if (!(await checkCredits({ notify: true }))) {
853
+ return;
854
+ }
846
855
  setLoading(true);
847
856
  try {
848
857
  let referral;
@@ -851,8 +860,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
851
860
  return window.location.href;
852
861
  })();
853
862
  }
854
- catch (err) {
855
- console.debug(err);
863
+ catch (_j) {
856
864
  }
857
865
  const session = await initSession({
858
866
  ...params,
@@ -861,8 +869,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
861
869
  pin: (_c = params.pin) !== null && _c !== void 0 ? _c : personification === null || personification === void 0 ? void 0 : personification.pin,
862
870
  additionalInfo: {
863
871
  ...(params.additionalInfo || additionalInfo || {}),
864
- loginToken: (_h = (_g = (_d = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _d !== void 0 ? _d : (_f = params.additionalInfo) === null || _f === void 0 ? void 0 : _f.loginToken) !== null && _g !== void 0 ? _g : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _h !== void 0 ? _h : authToken,
865
- language: ((_l = userLang !== null && userLang !== void 0 ? userLang : (_k = (_j = memori.culture) === null || _j === void 0 ? void 0 : _j.split('-')) === null || _k === void 0 ? void 0 : _k[0]) !== null && _l !== void 0 ? _l : 'IT').toLowerCase(),
872
+ loginToken: resolveLoginToken((_d = params.additionalInfo) === null || _d === void 0 ? void 0 : _d.loginToken),
873
+ language: ((_h = userLang !== null && userLang !== void 0 ? userLang : (_g = (_f = memori.culture) === null || _f === void 0 ? void 0 : _f.split('-')) === null || _g === void 0 ? void 0 : _g[0]) !== null && _h !== void 0 ? _h : 'IT').toLowerCase(),
866
874
  referral: referral,
867
875
  timeZoneOffset: new Date().getTimezoneOffset().toString(),
868
876
  },
@@ -891,7 +899,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
891
899
  }));
892
900
  setGotErrorInOpening(true);
893
901
  }
894
- else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 403) {
902
+ else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 403 && memori.privacyType !== 'PUBLIC') {
895
903
  setMemoriPwd(undefined);
896
904
  setAuthModalState('password');
897
905
  return session;
@@ -903,16 +911,15 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
903
911
  severity: 'error',
904
912
  duration: 0,
905
913
  }));
906
- setGotErrorInOpening(true);
907
914
  return session;
908
915
  }
909
916
  }
910
917
  catch (err) {
911
- console.error(err);
918
+ logWidgetError('fetchSession failed', err);
912
919
  }
913
920
  };
914
- const reopenSession = async (updateDialogState = false, password, recoveryTokens, tag, pin, initialContextVars, initialQuestion, birthDate, additionalInfoProp, continueFromChatLogID, continueFromSessionID, isSessionExpired) => {
915
- var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m;
921
+ const reopenSession = async (updateDialogState = false, password, recoveryTokens, tag, pin, initialContextVars, initialQuestion, birthDate, additionalInfoProp, continueFromChatLogID, continueFromSessionID, isSessionExpired, suppressHistoryUpdate) => {
922
+ var _a, _b, _c, _d, _f, _g, _h, _j;
916
923
  setLoading(true);
917
924
  let storageBirthDate = getLocalConfig('birthDate', undefined);
918
925
  let userBirthDate = birthDate !== null && birthDate !== void 0 ? birthDate : storageBirthDate;
@@ -930,14 +937,17 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
930
937
  setAuthModalState('password');
931
938
  return;
932
939
  }
940
+ if (!(await checkCredits({ notify: true }))) {
941
+ setLoading(false);
942
+ return null;
943
+ }
933
944
  let referral;
934
945
  try {
935
946
  referral = (() => {
936
947
  return window.location.href;
937
948
  })();
938
949
  }
939
- catch (err) {
940
- console.debug('[REOPEN_SESSION] Error getting referral:', err);
950
+ catch (_k) {
941
951
  }
942
952
  const { sessionID, currentState, ...response } = await initSession({
943
953
  memoriID: (_a = memori.engineMemoriID) !== null && _a !== void 0 ? _a : '',
@@ -957,21 +967,32 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
957
967
  birthDate: userBirthDate,
958
968
  additionalInfo: {
959
969
  ...(additionalInfoProp || additionalInfo || {}),
960
- loginToken: (_g = (_f = (_d = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _d !== void 0 ? _d : additionalInfoProp === null || additionalInfoProp === void 0 ? void 0 : additionalInfoProp.loginToken) !== null && _f !== void 0 ? _f : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _g !== void 0 ? _g : authToken,
961
- language: ((_k = userLang !== null && userLang !== void 0 ? userLang : (_j = (_h = memori.culture) === null || _h === void 0 ? void 0 : _h.split('-')) === null || _j === void 0 ? void 0 : _j[0]) !== null && _k !== void 0 ? _k : 'IT').toLowerCase(),
970
+ loginToken: resolveLoginToken(additionalInfoProp === null || additionalInfoProp === void 0 ? void 0 : additionalInfoProp.loginToken),
971
+ language: ((_g = userLang !== null && userLang !== void 0 ? userLang : (_f = (_d = memori.culture) === null || _d === void 0 ? void 0 : _d.split('-')) === null || _f === void 0 ? void 0 : _f[0]) !== null && _g !== void 0 ? _g : 'IT').toLowerCase(),
962
972
  referral: referral,
963
973
  timeZoneOffset: new Date().getTimezoneOffset().toString(),
964
974
  },
965
975
  });
966
976
  if (sessionID && currentState && response.resultCode === 0) {
967
- console.log('[REOPEN_SESSION] Session initialized successfully:', sessionID);
968
977
  setSessionId(sessionID);
969
978
  if (updateDialogState) {
970
979
  setCurrentDialogState(currentState);
971
- if (currentState.emission) {
972
- console.log('[REOPEN_SESSION] Processing emission:', currentState.emission);
973
- const initialStatus = isSessionExpired && history.length > 1
974
- ? 'Session Expired, reopening session'
980
+ const sessionExpiredStatus = isSessionExpired && history.length > 1
981
+ ? t('sessionExpiredReopening')
982
+ : null;
983
+ if (sessionExpiredStatus && suppressHistoryUpdate) {
984
+ pushMessage({
985
+ text: '',
986
+ emitter: 'system',
987
+ fromUser: false,
988
+ initial: sessionExpiredStatus,
989
+ contextVars: {},
990
+ date: new Date().toISOString(),
991
+ });
992
+ }
993
+ if (currentState.emission && !suppressHistoryUpdate) {
994
+ const initialStatus = sessionExpiredStatus
995
+ ? sessionExpiredStatus
975
996
  : history.length <= 1
976
997
  ? true
977
998
  : undefined;
@@ -980,7 +1001,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
980
1001
  {
981
1002
  text: currentState.emission,
982
1003
  emitter: currentState.emitter,
983
- media: (_l = currentState.emittedMedia) !== null && _l !== void 0 ? _l : currentState.media,
1004
+ media: (_h = currentState.emittedMedia) !== null && _h !== void 0 ? _h : currentState.media,
984
1005
  fromUser: false,
985
1006
  initial: (initialStatus === true
986
1007
  ? true
@@ -998,7 +1019,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
998
1019
  : pushMessage({
999
1020
  text: currentState.emission,
1000
1021
  emitter: currentState.emitter,
1001
- media: (_m = currentState.emittedMedia) !== null && _m !== void 0 ? _m : currentState.media,
1022
+ media: (_j = currentState.emittedMedia) !== null && _j !== void 0 ? _j : currentState.media,
1002
1023
  fromUser: false,
1003
1024
  initial: (initialStatus === true
1004
1025
  ? true
@@ -1028,8 +1049,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1028
1049
  }));
1029
1050
  setGotErrorInOpening(true);
1030
1051
  }
1031
- else if ((response === null || response === void 0 ? void 0 : response.resultCode) === 403) {
1032
- console.error('[REOPEN_SESSION] Authentication error');
1052
+ else if ((response === null || response === void 0 ? void 0 : response.resultCode) === 403 &&
1053
+ memori.privacyType !== 'PUBLIC') {
1033
1054
  setMemoriPwd(undefined);
1034
1055
  setAuthModalState('password');
1035
1056
  }
@@ -1043,15 +1064,61 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1043
1064
  }
1044
1065
  }
1045
1066
  catch (err) {
1046
- console.error('[REOPEN_SESSION] Caught error:', err);
1067
+ logWidgetError('reopenSession failed', err);
1047
1068
  }
1048
1069
  setLoading(false);
1049
1070
  return null;
1050
1071
  };
1072
+ const retryAfterExpiredSessionRef = useRef(() => Promise.resolve(null));
1073
+ retryAfterExpiredSessionRef.current = (params) => {
1074
+ const { text, media, translate = true, translatedText, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false, expiredSessionID, continueFromChatLogID: continueFromChatLogIDParam, } = params;
1075
+ const continueFromSessionID = expiredSessionID !== null && expiredSessionID !== void 0 ? expiredSessionID : sessionId;
1076
+ const continueFromChatLogID = continueFromChatLogIDParam !== null && continueFromChatLogIDParam !== void 0 ? continueFromChatLogIDParam : chatLogID;
1077
+ const reopenAfterExpiry = () => {
1078
+ var _a, _b;
1079
+ return reopenSession(true, memoriPwd || memori.secretToken, memoriTokens, undefined, undefined, {
1080
+ LANG: userLang,
1081
+ PATHNAME: window.location.pathname,
1082
+ ROUTE: ((_b = (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.split('/')) === null || _b === void 0 ? void 0 : _b.pop()) || '',
1083
+ ...(initialContextVars || {}),
1084
+ }, initialQuestion, undefined, undefined, continueFromChatLogID, continueFromSessionID, true, true);
1085
+ };
1086
+ const scheduleRetry = (newSessionID) => {
1087
+ setTimeout(() => {
1088
+ sendMessage(text, media, newSessionID, translate, translatedText, hidden, typingText, useLoaderTextAsMsg, hasBatchQueued, true);
1089
+ }, 500);
1090
+ };
1091
+ const handleReopenFailure = (state) => {
1092
+ setMemoriTyping(false);
1093
+ setTypingText(undefined);
1094
+ if (state === null && text && !hidden) {
1095
+ add(createAlertOptions({
1096
+ description: t('errors.SESSION_EXPIRED'),
1097
+ severity: 'error',
1098
+ }));
1099
+ }
1100
+ };
1101
+ if (!text) {
1102
+ return reopenAfterExpiry().then(state => {
1103
+ if (!(state === null || state === void 0 ? void 0 : state.sessionID)) {
1104
+ handleReopenFailure(state);
1105
+ }
1106
+ return state;
1107
+ });
1108
+ }
1109
+ return reopenAfterExpiry().then(state => {
1110
+ if (state === null || state === void 0 ? void 0 : state.sessionID) {
1111
+ scheduleRetry(state.sessionID);
1112
+ }
1113
+ else {
1114
+ handleReopenFailure(state);
1115
+ }
1116
+ return state;
1117
+ });
1118
+ };
1051
1119
  const changeTag = async (memoriId, sessionId, tag, pin) => {
1052
- var _a, _b, _c, _d, _f, _g, _h, _j, _k;
1120
+ var _a, _b, _c, _d, _f, _g, _h;
1053
1121
  if (!memoriId || !sessionId) {
1054
- console.error('CHANGETAG/Session not found');
1055
1122
  return Promise.reject('Session not found');
1056
1123
  }
1057
1124
  try {
@@ -1083,7 +1150,6 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1083
1150
  }
1084
1151
  }
1085
1152
  else if ([400, 401, 403, 404, 500].includes(resultCode)) {
1086
- console.warn('[APPCONTEXT/CHANGETAG]', resultCode);
1087
1153
  let storageBirthDate = getLocalConfig('birthDate', undefined);
1088
1154
  let referral;
1089
1155
  try {
@@ -1091,8 +1157,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1091
1157
  return window.location.href;
1092
1158
  })();
1093
1159
  }
1094
- catch (err) {
1095
- console.debug(err);
1160
+ catch (_j) {
1096
1161
  }
1097
1162
  fetchSession({
1098
1163
  memoriID: (_b = memori.engineMemoriID) !== null && _b !== void 0 ? _b : '',
@@ -1109,8 +1174,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1109
1174
  birthDate: birthDate || storageBirthDate || undefined,
1110
1175
  additionalInfo: {
1111
1176
  ...(additionalInfo || {}),
1112
- loginToken: (_g = (_f = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _f !== void 0 ? _f : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _g !== void 0 ? _g : authToken,
1113
- language: ((_k = userLang !== null && userLang !== void 0 ? userLang : (_j = (_h = memori.culture) === null || _h === void 0 ? void 0 : _h.split('-')) === null || _j === void 0 ? void 0 : _j[0]) !== null && _k !== void 0 ? _k : 'IT').toLowerCase(),
1177
+ loginToken: resolveLoginToken(),
1178
+ language: ((_h = userLang !== null && userLang !== void 0 ? userLang : (_g = (_f = memori.culture) === null || _f === void 0 ? void 0 : _f.split('-')) === null || _g === void 0 ? void 0 : _g[0]) !== null && _h !== void 0 ? _h : 'IT').toLowerCase(),
1114
1179
  referral: referral,
1115
1180
  timeZoneOffset: new Date().getTimezoneOffset().toString(),
1116
1181
  },
@@ -1127,7 +1192,6 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1127
1192
  }
1128
1193
  catch (_e) {
1129
1194
  let err = _e;
1130
- console.warn('[APPCONTEXT/CHANGETAG]', err);
1131
1195
  return Promise.reject(err);
1132
1196
  }
1133
1197
  return null;
@@ -1148,6 +1212,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1148
1212
  return () => {
1149
1213
  setHasUserActivatedSpeak(false);
1150
1214
  setClickedStart(false);
1215
+ sessionStartingRef.current = false;
1151
1216
  clearInteractionTimeout();
1152
1217
  timeoutRef.current = undefined;
1153
1218
  };
@@ -1174,10 +1239,9 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1174
1239
  apiUrl: `${baseUrl}/api/tts`,
1175
1240
  continuousSpeech: continuousSpeech,
1176
1241
  preview: preview,
1177
- }, autoStart, defaultEnableAudio, (_v = defaultSpeakerActive !== null && defaultSpeakerActive !== void 0 ? defaultSpeakerActive : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.defaultSpeakerActive) !== null && _v !== void 0 ? _v : true);
1242
+ }, autoStart, defaultEnableAudio, (_x = defaultSpeakerActive !== null && defaultSpeakerActive !== void 0 ? defaultSpeakerActive : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.defaultSpeakerActive) !== null && _x !== void 0 ? _x : true);
1178
1243
  const shouldPlayAudio = (text) => {
1179
1244
  const currentSpeakerMuted = getLocalConfig('muteSpeaker', !defaultEnableAudio);
1180
- console.log('[MemoriWidget] shouldPlayAudio', currentSpeakerMuted);
1181
1245
  return (text &&
1182
1246
  text.trim() &&
1183
1247
  !preview &&
@@ -1190,15 +1254,12 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1190
1254
  }
1191
1255
  try {
1192
1256
  const message = stripDuplicates(text);
1193
- console.debug('Processing speech message:', message);
1194
1257
  if (message.length > 0) {
1195
1258
  setUserMessage('');
1196
- console.debug('Sending message:', message);
1197
1259
  sendMessage(message);
1198
1260
  }
1199
1261
  }
1200
- catch (error) {
1201
- console.error('Error in processSpeechAndSendMessage:', error);
1262
+ catch (_a) {
1202
1263
  }
1203
1264
  };
1204
1265
  const { isListening, startRecording, stopRecording, } = useSTT(sttConfig, processSpeechAndSendMessage, {
@@ -1232,8 +1293,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1232
1293
  }
1233
1294
  return translatedState;
1234
1295
  }
1235
- catch (error) {
1236
- console.error('Error in translateAndSpeak:', error);
1296
+ catch (_a) {
1237
1297
  if (!hasUserActivatedSpeak) {
1238
1298
  setHasUserActivatedSpeak(true);
1239
1299
  }
@@ -1246,6 +1306,221 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1246
1306
  setHasUserActivatedSpeak,
1247
1307
  speakerMuted,
1248
1308
  ]);
1309
+ const processEnterTextDialogResponse = useCallback((event, pending) => {
1310
+ var _a, _b;
1311
+ const { msg, typingText: pendingTypingText, useLoaderTextAsMsg, } = pending;
1312
+ const currentState = event.currentState;
1313
+ if (event.resultCode !== 0 || !currentState) {
1314
+ if (isSessionExpiredNatsResponse(event) && pending.text) {
1315
+ setMemoriTyping(false);
1316
+ setTypingText(undefined);
1317
+ retryAfterExpiredSessionRef.current({
1318
+ text: pending.text,
1319
+ media: pending.media,
1320
+ translate: pending.translate,
1321
+ translatedText: pending.translatedText,
1322
+ hidden: pending.hidden,
1323
+ typingText: pending.typingText,
1324
+ useLoaderTextAsMsg: pending.useLoaderTextAsMsg,
1325
+ hasBatchQueued: pending.hasBatchQueued,
1326
+ expiredSessionID: sessionId,
1327
+ continueFromChatLogID: chatLogID,
1328
+ });
1329
+ return;
1330
+ }
1331
+ if (event.resultCode === 500 && event.resultMessage) {
1332
+ setHistory(h => [
1333
+ ...h,
1334
+ {
1335
+ text: 'Error: ' + event.resultMessage,
1336
+ emitter: 'system',
1337
+ fromUser: false,
1338
+ initial: false,
1339
+ contextVars: {},
1340
+ date: new Date().toISOString(),
1341
+ },
1342
+ ]);
1343
+ }
1344
+ return;
1345
+ }
1346
+ if (!msg) {
1347
+ return;
1348
+ }
1349
+ setChatLogID(undefined);
1350
+ const emission = useLoaderTextAsMsg && pendingTypingText
1351
+ ? pendingTypingText
1352
+ : (_a = currentState.emission) !== null && _a !== void 0 ? _a : currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.emission;
1353
+ if (userLang.toLowerCase() !== language.toLowerCase() &&
1354
+ emission &&
1355
+ isMultilanguageEnabled) {
1356
+ currentState.emission = emission;
1357
+ translateDialogState(currentState, userLang, msg).then(ts => {
1358
+ const text = ts.translatedEmission || ts.emission;
1359
+ if (text && shouldPlayAudio(text)) {
1360
+ handleSpeak(text);
1361
+ }
1362
+ });
1363
+ }
1364
+ else {
1365
+ setCurrentDialogState({
1366
+ ...currentState,
1367
+ emission,
1368
+ });
1369
+ if (emission) {
1370
+ pushMessage({
1371
+ text: emission,
1372
+ emitter: currentState.emitter,
1373
+ media: (_b = currentState.emittedMedia) !== null && _b !== void 0 ? _b : currentState.media,
1374
+ llmUsage: currentState.llmUsage,
1375
+ fromUser: false,
1376
+ questionAnswered: msg,
1377
+ generatedByAI: !!currentState.completion,
1378
+ contextVars: currentState.contextVars,
1379
+ date: currentState.currentDate,
1380
+ placeName: currentState.currentPlaceName,
1381
+ placeLatitude: currentState.currentLatitude,
1382
+ placeLongitude: currentState.currentLongitude,
1383
+ placeUncertaintyKm: currentState.currentUncertaintyKm,
1384
+ tag: currentState.currentTag,
1385
+ memoryTags: currentState.memoryTags,
1386
+ });
1387
+ if (emission && shouldPlayAudio(emission)) {
1388
+ handleSpeak(emission);
1389
+ }
1390
+ }
1391
+ }
1392
+ }, [
1393
+ userLang,
1394
+ language,
1395
+ isMultilanguageEnabled,
1396
+ currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.emission,
1397
+ translateDialogState,
1398
+ handleSpeak,
1399
+ shouldPlayAudio,
1400
+ ]);
1401
+ const clearEnterTextPending = useCallback((correlationID, pending) => {
1402
+ var _a;
1403
+ if ((_a = pending.waitForResponse) === null || _a === void 0 ? void 0 : _a.timeoutId) {
1404
+ clearTimeout(pending.waitForResponse.timeoutId);
1405
+ }
1406
+ pendingEnterTextRef.current.delete(correlationID);
1407
+ }, []);
1408
+ const deliverEnterTextNatsError = useCallback((event) => {
1409
+ var _a, _b, _c;
1410
+ const correlationID = event.correlationID;
1411
+ let pending;
1412
+ if (correlationID) {
1413
+ pending = pendingEnterTextRef.current.get(correlationID);
1414
+ if (pending) {
1415
+ clearEnterTextPending(correlationID, pending);
1416
+ (_a = pending.waitForResponse) === null || _a === void 0 ? void 0 : _a.reject(new Error((_b = event.errorMessage) !== null && _b !== void 0 ? _b : String((_c = event.errorCode) !== null && _c !== void 0 ? _c : 'NATS error')));
1417
+ }
1418
+ }
1419
+ if (isSessionExpiredNatsError(event) && (pending === null || pending === void 0 ? void 0 : pending.text)) {
1420
+ setMemoriTyping(false);
1421
+ setTypingText(undefined);
1422
+ retryAfterExpiredSessionRef.current({
1423
+ text: pending.text,
1424
+ media: pending.media,
1425
+ translate: pending.translate,
1426
+ translatedText: pending.translatedText,
1427
+ hidden: pending.hidden,
1428
+ typingText: pending.typingText,
1429
+ useLoaderTextAsMsg: pending.useLoaderTextAsMsg,
1430
+ hasBatchQueued: pending.hasBatchQueued,
1431
+ expiredSessionID: sessionId,
1432
+ continueFromChatLogID: chatLogID,
1433
+ });
1434
+ return;
1435
+ }
1436
+ const errorText = event.errorMessage
1437
+ ? `Error: ${event.errorMessage}`
1438
+ : event.errorCode
1439
+ ? `Error: ${event.errorCode}`
1440
+ : 'Error: An unexpected error occurred';
1441
+ pushMessage({
1442
+ text: errorText,
1443
+ emitter: 'system',
1444
+ fromUser: false,
1445
+ initial: false,
1446
+ contextVars: {},
1447
+ date: new Date().toISOString(),
1448
+ });
1449
+ setMemoriTyping(false);
1450
+ setTypingText(undefined);
1451
+ }, [clearEnterTextPending]);
1452
+ const deliverEnterTextNatsResponse = useCallback((correlationID, event) => {
1453
+ const pending = pendingEnterTextRef.current.get(correlationID);
1454
+ if (!pending) {
1455
+ bufferedNatsResponsesRef.current.set(correlationID, event);
1456
+ return;
1457
+ }
1458
+ clearEnterTextPending(correlationID, pending);
1459
+ if (pending.waitForResponse) {
1460
+ pending.waitForResponse.resolve(event);
1461
+ setMemoriTyping(false);
1462
+ setTypingText(undefined);
1463
+ return;
1464
+ }
1465
+ processEnterTextDialogResponse(event, pending);
1466
+ if (!pending.hasBatchQueued) {
1467
+ setMemoriTyping(false);
1468
+ setTypingText(undefined);
1469
+ }
1470
+ }, [processEnterTextDialogResponse, clearEnterTextPending]);
1471
+ const registerPendingEnterText = useCallback((correlationID, pending) => {
1472
+ const buffered = bufferedNatsResponsesRef.current.get(correlationID);
1473
+ if (buffered) {
1474
+ bufferedNatsResponsesRef.current.delete(correlationID);
1475
+ pendingEnterTextRef.current.set(correlationID, pending);
1476
+ deliverEnterTextNatsResponse(correlationID, buffered);
1477
+ return;
1478
+ }
1479
+ pendingEnterTextRef.current.set(correlationID, pending);
1480
+ }, [deliverEnterTextNatsResponse]);
1481
+ const waitForEnterTextNatsResponse = useCallback((correlationID, timeoutMs = 120000) => new Promise((resolve, reject) => {
1482
+ const timeoutId = setTimeout(() => {
1483
+ const current = pendingEnterTextRef.current.get(correlationID);
1484
+ if (current) {
1485
+ clearEnterTextPending(correlationID, current);
1486
+ }
1487
+ logWidgetError('NATS timeout', { correlationID, timeoutMs });
1488
+ reject(new Error('NATS enter-text response timeout'));
1489
+ }, timeoutMs);
1490
+ registerPendingEnterText(correlationID, {
1491
+ waitForResponse: {
1492
+ resolve: event => {
1493
+ clearTimeout(timeoutId);
1494
+ resolve(event);
1495
+ },
1496
+ reject: error => {
1497
+ clearTimeout(timeoutId);
1498
+ reject(error);
1499
+ },
1500
+ timeoutId,
1501
+ },
1502
+ });
1503
+ }), [registerPendingEnterText, clearEnterTextPending]);
1504
+ useNats({
1505
+ baseUrl,
1506
+ sessionId,
1507
+ onProgress: useCallback((event) => {
1508
+ if (event.message) {
1509
+ setTypingText(event.message);
1510
+ }
1511
+ }, []),
1512
+ onDialogResponse: useCallback((event) => {
1513
+ const correlationID = event.correlationID;
1514
+ if (!correlationID) {
1515
+ logWidgetError('NATS dialog response missing correlationID', event);
1516
+ setMemoriTyping(false);
1517
+ setTypingText(undefined);
1518
+ return;
1519
+ }
1520
+ deliverEnterTextNatsResponse(correlationID, event);
1521
+ }, [deliverEnterTextNatsResponse]),
1522
+ onError: deliverEnterTextNatsError,
1523
+ });
1249
1524
  const focusChatInput = () => {
1250
1525
  let textarea = document.querySelector('#chat-fieldset textarea');
1251
1526
  if (textarea && enableFocusChatInput) {
@@ -1267,7 +1542,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1267
1542
  timeoutRef.current = undefined;
1268
1543
  ttsStop();
1269
1544
  }
1270
- catch (e) {
1545
+ catch (_a) {
1271
1546
  }
1272
1547
  };
1273
1548
  useEffect(() => {
@@ -1430,7 +1705,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1430
1705
  };
1431
1706
  }, [sessionId, userLang, disableTextEnteredEvents]);
1432
1707
  const onClickStart = useCallback(async (session, initialSessionExpired = false, chatLog, targetSessionID) => {
1433
- var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1708
+ var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
1434
1709
  const sessionID = chatLog ? undefined : (session === null || session === void 0 ? void 0 : session.sessionID) || sessionId;
1435
1710
  const dialogState = chatLog
1436
1711
  ? undefined
@@ -1447,9 +1722,15 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1447
1722
  setPositionPopoverOpenState(true);
1448
1723
  return;
1449
1724
  }
1725
+ if (!(await checkCredits({ notify: true }))) {
1726
+ setClickedStart(false);
1727
+ setLoading(false);
1728
+ return;
1729
+ }
1450
1730
  if (!sessionID && !!minAge && !birth) {
1451
1731
  setShowAgeVerification(true);
1452
1732
  setClickedStart(false);
1733
+ return;
1453
1734
  }
1454
1735
  else if ((!sessionID &&
1455
1736
  memori.privacyType !== 'PUBLIC' &&
@@ -1462,83 +1743,95 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1462
1743
  return;
1463
1744
  }
1464
1745
  else if (!sessionID || initialSessionExpired) {
1465
- setClickedStart(false);
1466
1746
  setGotErrorInOpening(false);
1467
- const session = await fetchSession({
1468
- memoriID: memori.engineMemoriID,
1469
- password: secret || memoriPwd || memori.secretToken,
1470
- tag: personification === null || personification === void 0 ? void 0 : personification.tag,
1471
- pin: personification === null || personification === void 0 ? void 0 : personification.pin,
1472
- continueFromChatLogID: chatLog === null || chatLog === void 0 ? void 0 : chatLog.chatLogID,
1473
- initialContextVars: {
1474
- LANG: userLang,
1475
- PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
1476
- ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
1477
- ...((!chatLog
1478
- ? initialContextVars
1479
- : chatLog.lines[chatLog.lines.length - 1].contextVars) || {}),
1480
- },
1481
- initialQuestion: chatLog ? undefined : initialQuestion,
1482
- birthDate: birth,
1483
- additionalInfo: {
1484
- ...(additionalInfo || {}),
1485
- loginToken: (_g = (_f = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _f !== void 0 ? _f : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _g !== void 0 ? _g : authToken,
1486
- language: ((_k = userLang !== null && userLang !== void 0 ? userLang : (_j = (_h = memori.culture) === null || _h === void 0 ? void 0 : _h.split('-')) === null || _j === void 0 ? void 0 : _j[0]) !== null && _k !== void 0 ? _k : 'IT').toLowerCase(),
1487
- timeZoneOffset: new Date().getTimezoneOffset().toString(),
1488
- },
1489
- });
1490
- if (session === null || session === void 0 ? void 0 : session.dialogState) {
1491
- if (!chatLog) {
1492
- setHistory([]);
1493
- await translateAndSpeak(session.dialogState, userLang);
1494
- setHasUserActivatedSpeak(true);
1495
- }
1496
- else {
1497
- const messages = chatLog.lines.map((l, i) => {
1498
- var _a, _b;
1499
- return ({
1500
- text: l.text,
1501
- media: (_b = (_a = l.media) === null || _a === void 0 ? void 0 : _a.filter(m => allowedMediaTypes.includes(m.mimeType))) === null || _b === void 0 ? void 0 : _b.map(m => ({
1502
- mediumID: `${i}-${m.mimeType}`,
1503
- ...m,
1504
- })),
1505
- fromUser: l.inbound,
1506
- llmUsage: l.llmUsage,
1507
- timestamp: l.timestamp,
1508
- emitter: l.emitter,
1509
- initial: i === 0,
1510
- });
1511
- });
1512
- translatedMessages = messages !== null && messages !== void 0 ? messages : [];
1513
- if (language.toUpperCase() !== userLang.toUpperCase() &&
1514
- isMultilanguageEnabled) {
1515
- try {
1516
- translatedMessages = await Promise.all(messages.map(async (m) => {
1517
- if ('originalText' in m && m.originalText) {
1518
- return m;
1519
- }
1520
- return {
1747
+ if (sessionStartingRef.current) {
1748
+ return;
1749
+ }
1750
+ sessionStartingRef.current = true;
1751
+ try {
1752
+ const session = await fetchSession({
1753
+ memoriID: memori.engineMemoriID,
1754
+ password: secret || memoriPwd || memori.secretToken,
1755
+ tag: personification === null || personification === void 0 ? void 0 : personification.tag,
1756
+ pin: personification === null || personification === void 0 ? void 0 : personification.pin,
1757
+ continueFromChatLogID: chatLog === null || chatLog === void 0 ? void 0 : chatLog.chatLogID,
1758
+ initialContextVars: {
1759
+ LANG: userLang,
1760
+ PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
1761
+ ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) ||
1762
+ '',
1763
+ ...((!chatLog
1764
+ ? initialContextVars
1765
+ : chatLog.lines[chatLog.lines.length - 1].contextVars) || {}),
1766
+ },
1767
+ initialQuestion: chatLog ? undefined : initialQuestion,
1768
+ birthDate: birth,
1769
+ additionalInfo: {
1770
+ ...(additionalInfo || {}),
1771
+ loginToken: resolveLoginToken(),
1772
+ language: ((_h = userLang !== null && userLang !== void 0 ? userLang : (_g = (_f = memori.culture) === null || _f === void 0 ? void 0 : _f.split('-')) === null || _g === void 0 ? void 0 : _g[0]) !== null && _h !== void 0 ? _h : 'IT').toLowerCase(),
1773
+ timeZoneOffset: new Date().getTimezoneOffset().toString(),
1774
+ },
1775
+ });
1776
+ if (session === null || session === void 0 ? void 0 : session.dialogState) {
1777
+ if (!chatLog) {
1778
+ setHistory([]);
1779
+ await translateAndSpeak(session.dialogState, userLang);
1780
+ setHasUserActivatedSpeak(true);
1781
+ setClickedStart(false);
1782
+ }
1783
+ else {
1784
+ const messages = chatLog.lines.map((l, i) => {
1785
+ var _a, _b;
1786
+ return ({
1787
+ text: l.text,
1788
+ media: (_b = (_a = l.media) === null || _a === void 0 ? void 0 : _a.filter(m => allowedMediaTypes.includes(m.mimeType))) === null || _b === void 0 ? void 0 : _b.map(m => ({
1789
+ mediumID: `${i}-${m.mimeType}`,
1521
1790
  ...m,
1522
- originalText: m.text,
1523
- text: (await getTranslation(m.text, userLang, language, baseUrl)).text,
1524
- };
1525
- }));
1526
- }
1527
- catch (e) {
1528
- console.error('[onClickStart] Error translating messages:', e);
1791
+ })),
1792
+ fromUser: l.inbound,
1793
+ llmUsage: l.llmUsage,
1794
+ timestamp: l.timestamp,
1795
+ emitter: l.emitter,
1796
+ initial: i === 0,
1797
+ });
1798
+ });
1799
+ translatedMessages = messages !== null && messages !== void 0 ? messages : [];
1800
+ if (language.toUpperCase() !== userLang.toUpperCase() &&
1801
+ isMultilanguageEnabled) {
1802
+ try {
1803
+ translatedMessages = await Promise.all(messages.map(async (m) => {
1804
+ if ('originalText' in m && m.originalText) {
1805
+ return m;
1806
+ }
1807
+ return {
1808
+ ...m,
1809
+ originalText: m.text,
1810
+ text: (await getTranslation(m.text, userLang, language, baseUrl)).text,
1811
+ };
1812
+ }));
1813
+ }
1814
+ catch (_u) {
1815
+ }
1529
1816
  }
1817
+ setHistory(translatedMessages);
1818
+ translateDialogState(session.dialogState, userLang, undefined, true).finally(() => {
1819
+ setHasUserActivatedSpeak(true);
1820
+ setClickedStart(false);
1821
+ });
1530
1822
  }
1531
- setHistory(translatedMessages);
1532
- translateDialogState(session.dialogState, userLang, undefined, true).finally(() => {
1533
- setHasUserActivatedSpeak(true);
1534
- });
1823
+ }
1824
+ else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 0) {
1825
+ sessionStartingRef.current = false;
1826
+ await onClickStart(session || undefined);
1827
+ }
1828
+ else {
1829
+ setLoading(false);
1830
+ setClickedStart(false);
1535
1831
  }
1536
1832
  }
1537
- else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 0) {
1538
- await onClickStart(session || undefined);
1539
- }
1540
- else {
1541
- setLoading(false);
1833
+ finally {
1834
+ sessionStartingRef.current = false;
1542
1835
  }
1543
1836
  return;
1544
1837
  }
@@ -1547,9 +1840,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1547
1840
  const { currentState, ...response } = await getSession(sessionID);
1548
1841
  if (response.resultCode !== 0 || !currentState) {
1549
1842
  const { chatLogs } = await getSessionChatLogs(sessionID, sessionID);
1550
- setGotErrorInOpening(true);
1551
1843
  setSessionId(undefined);
1552
- setClickedStart(false);
1553
1844
  await onClickStart(undefined, true, chatLogs === null || chatLogs === void 0 ? void 0 : chatLogs[0]);
1554
1845
  return;
1555
1846
  }
@@ -1561,21 +1852,22 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1561
1852
  const session = await changeTag(memori.engineMemoriID, sessionID, personification.tag, personification.pin);
1562
1853
  if (session && session.resultCode === 0) {
1563
1854
  await translateAndSpeak(session.currentState, userLang);
1855
+ setClickedStart(false);
1564
1856
  }
1565
1857
  else {
1566
1858
  throw new Error('No session');
1567
1859
  }
1568
1860
  }
1569
- catch (e) {
1570
- console.error('[onClickStart] Error changing tag:', e);
1861
+ catch (_v) {
1571
1862
  reopenSession(true, memori === null || memori === void 0 ? void 0 : memori.secretToken, undefined, personification.tag, personification.pin, {
1572
1863
  LANG: userLang,
1573
- PATHNAME: (_l = window.location.pathname) === null || _l === void 0 ? void 0 : _l.toUpperCase(),
1574
- ROUTE: ((_p = (_o = (_m = window.location.pathname) === null || _m === void 0 ? void 0 : _m.split('/')) === null || _o === void 0 ? void 0 : _o.pop()) === null || _p === void 0 ? void 0 : _p.toUpperCase()) ||
1864
+ PATHNAME: (_j = window.location.pathname) === null || _j === void 0 ? void 0 : _j.toUpperCase(),
1865
+ ROUTE: ((_m = (_l = (_k = window.location.pathname) === null || _k === void 0 ? void 0 : _k.split('/')) === null || _l === void 0 ? void 0 : _l.pop()) === null || _m === void 0 ? void 0 : _m.toUpperCase()) ||
1575
1866
  '',
1576
1867
  ...(initialContextVars || {}),
1577
1868
  }, initialQuestion, birth).then(() => {
1578
1869
  setHasUserActivatedSpeak(true);
1870
+ setClickedStart(false);
1579
1871
  });
1580
1872
  }
1581
1873
  }
@@ -1588,6 +1880,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1588
1880
  const session = await changeTag(memori.engineMemoriID, sessionID, anonTag);
1589
1881
  if (session && session.resultCode === 0) {
1590
1882
  await translateAndSpeak(session.currentState, userLang);
1883
+ setClickedStart(false);
1591
1884
  }
1592
1885
  else {
1593
1886
  throw new Error('No session');
@@ -1596,19 +1889,20 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1596
1889
  catch (e) {
1597
1890
  reopenSession(true, memori === null || memori === void 0 ? void 0 : memori.secretToken, undefined, undefined, undefined, {
1598
1891
  LANG: userLang,
1599
- PATHNAME: (_q = window.location.pathname) === null || _q === void 0 ? void 0 : _q.toUpperCase(),
1600
- ROUTE: ((_t = (_s = (_r = window.location.pathname) === null || _r === void 0 ? void 0 : _r.split('/')) === null || _s === void 0 ? void 0 : _s.pop()) === null || _t === void 0 ? void 0 : _t.toUpperCase()) ||
1892
+ PATHNAME: (_o = window.location.pathname) === null || _o === void 0 ? void 0 : _o.toUpperCase(),
1893
+ ROUTE: ((_r = (_q = (_p = window.location.pathname) === null || _p === void 0 ? void 0 : _p.split('/')) === null || _q === void 0 ? void 0 : _q.pop()) === null || _r === void 0 ? void 0 : _r.toUpperCase()) ||
1601
1894
  '',
1602
1895
  ...(initialContextVars || {}),
1603
1896
  }, initialQuestion, birth).then(() => {
1604
1897
  setHasUserActivatedSpeak(true);
1898
+ setClickedStart(false);
1605
1899
  });
1606
1900
  }
1607
1901
  }
1608
1902
  else {
1609
1903
  try {
1610
1904
  const { chatLogs } = await getSessionChatLogs(sessionID, sessionID);
1611
- const messages = (_u = chatLogs === null || chatLogs === void 0 ? void 0 : chatLogs[0]) === null || _u === void 0 ? void 0 : _u.lines.map((l, i) => {
1905
+ const messages = (_s = chatLogs === null || chatLogs === void 0 ? void 0 : chatLogs[0]) === null || _s === void 0 ? void 0 : _s.lines.map((l, i) => {
1612
1906
  var _a, _b;
1613
1907
  return ({
1614
1908
  text: l.text,
@@ -1633,31 +1927,28 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1633
1927
  text: (await getTranslation(m.text, userLang, language, baseUrl)).text,
1634
1928
  })));
1635
1929
  }
1636
- catch (e) {
1637
- console.error('[onClickStart] Error translating messages:', e);
1930
+ catch (_w) {
1638
1931
  }
1639
1932
  }
1640
1933
  setHistory(translatedMessages);
1641
1934
  }
1642
- catch (e) {
1643
- console.error('[onClickStart] Error retrieving chat logs:', e);
1935
+ catch (_x) {
1644
1936
  }
1645
1937
  if ((!!(translatedMessages === null || translatedMessages === void 0 ? void 0 : translatedMessages.length) && translatedMessages.length > 1) ||
1646
1938
  !initialQuestion) {
1647
1939
  setHasUserActivatedSpeak(true);
1940
+ setClickedStart(false);
1648
1941
  await translateAndSpeak(currentState, userLang, undefined, !!(translatedMessages === null || translatedMessages === void 0 ? void 0 : translatedMessages.length));
1649
1942
  }
1650
1943
  else {
1651
- console.log('[onClickStart] Starting with initial question');
1652
1944
  translatedMessages = [];
1653
1945
  setHistory([]);
1654
- setMemoriTyping(true);
1655
1946
  const placeSpec = getPlaceSpecForEnterText(position);
1656
- const response = await postTextEnteredEvent({
1947
+ const response = await postEnterTextAsync({
1657
1948
  sessionId: sessionID,
1658
1949
  text: initialQuestion,
1659
1950
  ...(memori.needsDateTime && {
1660
- dateUTC: (_v = DateTime.utc().toISO()) !== null && _v !== void 0 ? _v : undefined,
1951
+ dateUTC: (_t = DateTime.utc().toISO()) !== null && _t !== void 0 ? _t : undefined,
1661
1952
  }),
1662
1953
  ...(placeSpec !== undefined && { place: placeSpec }),
1663
1954
  });
@@ -1673,16 +1964,34 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1673
1964
  date: new Date().toISOString(),
1674
1965
  },
1675
1966
  ]);
1676
- setMemoriTyping(false);
1677
1967
  return;
1678
1968
  }
1679
- await translateAndSpeak((_w = response.currentState) !== null && _w !== void 0 ? _w : currentState, userLang, undefined, false);
1969
+ const onClickStartCorrelationID = readCorrelationID(response);
1970
+ if (response.resultCode === 0 && onClickStartCorrelationID) {
1971
+ setMemoriTyping(true);
1972
+ try {
1973
+ const natsEvent = await waitForEnterTextNatsResponse(onClickStartCorrelationID);
1974
+ if (natsEvent.resultCode === 0 && natsEvent.currentState) {
1975
+ await translateAndSpeak(natsEvent.currentState, userLang, undefined, false);
1976
+ setClickedStart(false);
1977
+ }
1978
+ }
1979
+ catch (err) {
1980
+ logWidgetError('onClickStart NATS wait failed', err);
1981
+ setMemoriTyping(false);
1982
+ setTypingText(undefined);
1983
+ }
1984
+ }
1985
+ else if (response.resultCode === 0) {
1986
+ logWidgetError('onClickStart enter-text missing correlationID', response);
1987
+ }
1680
1988
  }
1681
1989
  }
1682
1990
  }
1683
1991
  else {
1684
1992
  setHistory([]);
1685
1993
  await translateAndSpeak(dialogState, userLang);
1994
+ setClickedStart(false);
1686
1995
  }
1687
1996
  }, [memoriPwd, memori, memoriTokens, birthDate, sessionId, userLang, position]);
1688
1997
  const setPositionPopoverOpen = useCallback((open) => {
@@ -1692,32 +2001,52 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1692
2001
  }
1693
2002
  }, [autoStart, onClickStart]);
1694
2003
  useEffect(() => {
1695
- if (!clickedStart && autoStart && selectedLayout !== 'HIDDEN_CHAT') {
2004
+ if (!clickedStart &&
2005
+ !sessionStartingRef.current &&
2006
+ !sessionId &&
2007
+ autoStart &&
2008
+ selectedLayout !== 'HIDDEN_CHAT' &&
2009
+ (!needsCredits || hasEnoughCredits)) {
1696
2010
  onClickStart();
1697
2011
  }
1698
- }, [clickedStart, autoStart, selectedLayout]);
2012
+ }, [
2013
+ clickedStart,
2014
+ autoStart,
2015
+ selectedLayout,
2016
+ sessionId,
2017
+ needsCredits,
2018
+ hasEnoughCredits,
2019
+ ]);
1699
2020
  useEffect(() => {
2021
+ var _a;
1700
2022
  const targetNode = document.querySelector(`memori-client[memoriname="${memori.name}"]`) ||
1701
2023
  document.querySelector(`memori-client[memoriid="${memori.memoriID}"]`) ||
1702
2024
  document.querySelector('memori-client');
1703
2025
  if (!targetNode) {
1704
2026
  return;
1705
2027
  }
2028
+ const propsToken = (_a = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _a !== void 0 ? _a : authToken;
2029
+ const initialDomToken = targetNode.getAttribute('authtoken') || undefined;
2030
+ if (initialDomToken && !propsToken) {
2031
+ setLoginToken(initialDomToken);
2032
+ userTokenRef.current = initialDomToken;
2033
+ }
2034
+ const applyAuthTokenFromElement = (element) => {
2035
+ var _a;
2036
+ const clientNode = element.nodeName === 'MEMORI-CLIENT'
2037
+ ? element
2038
+ : (_a = element.closest('memori-client')) !== null && _a !== void 0 ? _a : element.parentElement;
2039
+ const token = (clientNode === null || clientNode === void 0 ? void 0 : clientNode.getAttribute('authtoken')) || undefined;
2040
+ setLoginToken(token);
2041
+ userTokenRef.current = token;
2042
+ };
1706
2043
  const config = { attributes: true, childList: false, subtree: false };
1707
- const callback = (mutationList, _observer) => {
1708
- var _a, _b, _c;
2044
+ const callback = mutationList => {
2045
+ var _a;
1709
2046
  for (const mutation of mutationList) {
1710
2047
  if (mutation.type === 'attributes' &&
1711
2048
  ((_a = mutation.attributeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'authtoken') {
1712
- if (mutation.target.nodeName === 'MEMORI-CLIENT') {
1713
- setLoginToken(mutation.target.getAttribute('authtoken') || undefined);
1714
- userToken = mutation.target.getAttribute('authtoken') || undefined;
1715
- }
1716
- else {
1717
- setLoginToken(((_c = (_b = mutation.target) === null || _b === void 0 ? void 0 : _b.parentElement) === null || _c === void 0 ? void 0 : _c.getAttribute('authtoken')) ||
1718
- undefined);
1719
- userToken = mutation.target.getAttribute('authtoken') || undefined;
1720
- }
2049
+ applyAuthTokenFromElement(mutation.target);
1721
2050
  }
1722
2051
  }
1723
2052
  };
@@ -1726,7 +2055,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1726
2055
  return () => {
1727
2056
  observer.disconnect();
1728
2057
  };
1729
- }, []);
2058
+ }, [memori.name, memori.memoriID, additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken, authToken]);
1730
2059
  const [experts, setExperts] = useState();
1731
2060
  const fetchExperts = useCallback(async () => {
1732
2061
  if (!sessionId || !(memori === null || memori === void 0 ? void 0 : memori.enableBoardOfExperts))
@@ -1736,12 +2065,8 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1736
2065
  if (resp.resultCode === 0) {
1737
2066
  setExperts(experts);
1738
2067
  }
1739
- else {
1740
- console.warn('Error fetching experts', resp);
1741
- }
1742
2068
  }
1743
- catch (err) {
1744
- console.warn(err);
2069
+ catch (_a) {
1745
2070
  }
1746
2071
  }, [sessionId, memori === null || memori === void 0 ? void 0 : memori.enableBoardOfExperts]);
1747
2072
  useEffect(() => {
@@ -1751,11 +2076,26 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1751
2076
  !!loginToken &&
1752
2077
  !!(user === null || user === void 0 ? void 0 : user.userID) &&
1753
2078
  (user === null || user === void 0 ? void 0 : user.pAndCUAccepted);
1754
- const needsCredits = tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation;
1755
- const [hasEnoughCredits, setHasEnoughCredits] = useState(true);
1756
- const checkCredits = useCallback(async () => {
2079
+ const handleNotEnoughCredits = useCallback(() => {
2080
+ setHasEnoughCredits(false);
2081
+ setAuthModalState(null);
2082
+ add(createAlertOptions({
2083
+ description: t('notEnoughCredits'),
2084
+ severity: 'error',
2085
+ }));
2086
+ }, [add, t]);
2087
+ const checkCredits = useCallback(async (options) => {
1757
2088
  if (!(tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation))
1758
- return;
2089
+ return true;
2090
+ if (!ownerUserID && !ownerUserName) {
2091
+ if (options === null || options === void 0 ? void 0 : options.notify) {
2092
+ handleNotEnoughCredits();
2093
+ }
2094
+ else {
2095
+ setHasEnoughCredits(false);
2096
+ }
2097
+ return false;
2098
+ }
1759
2099
  try {
1760
2100
  const resp = await getCredits({
1761
2101
  operation: deepThoughtEnabled
@@ -1768,22 +2108,36 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1768
2108
  });
1769
2109
  if (resp.enough) {
1770
2110
  setHasEnoughCredits(true);
2111
+ return true;
1771
2112
  }
1772
2113
  else {
1773
- setHasEnoughCredits(false);
1774
- console.warn('Not enough credits. Required:', resp.required);
2114
+ if (options === null || options === void 0 ? void 0 : options.notify) {
2115
+ handleNotEnoughCredits();
2116
+ }
2117
+ else {
2118
+ setHasEnoughCredits(false);
2119
+ }
2120
+ return false;
1775
2121
  }
1776
2122
  }
1777
- catch (e) {
1778
- let err = e;
1779
- console.debug(err);
2123
+ catch (err) {
2124
+ logWidgetError('checkCredits failed', err);
2125
+ return true;
1780
2126
  }
1781
- }, [tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation, deepThoughtEnabled]);
2127
+ }, [
2128
+ baseUrl,
2129
+ deepThoughtEnabled,
2130
+ handleNotEnoughCredits,
2131
+ ownerUserID,
2132
+ ownerUserName,
2133
+ tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation,
2134
+ tenantID,
2135
+ ]);
1782
2136
  useEffect(() => {
1783
2137
  if (tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation) {
1784
2138
  checkCredits();
1785
2139
  }
1786
- }, [tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation, deepThoughtEnabled]);
2140
+ }, [tenant === null || tenant === void 0 ? void 0 : tenant.billingDelegation, deepThoughtEnabled, checkCredits]);
1787
2141
  useEffect(() => {
1788
2142
  if (__WEBCOMPONENT__)
1789
2143
  return;
@@ -1802,16 +2156,16 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1802
2156
  ? selectedLayout !== 'TOTEM' && selectedLayout !== 'WEBSITE_ASSISTANT'
1803
2157
  : !showOnlyLastMessages;
1804
2158
  const canShowLoginButton = !(tenant === null || tenant === void 0 ? void 0 : tenant.ssoLogin) &&
1805
- ((_w = showLogin !== null && showLogin !== void 0 ? showLogin : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showLogin) !== null && _w !== void 0 ? _w : memori.requireLoginToken);
2159
+ ((_y = showLogin !== null && showLogin !== void 0 ? showLogin : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showLogin) !== null && _y !== void 0 ? _y : memori.requireLoginToken);
1806
2160
  const headerProps = {
1807
2161
  memori: {
1808
2162
  ...memori,
1809
- ownerUserID: (_y = (_x = memori.ownerUserID) !== null && _x !== void 0 ? _x : ownerUserID) !== null && _y !== void 0 ? _y : undefined,
2163
+ ownerUserID: (_0 = (_z = memori.ownerUserID) !== null && _z !== void 0 ? _z : ownerUserID) !== null && _0 !== void 0 ? _0 : undefined,
1810
2164
  },
1811
2165
  apiClient: client,
1812
2166
  tenant,
1813
2167
  history,
1814
- showShare: (_z = showShare !== null && showShare !== void 0 ? showShare : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showShare) !== null && _z !== void 0 ? _z : true,
2168
+ showShare: (_1 = showShare !== null && showShare !== void 0 ? showShare : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showShare) !== null && _1 !== void 0 ? _1 : true,
1815
2169
  position,
1816
2170
  layout: selectedLayout,
1817
2171
  additionalSettings,
@@ -1821,18 +2175,18 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1821
2175
  setShowSettingsDrawer,
1822
2176
  setShowKnownFactsDrawer,
1823
2177
  setShowExpertsDrawer,
1824
- enableAudio: (_0 = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _0 !== void 0 ? _0 : true,
2178
+ enableAudio: (_2 = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _2 !== void 0 ? _2 : true,
1825
2179
  speakerMuted: speakerMuted !== null && speakerMuted !== void 0 ? speakerMuted : false,
1826
2180
  setSpeakerMuted: (mute) => {
1827
2181
  toggleMute(mute);
1828
2182
  },
1829
2183
  setShowChatHistoryDrawer,
1830
- showSettings: (_1 = showSettings !== null && showSettings !== void 0 ? showSettings : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showSettings) !== null && _1 !== void 0 ? _1 : true,
1831
- showChatHistory: (_2 = showChatHistory !== null && showChatHistory !== void 0 ? showChatHistory : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showChatHistory) !== null && _2 !== void 0 ? _2 : true,
2184
+ showSettings: (_3 = showSettings !== null && showSettings !== void 0 ? showSettings : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showSettings) !== null && _3 !== void 0 ? _3 : true,
2185
+ showChatHistory: (_4 = showChatHistory !== null && showChatHistory !== void 0 ? showChatHistory : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showChatHistory) !== null && _4 !== void 0 ? _4 : true,
1832
2186
  showMessageConsumption: enableMessageConsumption,
1833
2187
  hasUserActivatedSpeak,
1834
2188
  showReload: selectedLayout === 'TOTEM',
1835
- showClear: (_3 = showClear !== null && showClear !== void 0 ? showClear : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showClear) !== null && _3 !== void 0 ? _3 : false,
2189
+ showClear: (_5 = showClear !== null && showClear !== void 0 ? showClear : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showClear) !== null && _5 !== void 0 ? _5 : false,
1836
2190
  clearHistory: () => setHistory(h => h.slice(-1)),
1837
2191
  showLogin: canShowLoginButton,
1838
2192
  setShowLoginDrawer,
@@ -1847,7 +2201,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1847
2201
  setShowLoginDrawer(false);
1848
2202
  setUser(undefined);
1849
2203
  setLoginToken(undefined);
1850
- userToken = undefined;
2204
+ userTokenRef.current = undefined;
1851
2205
  removeLocalConfig('loginToken');
1852
2206
  });
1853
2207
  },
@@ -1863,7 +2217,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1863
2217
  hasUserActivatedSpeak,
1864
2218
  isPlayingAudio: isPlayingAudio &&
1865
2219
  !speakerMuted &&
1866
- ((_4 = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _4 !== void 0 ? _4 : true),
2220
+ ((_6 = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _6 !== void 0 ? _6 : true),
1867
2221
  loading: !!memoriTyping,
1868
2222
  baseUrl,
1869
2223
  apiUrl: client.constants.BACKEND_URL,
@@ -1893,7 +2247,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1893
2247
  notEnoughCredits: needsCredits && !hasEnoughCredits,
1894
2248
  showLogin: canShowLoginButton,
1895
2249
  setShowLoginDrawer,
1896
- showChatHistory: (_5 = showChatHistory !== null && showChatHistory !== void 0 ? showChatHistory : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showChatHistory) !== null && _5 !== void 0 ? _5 : true,
2250
+ showChatHistory: (_7 = showChatHistory !== null && showChatHistory !== void 0 ? showChatHistory : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showChatHistory) !== null && _7 !== void 0 ? _7 : true,
1897
2251
  setShowChatHistoryDrawer,
1898
2252
  user,
1899
2253
  };
@@ -1903,7 +2257,7 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1903
2257
  tenant,
1904
2258
  translateTo: isMultilanguageEnabled &&
1905
2259
  userLang.toUpperCase() !==
1906
- ((_10 = ((_9 = (_8 = (_7 = (_6 = memori.culture) === null || _6 === void 0 ? void 0 : _6.split('-')) === null || _7 === void 0 ? void 0 : _7[0]) !== null && _8 !== void 0 ? _8 : i18n.language) !== null && _9 !== void 0 ? _9 : 'IT')) === null || _10 === void 0 ? void 0 : _10.toUpperCase())
2260
+ ((_12 = ((_11 = (_10 = (_9 = (_8 = memori.culture) === null || _8 === void 0 ? void 0 : _8.split('-')) === null || _9 === void 0 ? void 0 : _9[0]) !== null && _10 !== void 0 ? _10 : i18n.language) !== null && _11 !== void 0 ? _11 : 'IT')) === null || _12 === void 0 ? void 0 : _12.toUpperCase())
1907
2261
  ? userLang
1908
2262
  : undefined,
1909
2263
  baseUrl,
@@ -1911,9 +2265,9 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1911
2265
  layout,
1912
2266
  memoriTyping,
1913
2267
  typingText,
1914
- showTypingText: (_11 = showTypingText !== null && showTypingText !== void 0 ? showTypingText : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showTypingText) !== null && _11 !== void 0 ? _11 : false,
2268
+ showTypingText: (_13 = showTypingText !== null && showTypingText !== void 0 ? showTypingText : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showTypingText) !== null && _13 !== void 0 ? _13 : false,
1915
2269
  history: showFullHistory ? history : history.slice(-2),
1916
- authToken: (_13 = (_12 = loginToken !== null && loginToken !== void 0 ? loginToken : userToken) !== null && _12 !== void 0 ? _12 : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _13 !== void 0 ? _13 : authToken,
2270
+ authToken: resolveLoginToken(),
1917
2271
  dialogState: currentDialogState,
1918
2272
  pushMessage,
1919
2273
  simulateUserPrompt,
@@ -1986,7 +2340,9 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1986
2340
  : FullPageLayout;
1987
2341
  const widgetTheme = (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.theme) === 'light' || (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.theme) === 'dark'
1988
2342
  ? integrationConfig.theme
1989
- : undefined;
2343
+ : isDarkTheme
2344
+ ? 'dark'
2345
+ : undefined;
1990
2346
  return (_jsx("div", { ref: setWidgetRootEl, className: cx('memori', 'memori-widget', `memori-layout-${String(selectedLayout).toLowerCase()}`, `memori-controls-${String(controlsPosition).toLowerCase()}`, `memori--avatar-${(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.avatar) || 'default'}`, {
1991
2347
  'memori--auto-start': autoStart,
1992
2348
  'memori--preview': preview,
@@ -1999,132 +2355,132 @@ const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenan
1999
2355
  }), "data-theme": widgetTheme, "data-memori-name": memori === null || memori === void 0 ? void 0 : memori.name, "data-memori-id": memori === null || memori === void 0 ? void 0 : memori.engineMemoriID, "data-memori-secondary-id": memori === null || memori === void 0 ? void 0 : memori.memoriID, "data-memori-session-id": sessionId, "data-memori-integration": integration === null || integration === void 0 ? void 0 : integration.integrationID, "data-memori-engine-state": JSON.stringify({
2000
2356
  ...currentDialogState,
2001
2357
  sessionID: sessionId,
2002
- }), style: { height }, children: _jsxs(MemoriUIProvider, { container: widgetRootEl, theme: widgetTheme, children: [_jsx(Layout, { Header: Header, headerProps: headerProps, Avatar: Avatar, avatarProps: avatarProps, Chat: Chat, chatProps: chatProps, StartPanel: StartPanel, startPanelProps: startPanelProps, integrationStyle: integrationStyle, integrationBackground: integrationBackground, poweredBy: poweredBy, autoStart: autoStart, sessionId: sessionId, hasUserActivatedSpeak: hasUserActivatedSpeak, loading: loading, avatar3dHidden: avatar3dHidden !== null && avatar3dHidden !== void 0 ? avatar3dHidden : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.avatar_3d_hidden }), _jsx(ArtifactAPIBridge, { pushMessage: (message) => {
2003
- setHistory(history => {
2004
- if (!history.length)
2005
- return history;
2006
- const lastMessage = history[history.length - 1];
2007
- if (!lastMessage || lastMessage.fromUser)
2008
- return history;
2009
- const updatedLastMessage = {
2010
- ...lastMessage,
2011
- text: lastMessage.text + message.text,
2012
- };
2013
- return [...history.slice(0, -1), updatedLastMessage];
2014
- });
2015
- } }), _jsx("audio", { id: "memori-audio", style: { display: 'none' }, src: "https://aisuru.com/intro.mp3" }), isClient && (_jsx(MemoriAuth, { withModal: true, pwdOrTokens: authModalState, openModal: !!authModalState, setPwdOrTokens: setAuthModalState, showTokens: memori.privacyType === 'SECRET', onFinish: (values) => {
2016
- var _a, _b, _c, _d;
2017
- if (values['password'])
2018
- setMemoriPwd(values['password']);
2019
- if (values['password'])
2020
- memoriPassword = values['password'];
2021
- if (values['tokens'])
2022
- setMemoriTokens(values['tokens']);
2023
- return reopenSession(!sessionId, values['password'], values['tokens'], personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2024
- LANG: userLang,
2025
- PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2026
- ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2027
- ...(initialContextVars || {}),
2028
- }, initialQuestion, birthDate)
2029
- .then(state => {
2030
- if (!(state === null || state === void 0 ? void 0 : state.sessionID)) {
2031
- throw new Error('AUTH_FAILED');
2032
- }
2033
- setAuthModalState(null);
2034
- if (state === null || state === void 0 ? void 0 : state.dialogState) {
2035
- setHasUserActivatedSpeak(true);
2036
- }
2037
- else {
2038
- onClickStart(state);
2039
- }
2040
- })
2041
- .catch(error => {
2042
- if (!(error instanceof Error) ||
2043
- error.message !== 'AUTH_FAILED') {
2044
- setGotErrorInOpening(true);
2045
- }
2046
- throw error;
2047
- });
2048
- }, minimumNumberOfRecoveryTokens: (_17 = memori === null || memori === void 0 ? void 0 : memori.minimumNumberOfRecoveryTokens) !== null && _17 !== void 0 ? _17 : 1 })), isClient && (_jsx(AgeVerificationModal, { visible: showAgeVerification, minAge: minAge, onClose: birthDate => {
2049
- var _a, _b, _c, _d;
2050
- if (birthDate) {
2051
- setBirthDate(birthDate);
2052
- setLocalConfig('birthDate', birthDate);
2053
- reopenSession(!sessionId, memoriPassword || memoriPwd || (memori === null || memori === void 0 ? void 0 : memori.secretToken), memoriTokens, personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2054
- LANG: userLang,
2055
- PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2056
- ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2057
- ...(initialContextVars || {}),
2058
- }, initialQuestion, birthDate)
2059
- .then(state => {
2060
- setShowAgeVerification(false);
2061
- setAuthModalState(null);
2062
- onClickStart(state || undefined);
2063
- })
2064
- .catch(() => {
2065
- setShowAgeVerification(false);
2066
- setGotErrorInOpening(true);
2067
- });
2068
- }
2069
- else {
2070
- setShowAgeVerification(false);
2071
- setClickedStart(false);
2072
- }
2073
- } })), showSettingsDrawer && (_jsx(SettingsDrawer, { layout: selectedLayout, open: !!showSettingsDrawer, onClose: () => setShowSettingsDrawer(false), microphoneMode: continuousSpeech ? 'CONTINUOUS' : 'HOLD_TO_TALK', continuousSpeechTimeout: continuousSpeechTimeout, setMicrophoneMode: mode => setContinuousSpeech(mode === 'CONTINUOUS'), setContinuousSpeechTimeout: setContinuousSpeechTimeout, controlsPosition: controlsPosition, setControlsPosition: setControlsPosition, hideEmissions: hideEmissions, setHideEmissions: setHideEmissions, avatarType: avatarType, setAvatarType: setAvatarType, enablePositionControls: enablePositionControls, setEnablePositionControls: setEnablePositionControls, isAvatar3d: !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.avatarURL), additionalSettings: additionalSettings, speakerMuted: speakerMuted })), showChatHistoryDrawer && (_jsx(ChatHistoryDrawer, { open: !!showChatHistoryDrawer, onClose: () => setShowChatHistoryDrawer(false), resumeSession: chatLog => {
2074
- setChatLogID(chatLog.chatLogID);
2075
- onClickStart(undefined, false, chatLog);
2076
- setShowChatHistoryDrawer(false);
2077
- }, apiClient: client, sessionId: sessionId || '', memori: memori, baseUrl: baseUrl, history: history, apiUrl: client.constants.BACKEND_URL, loginToken: loginToken, language: language, userLang: userLang, isMultilanguageEnabled: isMultilanguageEnabled })), showKnownFactsDrawer && sessionId && (_jsx(KnownFacts, { apiClient: client, memori: memori, sessionID: sessionId, visible: showKnownFactsDrawer, closeDrawer: () => setShowKnownFactsDrawer(false) })), showExpertsDrawer && !!experts && (_jsx(ExpertsDrawer, { apiUrl: client.constants.BACKEND_URL, baseUrl: baseUrl, tenant: tenant, experts: experts, open: showExpertsDrawer, onClose: () => setShowExpertsDrawer(false) })), showLoginDrawer && (tenant === null || tenant === void 0 ? void 0 : tenant.name) && (_jsx(LoginDrawer, { tenant: tenant, apiClient: client, open: !!showLoginDrawer, user: user, loginToken: loginToken, onClose: () => setShowLoginDrawer(false), drawerClassName: selectedLayout === 'WEBSITE_ASSISTANT'
2078
- ? 'memori-drawer--above-website-assistant'
2079
- : undefined, onLogin: (user, token) => {
2080
- var _a, _b, _c, _d;
2081
- reopenSession(false, memoriPassword || memoriPwd || (memori === null || memori === void 0 ? void 0 : memori.secretToken), [], personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2082
- LANG: userLang,
2083
- PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2084
- ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2085
- ...(initialContextVars || {}),
2086
- }, undefined, birthDate, { loginToken: token }, undefined, sessionId).then(state => {
2087
- var _a, _b;
2088
- setShowLoginDrawer(false);
2089
- setUser(user);
2090
- setLoginToken(token);
2091
- userToken = token;
2092
- setLocalConfig('loginToken', token);
2093
- if ((state === null || state === void 0 ? void 0 : state.sessionID) &&
2094
- state.sessionID !== sessionId &&
2095
- (state === null || state === void 0 ? void 0 : state.dialogState)) {
2096
- const username = (user === null || user === void 0 ? void 0 : user.userName) || t('login.user');
2097
- pushMessage({
2098
- text: '',
2099
- emitter: state.dialogState.emitter,
2100
- media: (_b = (_a = state.dialogState.emittedMedia) !== null && _a !== void 0 ? _a : state.dialogState.media) !== null && _b !== void 0 ? _b : [],
2101
- fromUser: false,
2102
- initial: t('login.successfullyLoggedIn', {
2103
- username,
2104
- }),
2105
- contextVars: state.dialogState.contextVars,
2106
- date: state.dialogState.currentDate,
2107
- placeName: state.dialogState.currentPlaceName,
2108
- placeLatitude: state.dialogState.currentLatitude,
2109
- placeLongitude: state.dialogState.currentLongitude,
2110
- placeUncertaintyKm: state.dialogState.currentUncertaintyKm,
2111
- tag: state.dialogState.currentTag,
2112
- memoryTags: state.dialogState.memoryTags,
2358
+ }), style: { height }, children: _jsx(MemoriUIProvider, { container: widgetRootEl, theme: widgetTheme, children: _jsx(WidgetSurfaceProvider, { value: widgetSurfaceEl, children: _jsxs("div", { ref: setWidgetSurfaceEl, className: "memori-widget__surface", children: [_jsx(Layout, { Header: Header, headerProps: headerProps, Avatar: Avatar, avatarProps: avatarProps, Chat: Chat, chatProps: chatProps, StartPanel: StartPanel, startPanelProps: startPanelProps, integrationStyle: integrationStyle, integrationBackground: integrationBackground, poweredBy: poweredBy, autoStart: autoStart, sessionId: sessionId, hasUserActivatedSpeak: hasUserActivatedSpeak, loading: loading, avatar3dHidden: avatar3dHidden !== null && avatar3dHidden !== void 0 ? avatar3dHidden : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.avatar_3d_hidden }), _jsx(ArtifactAPIBridge, { pushMessage: (message) => {
2359
+ setHistory(history => {
2360
+ if (!history.length)
2361
+ return history;
2362
+ const lastMessage = history[history.length - 1];
2363
+ if (!lastMessage || lastMessage.fromUser)
2364
+ return history;
2365
+ const updatedLastMessage = {
2366
+ ...lastMessage,
2367
+ text: lastMessage.text + message.text,
2368
+ };
2369
+ return [...history.slice(0, -1), updatedLastMessage];
2113
2370
  });
2114
- setCurrentDialogState(state.dialogState);
2115
- }
2116
- });
2117
- }, setUser: setUser, onLogout: () => {
2118
- if (!loginToken)
2119
- return;
2120
- client.backend.pwlUserLogout(loginToken).then(() => {
2121
- setShowLoginDrawer(false);
2122
- setUser(undefined);
2123
- setLoginToken(undefined);
2124
- userToken = undefined;
2125
- removeLocalConfig('loginToken');
2126
- });
2127
- } }))] }) }));
2371
+ } }), _jsx("audio", { id: "memori-audio", style: { display: 'none' }, src: "https://aisuru.com/intro.mp3" }), isClient && (_jsx(MemoriAuth, { withModal: true, pwdOrTokens: authModalState, openModal: !!authModalState, setPwdOrTokens: setAuthModalState, showTokens: memori.privacyType === 'SECRET', onFinish: (values) => {
2372
+ var _a, _b, _c, _d;
2373
+ if (values['password'])
2374
+ setMemoriPwd(values['password']);
2375
+ if (values['password'])
2376
+ memoriPassword = values['password'];
2377
+ if (values['tokens'])
2378
+ setMemoriTokens(values['tokens']);
2379
+ return reopenSession(!sessionId, values['password'], values['tokens'], personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2380
+ LANG: userLang,
2381
+ PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2382
+ ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2383
+ ...(initialContextVars || {}),
2384
+ }, initialQuestion, birthDate)
2385
+ .then(state => {
2386
+ if (!(state === null || state === void 0 ? void 0 : state.sessionID)) {
2387
+ throw new Error('AUTH_FAILED');
2388
+ }
2389
+ setAuthModalState(null);
2390
+ if (state === null || state === void 0 ? void 0 : state.dialogState) {
2391
+ setHasUserActivatedSpeak(true);
2392
+ }
2393
+ else {
2394
+ onClickStart(state);
2395
+ }
2396
+ })
2397
+ .catch(error => {
2398
+ if (!(error instanceof Error) ||
2399
+ error.message !== 'AUTH_FAILED') {
2400
+ setGotErrorInOpening(true);
2401
+ }
2402
+ throw error;
2403
+ });
2404
+ }, minimumNumberOfRecoveryTokens: (_17 = memori === null || memori === void 0 ? void 0 : memori.minimumNumberOfRecoveryTokens) !== null && _17 !== void 0 ? _17 : 1 })), isClient && (_jsx(AgeVerificationModal, { visible: showAgeVerification, minAge: minAge, onClose: birthDate => {
2405
+ var _a, _b, _c, _d;
2406
+ if (birthDate) {
2407
+ setBirthDate(birthDate);
2408
+ setLocalConfig('birthDate', birthDate);
2409
+ reopenSession(!sessionId, memoriPassword || memoriPwd || (memori === null || memori === void 0 ? void 0 : memori.secretToken), memoriTokens, personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2410
+ LANG: userLang,
2411
+ PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2412
+ ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2413
+ ...(initialContextVars || {}),
2414
+ }, initialQuestion, birthDate)
2415
+ .then(state => {
2416
+ setShowAgeVerification(false);
2417
+ setAuthModalState(null);
2418
+ onClickStart(state || undefined);
2419
+ })
2420
+ .catch(() => {
2421
+ setShowAgeVerification(false);
2422
+ setGotErrorInOpening(true);
2423
+ });
2424
+ }
2425
+ else {
2426
+ setShowAgeVerification(false);
2427
+ setClickedStart(false);
2428
+ }
2429
+ } })), showSettingsDrawer && (_jsx(SettingsDrawer, { layout: selectedLayout, open: !!showSettingsDrawer, onClose: () => setShowSettingsDrawer(false), microphoneMode: continuousSpeech ? 'CONTINUOUS' : 'HOLD_TO_TALK', continuousSpeechTimeout: continuousSpeechTimeout, setMicrophoneMode: mode => setContinuousSpeech(mode === 'CONTINUOUS'), setContinuousSpeechTimeout: setContinuousSpeechTimeout, controlsPosition: controlsPosition, setControlsPosition: setControlsPosition, hideEmissions: hideEmissions, setHideEmissions: setHideEmissions, avatarType: avatarType, setAvatarType: setAvatarType, enablePositionControls: enablePositionControls, setEnablePositionControls: setEnablePositionControls, isAvatar3d: !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.avatarURL), additionalSettings: additionalSettings, speakerMuted: speakerMuted })), showChatHistoryDrawer && (_jsx(ChatHistoryDrawer, { open: !!showChatHistoryDrawer, onClose: () => setShowChatHistoryDrawer(false), resumeSession: chatLog => {
2430
+ setChatLogID(chatLog.chatLogID);
2431
+ onClickStart(undefined, false, chatLog);
2432
+ setShowChatHistoryDrawer(false);
2433
+ }, apiClient: client, sessionId: sessionId || '', memori: memori, baseUrl: baseUrl, history: history, apiUrl: client.constants.BACKEND_URL, loginToken: loginToken, language: language, userLang: userLang, isMultilanguageEnabled: isMultilanguageEnabled })), showKnownFactsDrawer && sessionId && (_jsx(KnownFacts, { apiClient: client, memori: memori, sessionID: sessionId, visible: showKnownFactsDrawer, closeDrawer: () => setShowKnownFactsDrawer(false) })), showExpertsDrawer && !!experts && (_jsx(ExpertsDrawer, { apiUrl: client.constants.BACKEND_URL, baseUrl: baseUrl, tenant: tenant, experts: experts, open: showExpertsDrawer, onClose: () => setShowExpertsDrawer(false) })), showLoginDrawer && (tenant === null || tenant === void 0 ? void 0 : tenant.name) && (_jsx(LoginDrawer, { tenant: tenant, apiClient: client, open: !!showLoginDrawer, user: user, loginToken: loginToken, onClose: () => setShowLoginDrawer(false), drawerClassName: selectedLayout === 'WEBSITE_ASSISTANT'
2434
+ ? 'memori-drawer--above-website-assistant'
2435
+ : undefined, onLogin: (user, token) => {
2436
+ var _a, _b, _c, _d;
2437
+ reopenSession(false, memoriPassword || memoriPwd || (memori === null || memori === void 0 ? void 0 : memori.secretToken), [], personification === null || personification === void 0 ? void 0 : personification.tag, personification === null || personification === void 0 ? void 0 : personification.pin, {
2438
+ LANG: userLang,
2439
+ PATHNAME: (_a = window.location.pathname) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
2440
+ ROUTE: ((_d = (_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) === null || _d === void 0 ? void 0 : _d.toUpperCase()) || '',
2441
+ ...(initialContextVars || {}),
2442
+ }, undefined, birthDate, { loginToken: token }, undefined, sessionId).then(state => {
2443
+ var _a, _b;
2444
+ setShowLoginDrawer(false);
2445
+ setUser(user);
2446
+ setLoginToken(token);
2447
+ userTokenRef.current = token;
2448
+ setLocalConfig('loginToken', token);
2449
+ if ((state === null || state === void 0 ? void 0 : state.sessionID) &&
2450
+ state.sessionID !== sessionId &&
2451
+ (state === null || state === void 0 ? void 0 : state.dialogState)) {
2452
+ const username = (user === null || user === void 0 ? void 0 : user.userName) || t('login.user');
2453
+ pushMessage({
2454
+ text: '',
2455
+ emitter: state.dialogState.emitter,
2456
+ media: (_b = (_a = state.dialogState.emittedMedia) !== null && _a !== void 0 ? _a : state.dialogState.media) !== null && _b !== void 0 ? _b : [],
2457
+ fromUser: false,
2458
+ initial: t('login.successfullyLoggedIn', {
2459
+ username,
2460
+ }),
2461
+ contextVars: state.dialogState.contextVars,
2462
+ date: state.dialogState.currentDate,
2463
+ placeName: state.dialogState.currentPlaceName,
2464
+ placeLatitude: state.dialogState.currentLatitude,
2465
+ placeLongitude: state.dialogState.currentLongitude,
2466
+ placeUncertaintyKm: state.dialogState.currentUncertaintyKm,
2467
+ tag: state.dialogState.currentTag,
2468
+ memoryTags: state.dialogState.memoryTags,
2469
+ });
2470
+ setCurrentDialogState(state.dialogState);
2471
+ }
2472
+ });
2473
+ }, setUser: setUser, onLogout: () => {
2474
+ if (!loginToken)
2475
+ return;
2476
+ client.backend.pwlUserLogout(loginToken).then(() => {
2477
+ setShowLoginDrawer(false);
2478
+ setUser(undefined);
2479
+ setLoginToken(undefined);
2480
+ userTokenRef.current = undefined;
2481
+ removeLocalConfig('loginToken');
2482
+ });
2483
+ } }))] }) }) }) }));
2128
2484
  };
2129
2485
  export default MemoriWidget;
2130
2486
  //# sourceMappingURL=MemoriWidget.js.map