UNPKG

@memori.ai/memori-react

Version:

[![npm version](https://img.shields.io/github/package-json/v/memori-ai/memori-react)](https://www.npmjs.com/package/@memori.ai/memori-react) ![Tests](https://github.com/memori-ai/memori-react/workflows/CI/badge.svg?branch=main) ![TypeScript Support](https

924 lines 125 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const jsx_runtime_1 = require("react/jsx-runtime"); const ArtifactAPI_1 = require("../MemoriArtifactSystem/utils/ArtifactAPI"); const piiDetection_1 = require("../../helpers/piiDetection"); const react_1 = require("react"); const react_i18next_1 = require("react-i18next"); const memori_api_client_1 = tslib_1.__importDefault(require("@memori.ai/memori-api-client")); const classnames_1 = tslib_1.__importDefault(require("classnames")); const luxon_1 = require("luxon"); const react_hot_toast_1 = tslib_1.__importDefault(require("react-hot-toast")); const PositionDrawer_1 = tslib_1.__importDefault(require("../PositionDrawer/PositionDrawer")); const Auth_1 = tslib_1.__importDefault(require("../Auth/Auth")); const Chat_1 = tslib_1.__importDefault(require("../Chat/Chat")); const StartPanel_1 = tslib_1.__importDefault(require("../StartPanel/StartPanel")); const Avatar_1 = tslib_1.__importDefault(require("../Avatar/Avatar")); const Header_1 = tslib_1.__importDefault(require("../Header/Header")); const PoweredBy_1 = tslib_1.__importDefault(require("../PoweredBy/PoweredBy")); const AgeVerificationModal_1 = tslib_1.__importDefault(require("../AgeVerificationModal/AgeVerificationModal")); const SettingsDrawer_1 = tslib_1.__importDefault(require("../SettingsDrawer/SettingsDrawer")); const KnownFacts_1 = tslib_1.__importDefault(require("../KnownFacts/KnownFacts")); const ExpertsDrawer_1 = tslib_1.__importDefault(require("../ExpertsDrawer/ExpertsDrawer")); const LoginDrawer_1 = tslib_1.__importDefault(require("../LoginDrawer/LoginDrawer")); const Button_1 = tslib_1.__importDefault(require("../ui/Button")); const Close_1 = tslib_1.__importDefault(require("../icons/Close")); const FullPage_1 = tslib_1.__importDefault(require("../layouts/FullPage")); const Totem_1 = tslib_1.__importDefault(require("../layouts/Totem")); const Chat_2 = tslib_1.__importDefault(require("../layouts/Chat")); const WebsiteAssistant_1 = tslib_1.__importDefault(require("../layouts/WebsiteAssistant")); const HiddenChat_1 = tslib_1.__importDefault(require("../layouts/HiddenChat")); const ZoomedFullBody_1 = tslib_1.__importDefault(require("../layouts/ZoomedFullBody")); const translations_1 = require("../../helpers/translations"); const configuration_1 = require("../../helpers/configuration"); const utils_1 = require("../../helpers/utils"); const ttsVoiceUtility_1 = require("../../helpers/tts/ttsVoiceUtility"); const constants_1 = require("../../helpers/constants"); const error_1 = require("../../helpers/error"); const credits_1 = require("../../helpers/credits"); const sanitizer_1 = require("../../helpers/sanitizer"); const useTTS_1 = require("../../helpers/tts/useTTS"); const ChatHistory_1 = tslib_1.__importDefault(require("../ChatHistoryDrawer/ChatHistory")); const useSTT_1 = require("../../helpers/stt/useSTT"); const useNats_1 = require("../../helpers/nats/useNats"); const isSessionExpiredError_1 = require("../../helpers/nats/isSessionExpiredError"); const getMemoriState = (integrationId) => { var _a, _b, _c, _d, _f; let widget = integrationId ? document.querySelector(`.memori-widget[data-memori-integration="${integrationId}"]`) || ((_b = (_a = document .querySelector('memori-client')) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector(`.memori-widget[data-memori-integration]`)) : document.querySelector('.memori-widget') || ((_d = (_c = document .querySelector('memori-client')) === null || _c === void 0 ? void 0 : _c.shadowRoot) === null || _d === void 0 ? void 0 : _d.querySelector('.memori-widget')); if (!widget) return null; let engineState = (_f = widget.dataset) === null || _f === void 0 ? void 0 : _f.memoriEngineState; if (!engineState) return null; let dialogState = JSON.parse(engineState); let loginToken = (0, configuration_1.getLocalConfig)('loginToken', undefined); return { ...dialogState, loginToken, }; }; const NULL_PLACE_SPEC = { placeName: null, latitude: null, longitude: null, uncertaintyKm: null, }; const logWidgetError = (context, detail) => { console.error(`[MemoriWidget] ${context}`, detail !== null && detail !== void 0 ? detail : ''); }; function readCorrelationID(response) { const value = response.correlationID; return typeof value === 'string' && value.length > 0 ? value : undefined; } const typeMessage = (message, waitForPrevious = true, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false) => { const e = new CustomEvent('MemoriTextEntered', { detail: { text: message, waitForPrevious, hidden, typingText, useLoaderTextAsMsg, hasBatchQueued, }, }); document.dispatchEvent(e); const isSafariIOS = window.navigator.userAgent.includes('Safari') && !window.navigator.userAgent.includes('Chrome') && /iPad|iPhone|iPod/.test(navigator.userAgent); if (isSafariIOS) { setTimeout(() => { document.dispatchEvent(new CustomEvent('MemoriEndSpeak')); }, 300); } }; const typeMessageHidden = (message, waitForPrevious = true, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false) => typeMessage(message, waitForPrevious, true, typingText, useLoaderTextAsMsg, hasBatchQueued); const typeBatchMessages = (messages) => { function disableInputs() { var _a, _b, _c, _d; (_a = document .querySelector('fieldset#chat-fieldset')) === null || _a === void 0 ? void 0 : _a.setAttribute('disabled', ''); const styles = `opacity: 0.5; touch-action: none; pointer-events: none;`; (_b = document .querySelector('textarea.memori-chat-textarea--input')) === null || _b === void 0 ? void 0 : _b.setAttribute('style', styles); (_c = document .querySelector('button.memori-chat-inputs--send')) === null || _c === void 0 ? void 0 : _c.setAttribute('style', styles); (_d = document .querySelector('button.memori-chat-inputs--mic')) === null || _d === void 0 ? void 0 : _d.setAttribute('style', styles); } function reEnableInputs() { var _a, _b, _c, _d; (_a = document .querySelector('fieldset#chat-fieldset')) === null || _a === void 0 ? void 0 : _a.removeAttribute('disabled'); (_b = document .querySelector('textarea.memori-chat-textarea--input')) === null || _b === void 0 ? void 0 : _b.removeAttribute('style'); (_c = document .querySelector('button.memori-chat-inputs--send')) === null || _c === void 0 ? void 0 : _c.removeAttribute('style'); (_d = document .querySelector('button.memori-chat-inputs--mic')) === null || _d === void 0 ? void 0 : _d.removeAttribute('style'); } function areInputsDisabled() { var _a; return !!((_a = document .querySelector('fieldset#chat-fieldset')) === null || _a === void 0 ? void 0 : _a.hasAttribute('disabled')); } const isSafariIOS = window.navigator.userAgent.includes('Safari') && !window.navigator.userAgent.includes('Chrome') && /iPad|iPhone|iPod/.test(navigator.userAgent); const stepsGenerator = (function* () { yield* messages; })(); disableInputs(); const submitNewMessage = () => { const next = stepsGenerator.next(); const step = next.value; if (step) { if (!areInputsDisabled()) { disableInputs(); } let waitForPrevious = step.waitForPrevious; if (isSafariIOS) waitForPrevious = false; typeMessage(step.message, waitForPrevious, step.hidden, step.typingText, step.useLoaderTextAsMsg, !next.done); if (isSafariIOS) { setTimeout(() => { document.dispatchEvent(new CustomEvent('MemoriEndSpeak')); reEnableInputs(); }, 3000); } } else if (areInputsDisabled()) { reEnableInputs(); } if (next.done) { document.removeEventListener('MemoriEndSpeak', submitNewMessage); if (areInputsDisabled()) reEnableInputs(); return; } }; document.addEventListener('MemoriEndSpeak', submitNewMessage); submitNewMessage(); }; window.getMemoriState = getMemoriState; window.typeMessage = typeMessage; window.typeMessageHidden = typeMessageHidden; window.typeBatchMessages = typeBatchMessages; let audioContext; let memoriPassword; let userToken; const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenantID, memoriLang, uiLang, spokenLang, multilingual, integration, layout, customLayout, showShare, preview = false, embed = false, showCopyButton = true, showTranslationOriginal = false, showInputs = true, showDates = false, showContextPerLine = false, showMessageConsumption = false, showSettings, showTypingText = false, showClear = false, showLogin = false, showUpload, showOnlyLastMessages, showChatHistory, showReasoning, avatar3dHidden, height = '100vh', secret, baseUrl = 'https://aisuru-staging.aclambda.online', apiURL = 'https://backend-staging.memori.ai', engineURL = 'https://engine-staging.memori.ai', initialContextVars, initialQuestion, ttsProvider, ogImage, sessionID: initialSessionID, tenant, personification, authToken, enableAudio, defaultSpeakerActive = true, disableTextEnteredEvents = false, onStateChange, additionalInfo, additionalSettings, customMediaRenderer, userAvatar, __WEBCOMPONENT__ = false, useMathFormatting = false, autoStart = false, applyVarsToRoot = false, showFunctionCache = false, maxTotalMessagePayload, maxTextareaCharacters, }) => { var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18; const { t, i18n } = (0, react_i18next_1.useTranslation)(); const [isClient, setIsClient] = (0, react_1.useState)(false); (0, react_1.useEffect)(() => { setIsClient(true); }, []); const client = (0, memori_api_client_1.default)(apiURL, engineURL); const { initSession, deleteSession, postEnterTextAsync, postTextEnteredEvent, postPlaceChangedEvent, postDateChangedEvent, postTagChangedEvent, getSession, getExpertReferences, getSessionChatLogs, } = client; const [instruct, setInstruct] = (0, react_1.useState)(false); const [enableFocusChatInput, setEnableFocusChatInput] = (0, react_1.useState)(true); const [loginToken, setLoginToken] = (0, react_1.useState)((_a = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _a !== void 0 ? _a : authToken); const [user, setUser] = (0, react_1.useState)({ avatarURL: typeof userAvatar === 'string' ? userAvatar : undefined, }); (0, react_1.useEffect)(() => { if (loginToken && !(user === null || user === void 0 ? void 0 : user.userID) && (showLogin || memori.requireLoginToken)) { client.backend .pwlGetCurrentUser(loginToken) .then(({ user, resultCode }) => { if (user && resultCode === 0) { setUser(user); (0, configuration_1.setLocalConfig)('loginToken', loginToken); if (!birthDate && user.birthDate) { setBirthDate(user.birthDate); (0, configuration_1.setLocalConfig)('birthDate', user.birthDate); } } else { (0, configuration_1.removeLocalConfig)('loginToken'); } }); } }, [loginToken, user === null || user === void 0 ? void 0 : user.userID]); const [showLoginDrawer, setShowLoginDrawer] = (0, react_1.useState)(false); const [clickedStart, setClickedStart] = (0, react_1.useState)(false); const sessionStartingRef = (0, react_1.useRef)(false); 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()) || ((_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()); const integrationConfig = (integration === null || integration === void 0 ? void 0 : integration.customData) ? JSON.parse(integration.customData) : null; const isMultilanguageEnabled = multilingual !== undefined ? multilingual : !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.multilanguage); const forcedTimeout = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.forcedTimeout; const [userLang, setUserLang] = (0, react_1.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'); (0, react_1.useEffect)(() => { if (spokenLang != null) { setUserLang(spokenLang); } }, [spokenLang]); const applyMathFormatting = useMathFormatting !== undefined ? useMathFormatting : !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.useMathFormatting); (0, react_1.useEffect)(() => { if (applyMathFormatting) (0, utils_1.installMathJax)(); }, [applyMathFormatting]); (0, react_1.useEffect)(() => { const langToApply = uiLang && constants_1.uiLanguages.includes(uiLang.toLowerCase()) ? uiLang.toLowerCase() : userLang && constants_1.uiLanguages.includes(userLang.toLowerCase()) ? userLang.toLowerCase() : null; if (langToApply && typeof (i18n === null || i18n === void 0 ? void 0 : i18n.changeLanguage) === 'function') { i18n.changeLanguage(langToApply); } }, [uiLang, userLang]); const [loading, setLoading] = (0, react_1.useState)(false); const [memoriTyping, setMemoriTyping] = (0, react_1.useState)(false); const [typingText, setTypingText] = (0, react_1.useState)(); const pendingEnterTextRef = (0, react_1.useRef)(new Map()); const bufferedNatsResponsesRef = (0, react_1.useRef)(new Map()); const layoutName = typeof layout === 'string' ? layout : typeof (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === 'string' ? integrationConfig.layout : (_q = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _q === void 0 ? void 0 : _q.name; const selectedLayout = layoutName || 'DEFAULT'; const piiDetection = typeof (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === 'object' && (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) !== null && ((_s = (_r = integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) === null || _r === void 0 ? void 0 : _r.piiDetection) === null || _s === void 0 ? void 0 : _s.enabled) ? integrationConfig.layout.piiDetection : undefined; const defaultEnableAudio = (_t = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _t !== void 0 ? _t : true; const [hasUserActivatedListening, setHasUserActivatedListening] = (0, react_1.useState)(false); const [hasUserTypedMessage, setHasUserTypedMessage] = (0, react_1.useState)(false); const [showPositionDrawer, setShowPositionDrawer] = (0, react_1.useState)(false); const [showSettingsDrawer, setShowSettingsDrawer] = (0, react_1.useState)(false); const [showChatHistoryDrawer, setShowChatHistoryDrawer] = (0, react_1.useState)(false); const [showKnownFactsDrawer, setShowKnownFactsDrawer] = (0, react_1.useState)(false); const [showExpertsDrawer, setShowExpertsDrawer] = (0, react_1.useState)(false); const [continuousSpeech, setContinuousSpeech] = (0, react_1.useState)(false); const [continuousSpeechTimeout, setContinuousSpeechTimeout] = (0, react_1.useState)(2); const [controlsPosition, setControlsPosition] = (0, react_1.useState)('center'); const [enablePositionControls, setEnablePositionControls] = (0, react_1.useState)(false); const [avatarType, setAvatarType] = (0, react_1.useState)(null); const [hideEmissions, setHideEmissions] = (0, react_1.useState)(false); const [runtimeShowMessageConsumption, setRuntimeShowMessageConsumption] = (0, react_1.useState)(false); const speechSynthesizerRef = (0, react_1.useRef)(null); const [memoriSpeaking, setMemoriSpeaking] = (0, react_1.useState)(false); (0, react_1.useEffect)(() => { setMemoriSpeaking(!!speechSynthesizerRef.current); }, [speechSynthesizerRef.current]); (0, react_1.useEffect)(() => { var _a, _b; let defaultControlsPosition = 'bottom'; let microphoneMode = (0, configuration_1.getLocalConfig)('microphoneMode', 'HOLD_TO_TALK'); if (window.innerWidth <= 768) { defaultControlsPosition = 'bottom'; microphoneMode = 'HOLD_TO_TALK'; } else if (window.matchMedia('(orientation: portrait)').matches || window.innerHeight > window.innerWidth) { defaultControlsPosition = 'center'; } else { defaultControlsPosition = 'bottom'; } setContinuousSpeech(speakerMuted ? false : microphoneMode === 'CONTINUOUS'); setContinuousSpeechTimeout((0, configuration_1.getLocalConfig)('continuousSpeechTimeout', 2)); setControlsPosition((0, configuration_1.getLocalConfig)('controlsPosition', defaultControlsPosition)); setAvatarType((0, configuration_1.getLocalConfig)('avatarType', 'avatar3d')); setHideEmissions((0, configuration_1.getLocalConfig)('hideEmissions', false)); setRuntimeShowMessageConsumption((0, configuration_1.getLocalConfig)('showMessageConsumption', (_a = showMessageConsumption !== null && showMessageConsumption !== void 0 ? showMessageConsumption : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.showMessageConsumption) !== null && _a !== void 0 ? _a : false)); if (!(additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) && !authToken) { setLoginToken((0, configuration_1.getLocalConfig)('loginToken', undefined)); userToken = (0, configuration_1.getLocalConfig)('loginToken', undefined); setBirthDate((0, configuration_1.getLocalConfig)('birthDate', undefined)); } if (!((_b = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _b !== void 0 ? _b : true)) { (0, configuration_1.setLocalConfig)('muteSpeaker', true); } }, []); (0, react_1.useEffect)(() => { var _a; const isAudioEnabled = (_a = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _a !== void 0 ? _a : true; if (!isAudioEnabled) { (0, configuration_1.setLocalConfig)('muteSpeaker', true); } }, [enableAudio, integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio]); const [memoriPwd, setMemoriPwd] = (0, react_1.useState)(secret); const [memoriTokens, setMemoriTokens] = (0, react_1.useState)(); const [authModalState, setAuthModalState] = (0, react_1.useState)(null); const [position, _setPosition] = (0, react_1.useState)(); const hasUserProvidedPosition = (0, react_1.useCallback)((venue) => { if (!venue) return false; if (venue.placeName === 'Position' && venue.latitude === 0 && venue.longitude === 0) { return false; } return true; }, []); const buildEnterTextPlace = (0, react_1.useCallback)((venue) => { if (!venue) return undefined; const place = {}; if (venue.latitude != null && venue.longitude != null) { place.latitude = venue.latitude; place.longitude = venue.longitude; if (venue.placeName) place.placeName = venue.placeName; if (venue.uncertainty != null && venue.uncertainty > 0) place.uncertaintyKm = venue.uncertainty; } else if (venue.placeName) { place.placeName = venue.placeName; } return Object.keys(place).length > 0 ? place : undefined; }, []); const getPlaceSpecForEnterText = (0, react_1.useCallback)((venue) => { if (!memori.needsPosition) return undefined; return hasUserProvidedPosition(venue) ? buildEnterTextPlace(venue) : NULL_PLACE_SPEC; }, [memori.needsPosition, hasUserProvidedPosition, buildEnterTextPlace]); const setPosition = (venue) => { _setPosition(venue); if (venue && memori.needsPosition) { (0, configuration_1.setLocalConfig)('position', JSON.stringify(venue)); } else if (!venue) { (0, configuration_1.removeLocalConfig)('position'); } }; (0, react_1.useEffect)(() => { if (memori.needsPosition) { const position = (0, configuration_1.getLocalConfig)('position', undefined); if (position) { _setPosition(position); } } }, [memori.needsPosition]); const [userMessage, setUserMessage] = (0, react_1.useState)(''); const onChangeUserMessage = (value) => { if (!value || value === '\n' || value.trim() === '') { setUserMessage(''); return; } setUserMessage(value); clearInteractionTimeout(); }; const [listening, setListening] = (0, react_1.useState)(false); const [history, setHistory] = (0, react_1.useState)([]); const pushMessage = (message) => { setHistory(history => { var _a, _b; return [ ...history, { ...message, media: (_b = (_a = message.media) === null || _a === void 0 ? void 0 : _a.filter(m => { var _a; return !(m.mimeType === 'text/javascript' && !!((_a = m.properties) === null || _a === void 0 ? void 0 : _a.executable)); })) !== null && _b !== void 0 ? _b : [], }, ]; }); }; const [chatLogID, setChatLogID] = (0, react_1.useState)(undefined); const sendMessage = async (text, media, newSessionId, translate = true, translatedText, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false, skipHistoryPush = false) => { var _a, _b; const sessionID = newSessionId || sessionId || ((_a = window.getMemoriState()) === null || _a === void 0 ? void 0 : _a.sessionID); if (!sessionID || !(text === null || text === void 0 ? void 0 : text.length)) return; let msg = text; if (!hidden && translate && isMultilanguageEnabled && userLang.toUpperCase() !== language.toUpperCase()) { const translation = await (0, translations_1.getTranslation)(text, language, userLang, baseUrl); msg = translation.text; } const mediaDocuments = media === null || media === void 0 ? void 0 : media.filter(m => { var _a; return m.type === 'document' && ((_a = m.properties) === null || _a === void 0 ? void 0 : _a.isAttachedFile); }); if (mediaDocuments && mediaDocuments.length > 0) { const documentContents = mediaDocuments.map(doc => doc.content).join(' '); msg = msg + ' ' + documentContents; } if (piiDetection === null || piiDetection === void 0 ? void 0 : piiDetection.enabled) { const piiResult = (0, piiDetection_1.checkPii)(msg, piiDetection, (userLang === null || userLang === void 0 ? void 0 : userLang.toLowerCase()) || 'en'); if (piiResult.matched && piiResult.errorText) { if (!hidden) { pushMessage({ text: text, translatedText, fromUser: true, media: media !== null && media !== void 0 ? media : [], initial: sessionId ? !!newSessionId && newSessionId !== sessionId : !!newSessionId, }); } pushMessage({ text: piiResult.errorText, emitter: 'system', fromUser: false, initial: false, contextVars: {}, date: new Date().toISOString(), }); return; } } if (!hidden && !skipHistoryPush) pushMessage({ text: text, translatedText, fromUser: true, media: media !== null && media !== void 0 ? media : [], initial: sessionId ? !!newSessionId && newSessionId !== sessionId : !!newSessionId, }); let gotError = false; try { const placeSpec = getPlaceSpecForEnterText(position); const response = await postEnterTextAsync({ sessionId: sessionID, text: msg, ...(memori.needsDateTime && { dateUTC: (_b = luxon_1.DateTime.utc().toISO()) !== null && _b !== void 0 ? _b : undefined, }), ...(placeSpec !== undefined && { place: placeSpec }), }); const correlationID = readCorrelationID(response); if (response.resultCode === 0 && correlationID) { registerPendingEnterText(correlationID, { msg, text, media, translate, translatedText, hidden, typingText, useLoaderTextAsMsg, hasBatchQueued, }); setMemoriTyping(true); setTypingText(typingText); } else if (response.resultCode === 0) { logWidgetError('enter-text missing correlationID', response); } else if (response.resultCode === 404) { retryAfterExpiredSessionRef.current({ text, media, translate, translatedText, hidden, typingText, useLoaderTextAsMsg, hasBatchQueued, expiredSessionID: sessionID, continueFromChatLogID: chatLogID, }); } else if (response.resultCode === 500 && response.resultMessage) { setHistory(h => [ ...h, { text: 'Error: ' + response.resultMessage, emitter: 'system', fromUser: false, initial: false, contextVars: {}, date: new Date().toISOString(), }, ]); } else { return Promise.reject(response); } } catch (error) { gotError = true; logWidgetError('sendMessage failed', error); setTypingText(undefined); setMemoriTyping(false); } }; const translateDialogState = async (state, userLang, msg, avoidPushingMessage = false) => { var _a, _b, _c, _d, _f, _g; const emission = (_a = state === null || state === void 0 ? void 0 : state.emission) !== null && _a !== void 0 ? _a : currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.emission; let translatedState = { ...state }; let translatedMsg = null; if (!emission || language.toUpperCase() === userLang.toUpperCase() || !isMultilanguageEnabled || avoidPushingMessage) { translatedState = { ...state, emission }; if (emission) { translatedMsg = { text: emission, emitter: state.emitter, media: (_b = state.emittedMedia) !== null && _b !== void 0 ? _b : state.media, llmUsage: state.llmUsage, fromUser: false, questionAnswered: msg, contextVars: state.contextVars, date: state.currentDate, placeName: state.currentPlaceName, placeLatitude: state.currentLatitude, placeLongitude: state.currentLongitude, placeUncertaintyKm: state.currentUncertaintyKm, tag: state.currentTag, memoryTags: state.memoryTags, }; } } else { try { const t = await (0, translations_1.getTranslation)(emission, userLang, language, baseUrl); if (state.hints && state.hints.length > 0) { const translatedHints = await Promise.all(((_c = state.hints) !== null && _c !== void 0 ? _c : []).map(async (hint) => { var _a; const tHint = await (0, translations_1.getTranslation)(hint, userLang, language, baseUrl); return { text: (_a = tHint === null || tHint === void 0 ? void 0 : tHint.text) !== null && _a !== void 0 ? _a : hint, originalText: hint, }; })); translatedState = { ...state, emission: t.text, translatedHints, }; } else { translatedState = { ...state, emission: emission, translatedEmission: t.text, hints: (_d = state.hints) !== null && _d !== void 0 ? _d : (state.state === 'G1' ? currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.hints : []), }; } if (t.text.length > 0) { translatedMsg = { text: emission, translatedText: t.text, emitter: state.emitter, media: (_f = state.emittedMedia) !== null && _f !== void 0 ? _f : state.media, llmUsage: state.llmUsage, fromUser: false, questionAnswered: msg, generatedByAI: !!state.completion, contextVars: state.contextVars, date: state.currentDate, placeName: state.currentPlaceName, placeLatitude: state.currentLatitude, placeLongitude: state.currentLongitude, placeUncertaintyKm: state.currentUncertaintyKm, tag: state.currentTag, memoryTags: state.memoryTags, }; } } catch (error) { translatedState = { ...state, emission }; translatedMsg = { text: emission, emitter: state.emitter, media: (_g = state.emittedMedia) !== null && _g !== void 0 ? _g : state.media, llmUsage: state.llmUsage, fromUser: false, questionAnswered: msg, contextVars: state.contextVars, date: state.currentDate, placeName: state.currentPlaceName, placeLatitude: state.currentLatitude, placeLongitude: state.currentLongitude, placeUncertaintyKm: state.currentUncertaintyKm, tag: state.currentTag, memoryTags: state.memoryTags, }; } } setCurrentDialogState(translatedState); if (!avoidPushingMessage && translatedMsg) { pushMessage(translatedMsg); } return translatedState; }; const minAge = memori.ageRestriction !== undefined ? memori.ageRestriction : memori.nsfw ? 18 : memori.enableCompletions ? 14 : 0; const [birthDate, setBirthDate] = (0, react_1.useState)(); const [showAgeVerification, setShowAgeVerification] = (0, react_1.useState)(false); const getCultureCodeByLanguage = (lang) => { var _a, _b; let voice = ''; let voiceLang = (lang || ((_b = (_a = memori.culture) === null || _a === void 0 ? void 0 : _a.split('-')) === null || _b === void 0 ? void 0 : _b[0]) || i18n.language || 'IT').toUpperCase(); switch (voiceLang) { case 'IT': voice = 'it-IT'; break; case 'DE': voice = 'de-DE'; break; case 'EN': voice = 'en-GB'; break; case 'ES': voice = 'es-ES'; break; case 'FR': voice = 'fr-FR'; break; case 'PT': voice = 'pt-PT'; break; case 'UK': voice = 'uk-UK'; break; case 'RU': voice = 'ru-RU'; break; case 'PL': voice = 'pl-PL'; break; case 'FI': voice = 'fi-FI'; break; case 'EL': voice = 'el-GR'; break; case 'AR': voice = 'ar-SA'; break; case 'ZH': voice = 'zh-CN'; break; case 'JA': voice = 'ja-JP'; break; default: voice = 'it-IT'; break; } return voice; }; const [sessionId, setSessionId] = (0, react_1.useState)(initialSessionID); const [currentDialogState, _setCurrentDialogState] = (0, react_1.useState)(); const setCurrentDialogState = (state) => { var _a, _b; _setCurrentDialogState(state); if (onStateChange) { onStateChange(state); } const e = new CustomEvent('MemoriNewDialogState', { detail: state, }); document.dispatchEvent(e); const executableSnippets = (_b = ((_a = state === null || state === void 0 ? void 0 : state.emittedMedia) !== null && _a !== void 0 ? _a : state === null || state === void 0 ? void 0 : state.media)) === null || _b === void 0 ? void 0 : _b.filter(m => { var _a; return m.mimeType === 'text/javascript' && !!((_a = m.properties) === null || _a === void 0 ? void 0 : _a.executable); }); executableSnippets === null || executableSnippets === void 0 ? void 0 : executableSnippets.forEach(s => { try { setTimeout(() => { var _a; new Function((_a = s.content) !== null && _a !== void 0 ? _a : '')(); setTimeout(() => { var _a, _b, _c; (_a = document .querySelector('.memori-chat--content')) === null || _a === void 0 ? void 0 : _a.scrollTo(0, (_c = (_b = document.querySelector('.memori-chat--content')) === null || _b === void 0 ? void 0 : _b.scrollHeight) !== null && _c !== void 0 ? _c : 0); }, 400); }, 1000); } catch (_a) { } }); }; (0, react_1.useEffect)(() => { if (initialSessionID) { setSessionId(initialSessionID); onClickStart(undefined, false, undefined, initialSessionID); } }, [initialSessionID]); const fetchSession = async (params) => { var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l; let storageBirthDate = (0, configuration_1.getLocalConfig)('birthDate', undefined); let userBirthDate = (_a = birthDate !== null && birthDate !== void 0 ? birthDate : params.birthDate) !== null && _a !== void 0 ? _a : storageBirthDate; if (!userBirthDate && !!minAge) { setShowAgeVerification(true); return; } if (memori.privacyType !== 'PUBLIC' && !memori.secretToken && !memoriPwd && !memoriTokens) { setAuthModalState('password'); return; } if (!(await checkCredits({ notify: true }))) { return; } setLoading(true); try { let referral; try { referral = (() => { return window.location.href; })(); } catch (_m) { } const session = await initSession({ ...params, birthDate: userBirthDate, tag: (_b = params.tag) !== null && _b !== void 0 ? _b : personification === null || personification === void 0 ? void 0 : personification.tag, pin: (_c = params.pin) !== null && _c !== void 0 ? _c : personification === null || personification === void 0 ? void 0 : personification.pin, additionalInfo: { ...(params.additionalInfo || additionalInfo || {}), 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, 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(), referral: referral, timeZoneOffset: new Date().getTimezoneOffset().toString(), }, }); if ((session === null || session === void 0 ? void 0 : session.sessionID) && (session === null || session === void 0 ? void 0 : session.currentState) && session.resultCode === 0) { setSessionId(session.sessionID); if ((currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.currentTag) && memori.giverTag) { setInstruct((currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.currentTag) === memori.giverTag); } else { setInstruct(false); } setLoading(false); return { dialogState: session.currentState, sessionID: session.sessionID, }; } else if (session === null || session === void 0 ? void 0 : session.resultMessage.startsWith('This Memori is aged restricted')) { react_hot_toast_1.default.error(t('underageTwinSession', { age: minAge })); } else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 403 && memori.privacyType !== 'PUBLIC') { setMemoriPwd(undefined); setAuthModalState('password'); return session; } else { react_hot_toast_1.default.error(tst => ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("p", { children: t((0, error_1.getErrori18nKey)(session === null || session === void 0 ? void 0 : session.resultCode)) }), (0, jsx_runtime_1.jsx)(Button_1.default, { outlined: true, padded: false, onClick: () => react_hot_toast_1.default.dismiss(tst.id), icon: (0, jsx_runtime_1.jsx)(Close_1.default, {}), children: t('close') })] })), { duration: Infinity, }); return session; } } catch (err) { logWidgetError('fetchSession failed', err); } }; const reopenSession = async (updateDialogState = false, password, recoveryTokens, tag, pin, initialContextVars, initialQuestion, birthDate, additionalInfoProp, continueFromChatLogID, continueFromSessionID, isSessionExpired, suppressHistoryUpdate) => { var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m; setLoading(true); let storageBirthDate = (0, configuration_1.getLocalConfig)('birthDate', undefined); let userBirthDate = birthDate !== null && birthDate !== void 0 ? birthDate : storageBirthDate; try { if (!userBirthDate && !!minAge) { setShowAgeVerification(true); return; } if (memori.privacyType !== 'PUBLIC' && !password && !memori.secretToken && !memoriPwd && !recoveryTokens && !memoriTokens) { setAuthModalState('password'); return; } if (!(await checkCredits({ notify: true }))) { setLoading(false); return null; } let referral; try { referral = (() => { return window.location.href; })(); } catch (_o) { } const { sessionID, currentState, ...response } = await initSession({ memoriID: (_a = memori.engineMemoriID) !== null && _a !== void 0 ? _a : '', password: password || memoriPwd || memori.secretToken, recoveryTokens: recoveryTokens || memoriTokens, tag: tag !== null && tag !== void 0 ? tag : personification === null || personification === void 0 ? void 0 : personification.tag, pin: pin !== null && pin !== void 0 ? pin : personification === null || personification === void 0 ? void 0 : personification.pin, continueFromChatLogID: continueFromChatLogID, continueFromSessionID: continueFromSessionID, initialContextVars: { LANG: userLang, PATHNAME: window.location.pathname, ROUTE: ((_c = (_b = window.location.pathname) === null || _b === void 0 ? void 0 : _b.split('/')) === null || _c === void 0 ? void 0 : _c.pop()) || '', ...(initialContextVars || {}), }, initialQuestion, birthDate: userBirthDate, additionalInfo: { ...(additionalInfoProp || additionalInfo || {}), 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, 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(), referral: referral, timeZoneOffset: new Date().getTimezoneOffset().toString(), }, }); if (sessionID && currentState && response.resultCode === 0) { setSessionId(sessionID); if (updateDialogState) { setCurrentDialogState(currentState); const sessionExpiredStatus = isSessionExpired && history.length > 1 ? t('sessionExpiredReopening') : null; if (sessionExpiredStatus && suppressHistoryUpdate) { pushMessage({ text: '', emitter: 'system', fromUser: false, initial: sessionExpiredStatus, contextVars: {}, date: new Date().toISOString(), }); } if (currentState.emission && !suppressHistoryUpdate) { const initialStatus = sessionExpiredStatus ? sessionExpiredStatus : history.length <= 1 ? true : undefined; history.length <= 1 ? setHistory([ { text: currentState.emission, emitter: currentState.emitter, media: (_l = currentState.emittedMedia) !== null && _l !== void 0 ? _l : currentState.media, fromUser: false, initial: (initialStatus === true ? true : initialStatus || undefined), contextVars: currentState.contextVars, date: currentState.currentDate, placeName: currentState.currentPlaceName, placeLatitude: currentState.currentLatitude, placeLongitude: currentState.currentLongitude, placeUncertaintyKm: currentState.currentUncertaintyKm, tag: currentState.currentTag, memoryTags: currentState.memoryTags, }, ]) : pushMessage({ text: currentState.emission, emitter: currentState.emitter, media: (_m = currentState.emittedMedia) !== null && _m !== void 0 ? _m : currentState.media, fromUser: false, initial: (initialStatus === true ? true : initialStatus || undefined), contextVars: currentState.contextVars, date: currentState.currentDate, placeName: currentState.currentPlaceName, placeLatitude: currentState.currentLatitude, placeLongitude: currentState.currentLongitude, placeUncertaintyKm: currentState.currentUncertaintyKm, tag: currentState.currentTag, memoryTags: currentState.memoryTags, }); } } setLoading(false); return { dialogState: currentState, sessionID, }; } else if (response === null || response === void 0 ? void 0 : response.resultMessage.startsWith('This Memori is aged restricted')) { react_hot_toast_1.default.error(t('underageTwinSession',