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

946 lines (945 loc) 130 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { useState, useEffect, useCallback, useRef, } from 'react'; import { useTranslation } from 'react-i18next'; import memoriApiClient from '@memori.ai/memori-api-client'; import { AudioContext } from 'standardized-audio-context'; import * as speechSdk from 'microsoft-cognitiveservices-speech-sdk'; import cx from 'classnames'; import { DateTime } from 'luxon'; import toast from 'react-hot-toast'; import PositionDrawer from '../PositionDrawer/PositionDrawer'; import MemoriAuth from '../Auth/Auth'; import Chat from '../Chat/Chat'; import StartPanel from '../StartPanel/StartPanel'; import Avatar from '../Avatar/Avatar'; import Header from '../Header/Header'; import PoweredBy from '../PoweredBy/PoweredBy'; import AgeVerificationModal from '../AgeVerificationModal/AgeVerificationModal'; import SettingsDrawer from '../SettingsDrawer/SettingsDrawer'; import KnownFacts from '../KnownFacts/KnownFacts'; import ExpertsDrawer from '../ExpertsDrawer/ExpertsDrawer'; import LoginDrawer from '../LoginDrawer/LoginDrawer'; import Button from '../ui/Button'; import CloseIcon from '../icons/Close'; import FullPageLayout from '../layouts/FullPage'; import TotemLayout from '../layouts/Totem'; import ChatLayout from '../layouts/Chat'; import WebsiteAssistantLayout from '../layouts/WebsiteAssistant'; import HiddenChatLayout from '../layouts/HiddenChat'; import ZoomedFullBodyLayout from '../layouts/ZoomedFullBody'; import { getTranslation } from '../../helpers/translations'; import { setLocalConfig, getLocalConfig, removeLocalConfig, } from '../../helpers/configuration'; import { hasTouchscreen, stripDuplicates, stripEmojis, escapeHTML, stripMarkdown, stripOutputTags, stripHTML, installMathJax, } from '../../helpers/utils'; import { allowedMediaTypes, anonTag, uiLanguages, } from '../../helpers/constants'; import { getErrori18nKey } from '../../helpers/error'; import { getCredits } from '../../helpers/credits'; import { useViseme } from '../../context/visemeContext'; import ChatHistoryDrawer from '../ChatHistoryDrawer/ChatHistory'; 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 = getLocalConfig('loginToken', undefined); return { ...dialogState, loginToken, }; }; 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 recognizer; let speechConfig; let speechSynthesizer; let audioDestination; let audioContext; let memoriPassword; let speakerMuted = false; let memoriSpeaking = false; let userToken; const MemoriWidget = ({ memori, memoriConfigs, ownerUserID, ownerUserName, tenantID, memoriLang, multilingual, integration, layout, customLayout, showShare, preview = false, embed = false, showCopyButton = true, showTranslationOriginal = false, showInputs = true, showDates = false, showContextPerLine = false, showSettings, showTypingText = false, showClear = false, showLogin = false, showUpload, showOnlyLastMessages, showChatHistory, showReasoning, height = '100vh', secret, baseUrl = 'https://aisuru.com', apiURL = 'https://backend-staging.memori.ai', engineURL = 'https://engine-staging.memori.ai', initialContextVars, initialQuestion, ogImage, sessionID: initialSessionID, tenant, personification, authToken, AZURE_COGNITIVE_SERVICES_TTS_KEY, enableAudio, defaultSpeakerActive = true, disableTextEnteredEvents = false, onStateChange, additionalInfo, additionalSettings, customMediaRenderer, userAvatar, useMathFormatting = false, autoStart = false, applyVarsToRoot = false, showFunctionCache = false, }) => { 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; const { t, i18n } = useTranslation(); const [isClient, setIsClient] = useState(false); useEffect(() => { setIsClient(true); }, []); const client = memoriApiClient(apiURL, engineURL); const { initSession, deleteSession, postTextEnteredEvent, postPlaceChangedEvent, postDateChangedEvent, postTimeoutEvent, postTagChangedEvent, getSession, getExpertReferences, getSessionChatLogs, } = client; const [instruct, setInstruct] = useState(false); const [enableFocusChatInput, setEnableFocusChatInput] = useState(true); const [loginToken, setLoginToken] = useState((_a = additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _a !== void 0 ? _a : authToken); const [user, setUser] = useState({ avatarURL: typeof userAvatar === 'string' ? userAvatar : undefined, }); useEffect(() => { if (loginToken && !(user === null || user === void 0 ? void 0 : user.userID) && (showLogin || memori.requireLoginToken)) { client.backend.getCurrentUser(loginToken).then(({ user, resultCode }) => { if (user && resultCode === 0) { setUser(user); setLocalConfig('loginToken', loginToken); if (!birthDate && user.birthDate) { setBirthDate(user.birthDate); setLocalConfig('birthDate', user.birthDate); } } else { removeLocalConfig('loginToken'); } }); } }, [loginToken, user === null || user === void 0 ? void 0 : user.userID]); const [showLoginDrawer, setShowLoginDrawer] = useState(false); const [clickedStart, setClickedStart] = useState(false); const [gotErrorInOpening, setGotErrorInOpening] = useState(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] = useState((_o = (_m = (_l = (_k = memoriLang !== null && memoriLang !== void 0 ? memoriLang : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.lang) !== null && _k !== void 0 ? _k : language) !== null && _l !== void 0 ? _l : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.uiLang) !== null && _m !== void 0 ? _m : i18n.language) !== null && _o !== void 0 ? _o : 'IT'); const applyMathFormatting = useMathFormatting !== undefined ? useMathFormatting : !!(integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.useMathFormatting); useEffect(() => { if (applyMathFormatting) installMathJax(); }, [applyMathFormatting]); useEffect(() => { if (isMultilanguageEnabled && userLang && uiLanguages.includes(userLang.toLowerCase())) { i18n.changeLanguage(userLang.toLowerCase()); } }, [userLang]); const [loading, setLoading] = useState(false); const [memoriTyping, setMemoriTyping] = useState(false); const [typingText, setTypingText] = useState(); const selectedLayout = layout || (integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.layout) || 'DEFAULT'; const defaultEnableAudio = (_p = enableAudio !== null && enableAudio !== void 0 ? enableAudio : integrationConfig === null || integrationConfig === void 0 ? void 0 : integrationConfig.enableAudio) !== null && _p !== void 0 ? _p : false; const [hasUserActivatedSpeak, setHasUserActivatedSpeak] = useState(false); const [hasUserActivatedListening, setHasUserActivatedListening] = useState(false); const [showPositionDrawer, setShowPositionDrawer] = useState(false); const [showSettingsDrawer, setShowSettingsDrawer] = useState(false); const [showChatHistoryDrawer, setShowChatHistoryDrawer] = useState(false); const [showKnownFactsDrawer, setShowKnownFactsDrawer] = useState(false); const [showExpertsDrawer, setShowExpertsDrawer] = useState(false); const [muteSpeaker, setMuteSpeaker] = useState(!defaultEnableAudio || !defaultSpeakerActive || autoStart); const [continuousSpeech, setContinuousSpeech] = useState(false); const [continuousSpeechTimeout, setContinuousSpeechTimeout] = useState(2); const [isPlayingAudio, setIsPlayingAudio] = useState(false); const [controlsPosition, setControlsPosition] = useState('center'); const [enablePositionControls, setEnablePositionControls] = useState(false); const [avatarType, setAvatarType] = useState(null); const [hideEmissions, setHideEmissions] = useState(false); const { startProcessing, setAudioContext, addViseme, stopProcessing, resetVisemeQueue, } = useViseme(); useEffect(() => { memoriSpeaking = !!speechSynthesizer; }, [speechSynthesizer]); useEffect(() => { let defaultControlsPosition = 'bottom'; let microphoneMode = 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'; } const muteSpeaker = autoStart || getLocalConfig('muteSpeaker', !defaultEnableAudio || !defaultSpeakerActive || autoStart); setMuteSpeaker(muteSpeaker); speakerMuted = muteSpeaker; setContinuousSpeech(muteSpeaker ? false : microphoneMode === 'CONTINUOUS'); setContinuousSpeechTimeout(getLocalConfig('continuousSpeechTimeout', 2)); setControlsPosition(getLocalConfig('controlsPosition', defaultControlsPosition)); setAvatarType(getLocalConfig('avatarType', 'avatar3d')); setHideEmissions(getLocalConfig('hideEmissions', false)); if (!(additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) && !authToken) { setLoginToken(getLocalConfig('loginToken', undefined)); userToken = getLocalConfig('loginToken', undefined); setBirthDate(getLocalConfig('birthDate', undefined)); } }, []); const [memoriPwd, setMemoriPwd] = useState(secret); const [memoriTokens, setMemoriTokens] = useState(); const [authModalState, setAuthModalState] = useState(null); const [position, _setPosition] = useState(); const applyPosition = async (venue, sessionID) => { var _a; const session = sessionID !== null && sessionID !== void 0 ? sessionID : sessionId; if (venue && session && memori.needsPosition) { const { currentState, ...response } = await postPlaceChangedEvent({ sessionId: session, placeName: venue.placeName, latitude: venue.latitude, longitude: venue.longitude, uncertaintyKm: (_a = venue.uncertainty) !== null && _a !== void 0 ? _a : 0, }); if (currentState && response.resultCode === 0) { _setCurrentDialogState(cds => { var _a; return ({ ...cds, ...currentState, hints: ((_a = currentState.hints) === null || _a === void 0 ? void 0 : _a.length) ? currentState.hints : cds === null || cds === void 0 ? void 0 : cds.hints, }); }); } } }; const setPosition = (venue) => { _setPosition(venue); applyPosition(venue); if (venue && memori.needsPosition) { setLocalConfig('position', JSON.stringify(venue)); } else if (!venue) { removeLocalConfig('position'); } }; useEffect(() => { if (memori.needsPosition) { const position = getLocalConfig('position', undefined); if (position) { _setPosition(position); } } }, [memori.needsPosition]); const [userMessage, setUserMessage] = useState(''); const onChangeUserMessage = (value) => { if (!value || value === '\n' || value.trim() === '') { setUserMessage(''); resetInteractionTimeout(); return; } setUserMessage(value); clearInteractionTimeout(); }; const [listening, setListening] = useState(false); const [history, setHistory] = 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] = useState(undefined); const sendMessage = async (text, media, newSessionId, translate = true, translatedText, hidden = false, typingText, useLoaderTextAsMsg = false, hasBatchQueued = false) => { var _a, _b, _c, _d, _f; 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; if (!hidden) pushMessage({ text: text, translatedText, fromUser: true, media: media !== null && media !== void 0 ? media : [], initial: sessionId ? !!newSessionId && newSessionId !== sessionId : !!newSessionId, }); setMemoriTyping(true); setTypingText(typingText); let msg = text; let gotError = false; try { if (!hidden && translate && isMultilanguageEnabled && userLang.toUpperCase() !== language.toUpperCase()) { const translation = await getTranslation(text, language, userLang, baseUrl); msg = translation.text; } const findMediaDocument = media === null || media === void 0 ? void 0 : media.find(m => { var _a; return !m.mediumID && ((_a = m.properties) === null || _a === void 0 ? void 0 : _a.isAttachedFile); }); if (findMediaDocument) { msg = msg + ' ' + findMediaDocument.content; } const mediaDocuments = media === null || media === void 0 ? void 0 : media.filter(m => { var _a; return !m.mediumID && ((_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; } const { currentState, ...response } = await postTextEnteredEvent({ sessionId: sessionID, text: msg, }); if (response.resultCode === 0 && currentState) { setChatLogID(undefined); const emission = useLoaderTextAsMsg && typingText ? typingText : (_b = currentState.emission) !== null && _b !== void 0 ? _b : currentDialogState === null || currentDialogState === void 0 ? void 0 : currentDialogState.emission; if (userLang.toLowerCase() !== language.toLowerCase() && emission && isMultilanguageEnabled) { currentState.emission = emission; translateDialogState(currentState, userLang, msg).then(ts => { let text = ts.translatedEmission || ts.emission; if (text) { speak(text); } }); } else { setCurrentDialogState({ ...currentState, emission, }); if (emission) { pushMessage({ text: emission, emitter: currentState.emitter, media: (_c = currentState.emittedMedia) !== null && _c !== void 0 ? _c : currentState.media, fromUser: false, questionAnswered: msg, generatedByAI: !!currentState.completion, contextVars: currentState.contextVars, date: currentState.currentDate, placeName: currentState.currentPlaceName, placeLatitude: currentState.currentLatitude, placeLongitude: currentState.currentLongitude, placeUncertaintyKm: currentState.currentUncertaintyKm, tag: currentState.currentTag, memoryTags: currentState.memoryTags, }); speak(emission); } } } else if (response.resultCode === 404) { setHistory(h => [...h.slice(0, h.length - 1)]); reopenSession(false, memoriPwd || memori.secretToken, memoriTokens, undefined, undefined, { PATHNAME: window.location.pathname, ROUTE: ((_f = (_d = window.location.pathname) === null || _d === void 0 ? void 0 : _d.split('/')) === null || _f === void 0 ? void 0 : _f.pop()) || '', ...(initialContextVars || {}), }, initialQuestion).then(state => { console.info('session timeout'); if (state === null || state === void 0 ? void 0 : state.sessionID) { setTimeout(() => { sendMessage(text, media, state === null || state === void 0 ? void 0 : state.sessionID); }, 500); } }); } } catch (error) { console.error(error); gotError = true; setTypingText(undefined); setMemoriTyping(false); } if (!hasBatchQueued) { 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, 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 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 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, 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) { console.error('[TRANSLATE] Error during translation:', error); translatedState = { ...state, emission }; translatedMsg = { text: emission, emitter: state.emitter, media: (_g = state.emittedMedia) !== null && _g !== void 0 ? _g : state.media, 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] = useState(); const [showAgeVerification, setShowAgeVerification] = useState(false); const [sessionId, setSessionId] = useState(initialSessionID); const [currentDialogState, _setCurrentDialogState] = 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; console.log('snippet', s); 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 (e) { console.warn(e); } }); }; const fetchSession = async (params) => { var _a, _b, _c, _d, _f; let storageBirthDate = 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; } setLoading(true); try { let referral; try { referral = (() => { return window.location.href; })(); } catch (err) { console.debug(err); } 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: { ...(additionalInfo || {}), loginToken: (_f = (_d = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _d !== void 0 ? _d : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _f !== void 0 ? _f : authToken, language: getCultureCodeByLanguage(userLang), 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); } if (position && memori.needsPosition) applyPosition(position, session.sessionID); 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')) { console.warn(session); toast.error(t('underageTwinSession', { age: minAge })); setGotErrorInOpening(true); } else if ((session === null || session === void 0 ? void 0 : session.resultCode) === 403) { setMemoriPwd(undefined); setAuthModalState('password'); return session; } else { console.warn(session); toast.error(tst => (_jsxs("div", { children: [_jsx("p", { children: t(getErrori18nKey(session === null || session === void 0 ? void 0 : session.resultCode)) }), _jsx(Button, { outlined: true, padded: false, onClick: () => toast.dismiss(tst.id), icon: _jsx(CloseIcon, {}), children: t('close') })] })), { duration: Infinity, }); setGotErrorInOpening(true); return session; } } catch (err) { console.error(err); } }; const reopenSession = async (updateDialogState = false, password, recoveryTokens, tag, pin, initialContextVars, initialQuestion, birthDate) => { var _a, _b, _c, _d, _f, _g, _h; setLoading(true); let storageBirthDate = 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; } let referral; try { referral = (() => { return window.location.href; })(); console.log('[REOPEN_SESSION] Got referral:', referral); } catch (err) { console.debug('[REOPEN_SESSION] Error getting referral:', err); } 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, initialContextVars: { 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: { ...(additionalInfo || {}), loginToken: (_f = (_d = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _d !== void 0 ? _d : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _f !== void 0 ? _f : authToken, language: getCultureCodeByLanguage(userLang), referral: referral, timeZoneOffset: new Date().getTimezoneOffset().toString(), }, }); if (sessionID && currentState && response.resultCode === 0) { setSessionId(sessionID); if (updateDialogState) { setCurrentDialogState(currentState); if (currentState.emission) { history.length <= 1 ? setHistory([ { text: currentState.emission, emitter: currentState.emitter, media: (_g = currentState.emittedMedia) !== null && _g !== void 0 ? _g : currentState.media, fromUser: false, initial: true, 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: (_h = currentState.emittedMedia) !== null && _h !== void 0 ? _h : currentState.media, fromUser: false, initial: true, contextVars: currentState.contextVars, date: currentState.currentDate, placeName: currentState.currentPlaceName, placeLatitude: currentState.currentLatitude, placeLongitude: currentState.currentLongitude, placeUncertaintyKm: currentState.currentUncertaintyKm, tag: currentState.currentTag, memoryTags: currentState.memoryTags, }); } } if (position && memori.needsPosition) { applyPosition(position, sessionID); } if (memori.needsDateTime) { sendDateChangedEvent({ sessionID: sessionID, state: currentState }); } setLoading(false); return { dialogState: currentState, sessionID, }; } else if (response === null || response === void 0 ? void 0 : response.resultMessage.startsWith('This Memori is aged restricted')) { console.error('[REOPEN_SESSION] Age restriction error:', response); toast.error(t('underageTwinSession', { age: minAge })); setGotErrorInOpening(true); } else if ((response === null || response === void 0 ? void 0 : response.resultCode) === 403) { console.error('[REOPEN_SESSION] Authentication error'); setMemoriPwd(undefined); setAuthModalState('password'); } else { console.error('[REOPEN_SESSION] Other error:', response); toast.error(t(getErrori18nKey(response.resultCode))); setGotErrorInOpening(true); } } catch (err) { console.error('[REOPEN_SESSION] Caught error:', err); } setLoading(false); return null; }; const [chatLogs, setChatLogs] = useState([]); const resumeSession = async (chatLog, questionsAndAnswers, initialContextVars, initialQuestion, birthDate) => { var _a, _b, _c, _d, _f; setLoading(true); let storageBirthDate = getLocalConfig('birthDate', undefined); let userBirthDate = birthDate !== null && birthDate !== void 0 ? birthDate : storageBirthDate; try { if (!userBirthDate && !!minAge) { setShowAgeVerification(true); return; } if (memori.privacyType !== 'PUBLIC' && !memoriPassword && !memori.secretToken && !memoriPwd && !memoriTokens) { setAuthModalState('password'); return; } let referral; try { referral = (() => { return window.location.href; })(); console.log('[REOPEN_SESSION] Got referral:', referral); } catch (err) { console.debug('[REOPEN_SESSION] Error getting referral:', err); } const { sessionID, currentState, ...response } = await initSession({ memoriID: (_a = memori.engineMemoriID) !== null && _a !== void 0 ? _a : '', password: memoriPassword || memoriPwd || memori.secretToken, recoveryTokens: memoriTokens, tag: personification === null || personification === void 0 ? void 0 : personification.tag, pin: personification === null || personification === void 0 ? void 0 : personification.pin, continueFromChatLogID: chatLog.chatLogID, initialContextVars: { 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: { ...(additionalInfo || {}), loginToken: (_f = (_d = userToken !== null && userToken !== void 0 ? userToken : loginToken) !== null && _d !== void 0 ? _d : additionalInfo === null || additionalInfo === void 0 ? void 0 : additionalInfo.loginToken) !== null && _f !== void 0 ? _f : authToken, language: getCultureCodeByLanguage(userLang), referral: referral, timeZoneOffset: new Date().getTimezoneOffset().toString(), }, }); if (sessionID) { setSessionId(sessionID); setHistory(chatLog.lines.map(log => { var _a; return ({ text: log.text, emitter: log.emitter, media: (_a = log.media) === null || _a === void 0 ? void 0 : _a.map(m => ({ ...m, mediumID: 'mediumID' in m ? String(m.mediumID) : crypto.randomUUID(), })), fromUser: log.inbound, initial: false, contextVars: log.contextVars, date: log.timestamp, }); })); setChatLogs(questionsAndAnswers); } else if (response === null || response === void 0 ? void 0 : response.resultMessage.startsWith('This Memori is aged restricted')) { console.error('[REOPEN_SESSION] Age restriction error:', response); toast.error(t('underageTwinSession', { age: minAge })); setGotErrorInOpening(true); } else if ((response === null || response === void 0 ? void 0 : response.resultCode) === 403) { console.error('[REOPEN_SESSION] Authentication error'); setMemoriPwd(undefined); setAuthModalState('password'); } else { console.error('[REOPEN_SESSION] Other error:', response); toast.error(t(getErrori18nKey(response.resultCode))); setGotErrorInOpening(true); } } catch (err) { console.error('[RESUME_SESSION] Caught error:', err); } setLoading(false); }; const changeTag = async (memoriId, sessionId, tag, pin) => { var _a, _b, _c, _d, _f; if (!memoriId || !sessionId) { console.error('CHANGETAG/Session not found'); return Promise.reject('Session not found'); } try { const { currentState, resultCode } = await postTagChangedEvent(sessionId, tag !== null && tag !== void 0 ? tag : anonTag); if (resultCode === 0) { let textResult = 0; if (tag !== anonTag && pin && (currentState.state === 'X1a' || currentState.state === 'X1b')) { const { resultCode: textResultCode } = await postTextEnteredEvent({ sessionId, text: pin !== null && pin !== void 0 ? pin : '', }); textResult = textResultCode; } if (textResult === 0) { const { currentState, ...response } = await getSession(sessionId); if (response.resultCode === 0 && !!currentState) { return { currentState, sessionId, ...response, }; } } else if ([400, 401, 403, 404, 500].includes(resultCode)) { console.warn('[APPCONTEXT/CHANGETAG]', resultCode); let storageBirthDate = getLocalConfig('birthDate', undefined); let referral; try { referral = (() => { return window.location.href; })(); } catch (err) { console.debug(err); } fetchSession({ memoriID: (_a = memori.engineMemoriID) !== null && _a !== void 0 ? _a : '', password: secret || memoriPwd || memori.secretToken, 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, initialContextVars: { 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: birthDate || storageBirthDate || undefined, additionalInfo: { ...(additionalInfo || {}),