@memori.ai/memori-react
Version:
[](https://www.npmjs.com/package/@memori.ai/memori-react)  ;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
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 standardized_audio_context_1 = require("standardized-audio-context");
const speechSdk = tslib_1.__importStar(require("microsoft-cognitiveservices-speech-sdk"));
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 constants_1 = require("../../helpers/constants");
const error_1 = require("../../helpers/error");
const credits_1 = require("../../helpers/credits");
const visemeContext_1 = require("../../context/visemeContext");
const ChatHistory_1 = tslib_1.__importDefault(require("../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 = (0, configuration_1.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 } = (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, postTextEnteredEvent, postPlaceChangedEvent, postDateChangedEvent, postTimeoutEvent, 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.getCurrentUser(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 [gotErrorInOpening, setGotErrorInOpening] = (0, react_1.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] = (0, react_1.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);
(0, react_1.useEffect)(() => {
if (applyMathFormatting)
(0, utils_1.installMathJax)();
}, [applyMathFormatting]);
(0, react_1.useEffect)(() => {
if (isMultilanguageEnabled &&
userLang &&
constants_1.uiLanguages.includes(userLang.toLowerCase())) {
i18n.changeLanguage(userLang.toLowerCase());
}
}, [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 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] = (0, react_1.useState)(false);
const [hasUserActivatedListening, setHasUserActivatedListening] = (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 [muteSpeaker, setMuteSpeaker] = (0, react_1.useState)(!defaultEnableAudio || !defaultSpeakerActive || autoStart);
const [continuousSpeech, setContinuousSpeech] = (0, react_1.useState)(false);
const [continuousSpeechTimeout, setContinuousSpeechTimeout] = (0, react_1.useState)(2);
const [isPlayingAudio, setIsPlayingAudio] = (0, react_1.useState)(false);
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 { startProcessing, setAudioContext, addViseme, stopProcessing, resetVisemeQueue, } = (0, visemeContext_1.useViseme)();
(0, react_1.useEffect)(() => {
memoriSpeaking = !!speechSynthesizer;
}, [speechSynthesizer]);
(0, react_1.useEffect)(() => {
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';
}
const muteSpeaker = autoStart ||
(0, configuration_1.getLocalConfig)('muteSpeaker', !defaultEnableAudio || !defaultSpeakerActive || autoStart);
setMuteSpeaker(muteSpeaker);
speakerMuted = muteSpeaker;
setContinuousSpeech(muteSpeaker ? 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));
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));
}
}, []);
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 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) {
(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('');
resetInteractionTimeout();
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) => {
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 (0, translations_1.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 (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,
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] = (0, react_1.useState)();
const [showAgeVerification, setShowAgeVerification] = (0, react_1.useState)(false);
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;
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 = (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;
}
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);
react_hot_toast_1.default.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);
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,
});
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 = (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;
}
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);
react_hot_toast_1.default.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);
react_hot_toast_1.default.error(t((0, error_1.getErrori18nKey)(response.resultCode)));
setGotErrorInOpening(true);
}
}
catch (err) {
console.error('[REOPEN_SESSION] Caught error:', err);
}
setLoading(false);
return null;
};
const [chatLogs, setChatLogs] = (0, react_1.useState)([]);
const resumeSession = async (chatLog, questionsAndAnswers, initialContextVars, initialQuestion, birthDate) => {
var _a, _b, _c, _d, _f;
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' &&
!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);
react_hot_toast_1.default.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);
react_hot_toast_1.default.error(t((0, error_1.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 : constants_1.anonTag);
if (resultCode === 0) {
let textResult = 0;
if (tag !== constants_1.anonTag &&
pin &&
(currentState.state === 'X1a' || currentState.state === 'X1b')) {
const { resultCode: textResultCode } = await postTextEnteredEvent({
sessionId,
text: pin !== null && pin !== void 0 ? pin : '',
});
textResult = textResu