sentifyd-bot 1.1.5 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.es.js +312 -141
  2. package/package.json +2 -2
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import{io as t}from"socket.io-client";import{AudioConfig as e,SpeechRecognizer as i,ResultReason as a,CancellationReason as n,CancellationErrorCode as s,SpeechConfig as o,PropertyId as r,AutoDetectSourceLanguageConfig as c}from"microsoft-cognitiveservices-speech-sdk";import"js-cookie";import{jwtDecode as h}from"jwt-decode";import{v4 as l}from"uuid";import{createMachine as d,assign as u,fromPromise as p,createActor as m}from"xstate";import*as g from"three";import{OrbitControls as y}from"three/addons/controls/OrbitControls.js";import{GLTFLoader as v}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as f}from"three/addons/loaders/DRACOLoader.js";import{FBXLoader as b}from"three/addons/loaders/FBXLoader.js";import{RoomEnvironment as _}from"three/addons/environments/RoomEnvironment.js";import x from"three/addons/libs/stats.module.js";import{html as k,nothing as w,css as S,LitElement as A}from"lit";import C from"toastify-js";import{styleMap as R}from"lit/directives/style-map.js";const T=t=>new Promise((e=>setTimeout(e,t))),L=t=>t?t.replace(/<prosody[^>]*>([\s\S]*?)<\/prosody>/gi,"$1").replace(/#\*[\s\S]*?\*#/g,""):t,z=t=>(t instanceof Date?t:new Date(t)).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});function M(){return"undefined"!=typeof window&&window.VITE_APP_SOCKET_URL?window.VITE_APP_SOCKET_URL:"https://sentifyd-serve.agreeablestone-0bc8c055.swedencentral.azurecontainerapps.io"}const I=M(),E={auth:{tokenRefreshInterval:6e5,speechTokenInterval:42e4,maxLoginRetries:3,loginRetryDelay:5e3,closeToExpirationLimit:6e4,speechTokenRetries:5,serverBaseURL:M()},avatar:{type:"gltf"},constants:{HEADROLL_BLENDSHAPE_INDEX:52,LEFTEYE_BLENDSHAPE_INDEX:53,RIGHTEYE_BLENDSHAPE_INDEX:54,FRAME_RATE:60},dom:{avatarDivId:"#avatar-container",toastifyDivId:"#toastify-container",canvasWidth:400,canvasHeight:500,headerAndFooterHeight:166,controlsHeight:90,smallDisplayWidth:768,smallScreenSafetyPadding:24},renderer:{alpha:!0,antialias:!0},speech:{authorizationEndPoint:"/api/v1/chatbot/get-speech-token",maxDurationTimeout:6e5,vad:{segmentationSilenceMs:1700,initialSilenceMs:12e3,semantic:!0},bargeIn:{enabled:!0,debug:!1}},captions:{wordsPerMinute:140,maxCharactersPerCaption:40,minCharactersPerCaption:15,captionChangeDelay:200,captionTimeout:1500},alerts:{maxAlerts:3,dismissableAlertDuration:4500},chatbot:{streaming:!1,thinkingTimeout:15e3,speakingTimeout:24e4},test:{stateTestMode:!1,enableDiagnostics:!1},connection:{reconnectInitialDelay:2e3,reconnectMaxDelay:3e4,reconnectFactor:1.6}},P=async(t,e)=>{for(const i of t){const{name:t}=i;switch(t){case"RequestUserData":await D(e);break;case"EndConversation":await H(e);break;case"DisableCaptions":await O(e);break;case"EnableCaptions":await B(e);break;case"SwitchToChatMode":await F(e);break;case"SwitchToAvatarMode":await N(e);break;case"SetAvatarView":await U(e,i.view);break;case"SetAvatarMood":await V(e,i.mood);break;case"PlayOrStopAvatarGesture":await $(e,i.gesture,i.dur||3,i.mirror||!1,i.ms||1e3);break;case"PlayOrStopAvatarAnimation":await j(e,i.animation,i.dur||3);break;case"ControlAvatarLookAt":await q(e,i.target,i.t||1e3,i.x||0,i.y||0)}}},D=async t=>{t.emit("event_command_UI_RequestUserData")},H=async t=>{t.emit("event_command_UI_EndConversation")},O=async t=>{t.emit("event_command_UI_DisableCaptions")},B=async t=>{t.emit("event_command_UI_EnableCaptions")},F=async t=>{t.emit("event_command_UI_SwitchToChatMode")},N=async t=>{t.emit("event_command_UI_SwitchToAvatarMode")},U=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarView",{view:e})},V=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarMood",{mood:e})},$=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_PlayOrStopGesture",{gesture:e,duration:i,mirror:a,ms:n})},j=async(t,e,i)=>{t.emit("event_command_Avatar_PlayOrStopAnimation",{animation:e,dur:i})},q=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_ControlAvatarLookAt",{target:e,t:i,x:a,y:n})};class W{constructor(t,e=null){this.validateDependencies({auth:t}),this.socketUrl=I,this.auth=t,this.socket=null,this.isAuthenticating=!1,this.onConnectionStatusChange=e}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize WebSocketManager due to missing dependencies: ${e.join(", ")}`)}async connect(){this.socket?.connected&&this.disconnect();const e=this.auth.getAccessToken();return new Promise(((i,a)=>{this.socket=t(this.socketUrl,{auth:{token:`Bearer ${e}`},path:"/socket.io",reconnection:!0,reconnectionAttempts:5,reconnectionDelay:500,reconnectionDelayMax:1e4}),this.registerWebsocketEventHandlers(i,a)}))}isSocketConnected(){return this.socket?.connected}isInitialised(){return null!==this.socket}disconnect(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null)}registerWebsocketEventHandlers(t,e){this.socket.removeAllListeners(),this.socket.io.on("error",(t=>{})),this.socket.io.on("reconnect",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("connected")})),this.socket.io.on("reconnect_attempt",(t=>{})),this.socket.io.on("reconnect_error",(t=>{})),this.socket.io.on("reconnect_failed",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("failed"),this.socket=null,e(new Error("Websocket connection failed after maximum retries."))})),this.socket.on("connect",(()=>{this.socket.io.engine,this.onConnectionStatusChange&&this.onConnectionStatusChange("connected"),t()})),this.socket.on("connect_error",(t=>{t.message.includes("Token expired")||t.message.includes("Invalid token")?this.reAuthenticate():(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),e?.(t))})),this.socket.on("disconnect",(t=>{this.socket&&this.socket.active||this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")})),this.socket.onAny(((t,...e)=>{}))}reAuthenticate(){this.isAuthenticating||(this.isAuthenticating=!0,this.auth.authenticate().then((()=>{this.connect(),this.isAuthenticating=!1})).catch((t=>{this.isAuthenticating=!1,this.onConnectionStatusChange("failed")})))}on(t,e){this.socket&&this.socket.on(t,e)}emit(t,e,i){this.isSocketConnected()?i?this.socket.emit(t,e,i):this.socket.emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}async emitWithResponse(t,e){return new Promise(((i,a)=>{this.isSocketConnected()?this.socket.emit(t,e,(t=>{i(t)})):(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),a(new Error("Socket not connected")))}))}timeoutEmit(t,e,i,a){this.isSocketConnected()?a?this.socket.timeout(i).emit(t,e,a):this.socket.timeout(i).emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}destroy(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null),this.isAuthenticating=!1,this.onConnectionStatusChange=null}}class Q{constructor(t){if(!t||"string"!=typeof t)throw new Error("ConnectionModule requires a valid name");this.name=t,this.connectionState="disconnected",this.subscribers=[]}isConnecting(){return"connecting"===this.connectionState}isDisconnected(){return"disconnected"===this.connectionState}isReconnecting(){return"reconnecting"===this.connectionState}isConnected(){return"connected"===this.connectionState}isFailed(){return"failed"===this.connectionState}setConnected(){this.updateConnectionState("connected")}setDisconnected(){this.updateConnectionState("disconnected")}setConnecting(){this.updateConnectionState("connecting")}setReconnecting(){this.updateConnectionState("reconnecting")}setFailed(){this.updateConnectionState("failed")}updateConnectionState(t){return!!["connected","connecting","reconnecting","disconnected","failed"].includes(t)&&this.connectionState!==t&&(this.connectionState,this.connectionState=t,this.notifySubscribers(),!0)}reconnect(){}subscribe(t){return"function"==typeof t&&!this.subscribers.includes(t)&&(this.subscribers.push(t),!0)}unsubscribe(t){if("function"!=typeof t)return!1;const e=this.subscribers.length;return this.subscribers=this.subscribers.filter((e=>e!==t)),this.subscribers.length<e}notifySubscribers(){0!==this.subscribers.length&&[...this.subscribers].forEach(((t,e)=>{try{t(this.connectionState,this.name)}catch(i){}}))}destroy(){try{this.subscribers=[],this.connectionState="disconnected"}catch(t){}}getStateInfo(){return{name:this.name,state:this.connectionState,subscriberCount:this.subscribers.length}}}class G{constructor(t,e,i){this.id=t,this.state="CREATED",this.abortController=new AbortController,this.audio=(t=>{let e,i=!1;return{readable:new ReadableStream({start(a){e=a,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}i=!0}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this.lipsync=(t=>{let e,i=!1;return{readable:new ReadableStream({start(i){e=i,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this._watchdog=setTimeout((()=>{this._watchdog=null,i?.(this)}),e)}activate(){this.state="ACTIVE"}finish(){if("FINISHED"!==this.state){this.state="FINISHED",clearTimeout(this._watchdog);try{this.audio.close()}catch{}try{this.lipsync.close()}catch{}this.abortController.abort("turn finished")}}abort(){"FINISHED"!==this.state&&(this.state="STOPPING",this.abortController.abort("turn interrupted"),clearTimeout(this._watchdog))}get isActive(){return"ACTIVE"===this.state}get done(){return"FINISHED"===this.state}}const Y=12e4;class X extends Q{static _instance=null;constructor(t,e,i,a){if(X._instance)return X._instance;super("chatSocket"),this.validateDependencies({bus:t,auth:e,sessionData:i,avatarOrchestrator:a}),this.socketManager=new W(e,(t=>this.updateConnectionState(t))),this.isChatbotShown=!0,this.chatbotMode="AVATAR",this.bus=t,this.sessionData=i,this.auth=e,this.avatarOrchestrator=a,this.pendingDelayedActions=null,this.turn=null,this.INTERRUPT_WATCHDOG=15e3,X._instance=this}static getInstance(t,e,i,a){return X._instance||(X._instance=new X(t,e,i,a)),X._instance}_isDataForCurrentTurn(){return!!this.turn&&!this.turn.done&&this.turn.id===this.sessionData.conversation.currentTurnId}static resetInstance(){X._instance&&(X._instance._cleanup(),X._instance=null)}_cleanup(){this.cleanupActiveStreams(),this.socketManager?.disconnect(),this.pendingDelayedActions=null,this.turn=null,this.audioStream=null,this.lipsyncStream=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize ChatSocket due to missing dependencies: ${e.join(", ")}`)}async init(){if(!this.sessionData||!this.sessionData.avatarName||!this.sessionData.language)throw new Error("Missing required session data for chat connection.");this.sessionData.trainingId;try{this.setConnecting(),await this.socketManager.connect()}catch(t){this.setDisconnected()}this.registerTTSEventHandlers()}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting();try{if(await this.socketManager.connect(),!this.socketManager.isSocketConnected())throw new Error("Socket still not connected after connect()");this.registerTTSEventHandlers(),this.setConnected()}catch(t){this.setFailed()}}}registerTTSEventHandlers(){this.socketManager.on("conversation_ai_reply",(t=>this.handleConversationResponse(t))),this.socketManager.on("tts_stream_start",(t=>{t?.turnId,this.turn&&this.turn.id===this.sessionData.conversation.currentTurnId||this.prepareStreamsForTurn(this.sessionData.conversation.currentTurnId),this.turn.activate(),this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("STREAM_START",{audioStream:this.audioStream,lipsyncStream:this.lipsyncStream,turnId:this.turn.id})})),this.socketManager.on("tts_viseme",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed&&this.turn&&this.turn.isActive)try{this.lipsyncStream.push({type:"viseme",...t})}catch(e){if(e.message?.includes("closed readable stream"))return}})),this.socketManager.on("tts_word",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"word",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_blend",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"blend",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_error",(t=>{this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("TTS_ERROR",{error:t})})),this.socketManager.on("tts_chunk",(t=>{if(this._isDataForCurrentTurn()&&this.audioStream&&!this.audioStream.isClosed){if(!this.turn||!this.turn.isActive||!this.audioStream)return;try{this.audioStream.push(t)}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_stream_end",(t=>{const e=t?.turnId;t?.reason,this.turn&&e===this.turn.id&&(this.turn.finish(),this.avatarOrchestrator.sendEvent("STREAM_END"),this.turn=null)}))}async handleConversationResponse(t){this.sessionData?.conversation?.conversationId&&("success"===t?.status?(t?.error,await this.processAIResponse(t)):"error"===t?.status?this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:t.error,chatbotMode:this.chatbotMode}):this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"No response from server. Please try again."},chatbotMode:this.chatbotMode}))}async sendInitConversationEvent(){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((t,e)=>{this.socketManager.timeoutEmit("init_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,streaming:!1},Y,((i,a)=>{i||"success"!==a?.status?e(new Error(i||a?.error?.message||"Conversation init failed")):t({initialized:!0})}))}))}async sendStartConversationEvent(){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((t,e)=>{this.socketManager.timeoutEmit("start_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,turnId:this.sessionData.conversation.currentTurnId,streaming:!1,isTermsAccepted:!0===this.sessionData.isTermsAccepted},Y,(async(i,a)=>{if(i||"success"!==a?.status)e(new Error(i||a?.error?.message||"Conversation start failed"));else try{await this.processAIResponse(a),t(a)}catch(n){e(n)}}))}))}sendEndConversationEvent(t,e){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("end_conversation",{conversationId:t,satisfactionScore:e,chatbotMode:this.chatbotMode},(e=>{"success"===e?.status?this.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t}):e?.status}))}prepareStreamsForTurn(t){this.turn&&!this.turn.done&&this.turn.abort(),this.turn=new G(t,this.INTERRUPT_WATCHDOG,(t=>{this.socketManager.emit("interrupt_tts",{turnId:t.id})})),this.audioStream=this.turn.audio,this.lipsyncStream=this.turn.lipsync}async processAIResponse(t){try{const e=t?.data?.actions||[],i=e.filter((t=>!1!==t.immediate)),a=e.filter((t=>!1===t.immediate));if(i.length>0&&await P(i,this.bus),a.length>0&&(this.pendingDelayedActions=a),"message"===t.data?.dataType?await this.receiveMessage(t.data,t.timestamp):"avatar_structured_response"===t.data?.dataType?await this.receiveAvatarStructuredResponse(t.data,t.timestamp):t?.data?.messageContent&&await this.receiveMessage(t.data,t.timestamp),"CHAT"===this.chatbotMode&&this.pendingDelayedActions&&this.pendingDelayedActions.length>0)try{await P(this.pendingDelayedActions,this.bus)}finally{this.pendingDelayedActions=null}}catch(e){this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"Error getting a response. Please try again."},chatbotMode:this.chatbotMode})}}async receiveAvatarStructuredResponse(t,e){if(!t?.structuredResponse)throw new Error("Avatar response is invalid");const i=z(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,structuredResponse:t.structuredResponse,chatbotMode:this.chatbotMode})}async receiveMessage(t,e){if(!t?.messageContent)throw new Error("Message is invalid");const i=z(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,chatbotMode:this.chatbotMode})}async sendMessage(t,e="CHAT"){if(this.pendingDelayedActions=null,!this.sessionData.trainingId||!t?.messageText)return{success:!1,error:"Missing required field(s)"};if(!this.sessionData.conversation.conversationId)return{success:!1,error:"No conversation found. Start a conversation first."};try{const i=this.sessionData.conversation.incrementTurnId();this.prepareStreamsForTurn(i),this.socketManager.emit("user_chat_message",{trainingId:this.sessionData.trainingId,avatarId:this.sessionData.avatarId,userName:this.sessionData.username,conversationId:this.sessionData.conversation.conversationId,turnId:i,message:t.messageText,messageDuration:t?.messageDuration||0,chatbotMode:e,detectedLanguage:t?.detectedLanguage||this.sessionData.language,voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,streaming:E.chatbot.streaming||!1});const a=z(new Date);return this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:t.messageText,time:a,chatbotMode:e}),this.sessionData.conversation.lastDetectedLanguage=t?.detectedLanguage,{success:!0}}catch(i){return{success:!1,error:i.message||"An error occurred while sending the message"}}}sendUserData(){const t=this.sessionData.conversation.incrementTurnId();if(this.prepareStreamsForTurn(t),this.avatarOrchestrator){const t=this.avatarOrchestrator.getSnapshot(),e=t?.matches("lifecycle.conversation.inProgress.thinking");e||this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:"[User data update]",time:z(new Date),chatbotMode:this.chatbotMode})}if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("update_user_data",{conversationId:this.sessionData.conversation.conversationId,turnId:t,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",chatbotMode:this.chatbotMode,lipsyncType:this.sessionData.lipsyncType,userData:{username:this.sessionData.username,phoneNumber:this.sessionData.phoneNumber,email:this.sessionData.email,isTermsAccepted:this.sessionData.isTermsAccepted}},(async t=>{"success"===t?.status?this.processAIResponse(t):t?.status}))}cleanupActiveStreams(){this.turn&&this.turn.abort()}async interruptCurrentTurn(){if(!this.turn)return{status:"warning",message:"No active turn"};try{return this.turn.abort(),await this.socketManager.emitWithResponse("interrupt_tts",{turnId:this.turn.id})}catch(t){return{status:"error",message:"Interruption failed"}}}destroy(){this.socketManager?.destroy()}}class Z{constructor({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n,autoDetectLanguage:s}={}){this.validateDependencies({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n}),this.bus=a,this.avatarOrchestrator=n,this.speechConfig=e,this.recognizer=t,this.audioConfig=i,this.messageText="",this.messageDuration=0,this.detectedLanguage="",this.isMessageSent=!1,this.isListening=!1,this.isMicDetected=!0,this.autoDetectLanguage=s,this.languageDurations={},this._isStopping=!1,this.maxDurationTimeoutId=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize SpeechRecognition due to missing dependencies: ${e.join(", ")}`)}static async build(t,e,i,a){if(!t)throw new Error("speechConfig is required");const{recognizer:n,audioConfig:s}=await this.init(t,e),o=new Z({recognizer:n,speechConfig:t,audioConfig:s,bus:i,avatarOrchestrator:a,autoDetectLanguage:!!e});return o._registerRecognizerEvents(),o}static async init(t,a){try{const n=e.fromDefaultMicrophoneInput();let s=null;return s=a?i.FromConfig(t,a,n):new i(t,n),{recognizer:s,audioConfig:n}}catch(n){throw new Error("Error in SpeechRecognition initialization: "+n)}}static async checkMicrophoneAccess(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Media devices not supported");if(0===(await navigator.mediaDevices.enumerateDevices()).filter((t=>"audioinput"===t.kind)).length)throw new Error("No microphone devices found");return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach((t=>t.stop())),!0}catch(t){throw new Error(`Microphone access issue: ${t.message}`)}}start(){try{this._isStopping=!1,clearTimeout(this.maxDurationTimeoutId),this.messageText="",this.messageDuration=0,this.isMessageSent=!1,this.autoDetectLanguage&&(this.languageDurations={}),this.recognizeNewMessage(),this._setMaxDurationTimeout()}catch(t){this.stop()}}stop(){if(!this._isStopping){this._isStopping=!0;try{this.recognizer&&this.recognizer.stopContinuousRecognitionAsync()}catch(t){}finally{this.isListening=!1,this._isStopping=!1}clearTimeout(this.maxDurationTimeoutId)}}sendMessage(){if(!this.isMessageSent&&this.messageText&&this.messageText.trim())try{this.autoDetectLanguage?this.detectedLanguage=this._determineMainLanguage():this.detectedLanguage=this.speechConfig.speechRecognitionLanguage,this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:this.messageDuration,detectedLanguage:this.detectedLanguage}),this.isMessageSent=!0}catch(t){}}simulateRecognition(){this.avatarOrchestrator.transitionToListening(),this.messageText="Hello, how are you doing today?",this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:3e3,detectedLanguage:"en-US"})}recognizeNewMessage(){try{this._startRecognizer()}catch(t){this._emitAlert("Failed to start listening. Make sure your microphone is working."),this.stop()}}_startRecognizer(){this.recognizer.startContinuousRecognitionAsync((()=>{this.avatarOrchestrator.is("listening"),this.isListening=!0}),(async t=>{await this._handleRecognitionStartupError(t),this.isMicDetected=!1,this.stop()}))}async _handleRecognitionStartupError(t){let e="Failed to start listening. Please check your microphone settings.";try{await Z.checkMicrophoneAccess(),e="Speech recognition setup failed. Please refresh the page and try again."}catch(i){e=this._isBrowserPermissionError(i)?"Microphone access denied. Please allow microphone access in your browser settings and refresh the page.":this._isBrowserDeviceError(i)?"No microphone detected. Please connect a microphone and refresh the page.":`${i.message}. Please check your microphone.`}this._emitAlert(e)}_isBrowserPermissionError(t){if(t&&"object"==typeof t)return"NotAllowedError"===t.name||"PermissionDeniedError"===t.name||"SecurityError"===t.name;const e=t.toString().toLowerCase();return e.includes("permission")||e.includes("notallowed")||e.includes("denied")}_isBrowserDeviceError(t){if(t&&"object"==typeof t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name;const e=t.toString().toLowerCase();return e.includes("notfound")||e.includes("device")||e.includes("microphone not found")}close(){this.stop(),this.recognizer&&(this.recognizer.close(),this.recognizer.dispose(!0),this.recognizer=void 0)}_registerRecognizerEvents(){this.recognizer.recognized=(t,e)=>{if(!this._isStopping&&this.isListening&&!this.isMessageSent&&e.result.reason===a.RecognizedSpeech&&""!==e.result.text){if(this.messageText=(this.messageText?this.messageText+" ":"")+e.result.text,this.messageDuration+=e.result.duration,this.autoDetectLanguage){const t=e.result.language,i=e.result.duration;this.languageDurations[t]?this.languageDurations[t]+=i:this.languageDurations[t]=i}this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText}),this._completeRecognitionTurn()}},this.recognizer.recognizing=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||""!==e.result.text&&this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText+" "+e.result.text})},this.recognizer.speechStartDetected=(t,e)=>{},this.recognizer.speechEndDetected=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||this.messageText?.trim()&&this._completeRecognitionTurn()},this.recognizer.canceled=(t,e)=>{e.reason===n.Error&&this._handleAzureSpeechError(e),this.stop()}}_handleAzureSpeechError(t){const e=t.errorCode,i=t.errorDetails||"No additional details available";let a="",n=!1;switch(e){case s.NoError:a="An unexpected error occurred. Please try again.";break;case s.AuthenticationFailure:a="Unable to connect to voice services. Please try again later.",n=!0;break;case s.BadRequestParameters:a="Voice service is temporarily unavailable. Please try again in a moment.";break;case s.TooManyRequests:a="Too many simultaneous requests. Please wait a moment and try again.";break;case s.ConnectionFailure:a="Connection issue detected. Please check your internet connection and try again.";break;case s.ServiceTimeout:a="Response timeout. Please try again.";break;case s.ServiceError:a="Voice service is temporarily unavailable. Please try again in a moment.";break;case s.RuntimeError:a="An unexpected error occurred. Please refresh the page and try again.";break;case s.Forbidden:a="Voice service is currently busy. Please try again in a few minutes.";break;default:a="An unknown error occurred. Please try again."}n&&this.bus.emit("event_error_VoiceBot_ExpiredOrInvalidToken",i),this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:a})}_emitAlert(t,e={}){if("string"!=typeof t||!this.bus)return;if(t.toLowerCase().includes("microphone")&&this._isChatModeActive())return;const i={errorMessage:t,...e};this.bus.emit("event_command_Alerts_ShowDismissableAlert",i)}_isChatModeActive(){try{const t=this.avatarOrchestrator?.getSnapshot?.(),e=t?.context?.chatSocket?.chatbotMode;return"CHAT"===e}catch(t){return!1}}_setMaxDurationTimeout(){this.maxDurationTimeoutId=setTimeout((()=>{this._completeRecognitionTurn()}),E.speech.maxDurationTimeout)}_completeRecognitionTurn(){this._isStopping||this.stop(),this.sendMessage()}_determineMainLanguage(){let t=null,e=0;for(const[i,a]of Object.entries(this.languageDurations))a>e&&(e=a,t=i);return t}destroy(){try{this.close()}catch(t){}}}class J extends Q{constructor(t,e){super("speech-token"),this.auth=t,this.refreshTokenCallback=e,this.tokenRefreshLoop=null}async requestAuthorizationToken(t=E.auth.speechTokenRetries){for(let i=1;i<=t;i++)try{const t=await this.fetchSpeechToken();return this.setConnected(),t}catch(e){if(i===t)throw this.setFailed(),new Error(`Failed to fetch speech token after ${t} attempts`)}}async fetchSpeechToken(){try{const t=await this.auth.callSentifydApi(E.speech.authorizationEndPoint,"POST"),{token:e}=t.data;if(!e)throw new Error("Invalid token structure received from API.");return t.data}catch(t){throw new Error("Failed to fetch data from API.")}}async startTokenRefreshLoop(){await this.stopTokenRefreshLoop(),this.tokenRefreshLoop=setInterval((async()=>{try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),this.setConnected()}catch(t){this.setDisconnected()}}),E.auth.speechTokenInterval)}async stopTokenRefreshLoop(){this.tokenRefreshLoop&&(clearInterval(this.tokenRefreshLoop),this.tokenRefreshLoop=null)}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting(),await this.stopTokenRefreshLoop();try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),await this.startTokenRefreshLoop()}catch(t){this.setFailed()}}}}class K{constructor({speechService:t,speechConfig:e,autoDetectSourceLanguageConfig:i,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}={}){this.validateDependencies({speechService:t,speechConfig:e,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}),this.sessionData=r,this.speechService=t,this.speechConfig=e,this.speechRecognizer=a,this.bus=n,this.avatarOrchestrator=o,this.autoDetectSourceLanguageConfig=i,this._currentTurnId=0,this._expectedTurnId=0,this._lastInterruptionTime=0,this.INTERRUPTION_DEBOUNCE=100,this._isHandlingAudioEnd=!1,this.registerEventListeners(),this.speechService.startTokenRefreshLoop()}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize VoiceBot due to missing dependencies: ${e.join(", ")}`)}registerEventListeners(){this._busHandlers=this._busHandlers||[];const t=t=>{this.getNewSpeechToken()};this.bus.on("event_error_VoiceBot_ExpiredOrInvalidToken",t),this._busHandlers.push(["event_error_VoiceBot_ExpiredOrInvalidToken",t])}static async build(t,e,i,a){const{speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r}=await this.init(a,t,i,e);return new K({speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r,bus:t,auth:i,avatarOrchestrator:e,sessionData:a})}static async init(t,e,i,a){try{const n=t?.language||"en-US",s=(t?.voice,t?.autodetectLanguages||[]);let h=null,l=null;const d=new J(i,(t=>{h&&(h.authorizationToken=t)})),{token:u,region:p}=await d.requestAuthorizationToken();if(!u||!p)throw new Error("Failed to get authorization token");h=o.fromAuthorizationToken(u,p);const m=E?.speech?.vad??{},g=t?.speech?.vad??t?.vad??{},y=g.segmentationSilenceMs??m.segmentationSilenceMs??800,v=g.initialSilenceMs??m.initialSilenceMs??8e3;h.setProperty(r.Speech_SegmentationSilenceTimeoutMs,String(y)),h.setProperty(r.SpeechServiceConnection_InitialSilenceTimeoutMs,String(v));const f=g.strategy??m.strategy,b=g.semantic??m.semantic,_="string"==typeof f?f:!0===b?"Semantic":null;_&&h.setProperty(r.Speech_SegmentationStrategy,_),"multilingual"===n?s.length>0?l=c.fromLanguages(s):h.speechRecognitionLanguage="en-US":h.speechRecognitionLanguage=n;const x=await Z.build(h,l,e,a);return{speechService:d,speechConfig:h,autoDetectSourceLanguageConfig:l,speechRecognizer:x}}catch(n){throw new Error("Error in VoiceBot initialization",{cause:n})}}async getNewSpeechToken(){try{const{token:t}=await this.speechService.requestAuthorizationToken();this.speechConfig.authorizationToken=t}catch(t){}}isConversationInProgress(){return!!this.sessionData?.conversation?.conversationId}async startListening(){if(this.speechRecognizer.isListening)return{success:!0,alreadyListening:!0};try{return this.speechRecognizer.isMicDetected||(this.speechRecognizer.close(),this.speechRecognizer=await Z.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator),this.speechRecognizer.isMicDetected=!0),this.speechRecognizer.start(),{success:!0,started:!0}}catch(t){return{success:!1,error:t.message||"Failed to start speech recognition"}}}stopListening(){try{return this.speechRecognizer.stop(),{success:!0}}catch(t){return{success:!1,error:t.message||"Failed to stop speech recognition"}}}async updateSpeechLanguage(t){this.speechConfig.speechRecognitionLanguage=t,this.speechRecognizer.close(),this.speechRecognizer=await Z.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator)}destroy(){this._busHandlers?.forEach((([t,e])=>this.bus.off(t,e))),this._busHandlers=[],this.speechRecognizer?.destroy(),this.speechService?.stopTokenRefreshLoop()}}const tt={enabled:!0,micThreshold:.0033,avatarQuietFloor:.009,minSignalRatio:1.2,minSignalRatioWhileSpeaking:.38,minSignalDelta:.0028,absoluteMicOverride:.012,minDurationMs:200,cooldownMs:1500,envelopeAttack:.6,envelopeRelease:.8,leakAdaptRate:.06,leakFloor:0,leakCeil:.25,leakMargin:.012,leakDecayHoldMs:300,leakDecayRate:.2,leakMinAvatar:.01,noiseStdK:3.4,minSnr:3.2,noiseMinSamples:90,warmupMs:400,speakingGuardMs:200,minConsecutive:3,hangoverMs:100,minAbsQuiet:.0032,bandpassHz:[350,3400],minDurationWhileSpeakingMs:260,debug:!1};class et{constructor({talkingAvatar:t,avatarOrchestrator:e,config:i}={}){this.talkingAvatar=t,this.avatarOrchestrator=e,this.config={...tt,...i||{}},this._audioCtx=null,this._micStream=null,this._micSource=null,this._micBpf=null,this._micAnalyser=null,this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._armed=!1,this._candidateSince=null,this._lastTriggerTime=0,this._rafId=null,this._projectionUnsub=null,this._isDestroyed=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._lastFrameTs=0,this._lastAudioResumeAttempt=0,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats()}async init(){if(this.config.enabled)try{await this._ensureMicAnalyser(),this._subscribeToState()}catch(t){this._teardown()}}destroy(){this._isDestroyed=!0,this._unsubscribe(),this._disarm(),this._teardown()}async _ensureMicAnalyser(){if(this._micAnalyser)return;if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("Media devices API not available");this._audioCtx=this._audioCtx||new(window.AudioContext||window.webkitAudioContext);const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1}});this._micStream=t,this._micSource=this._audioCtx.createMediaStreamSource(t),this._micBpf=this._audioCtx.createBiquadFilter(),this._micBpf.type="bandpass";const[e,i]=Array.isArray(this.config.bandpassHz)&&2===this.config.bandpassHz.length?this.config.bandpassHz:[300,3e3],a=Math.max(10,Math.min(e,i||e)),n=Math.max(1.5*a,i||10*a),s=Math.sqrt(a*n);this._micBpf.frequency.value=Number.isFinite(s)?s:1e3;const o=Math.log2(n/a),r=Math.sinh(Math.log(2)/2*Math.max(o,.01)),c=r>0?1/(2*r):1;this._micBpf.Q.value=Math.max(.5,Math.min(4,c||1)),this._micAnalyser=this._audioCtx.createAnalyser(),this._micAnalyser.fftSize=512,this._micAnalyser.smoothingTimeConstant=.4,this._micSource.connect(this._micBpf).connect(this._micAnalyser),this._micBuffer=new Float32Array(this._micAnalyser.fftSize),this._debugEvent("mic-ready",{sampleRate:this._audioCtx.sampleRate,fftSize:this._micAnalyser.fftSize})}_subscribeToState(){this.avatarOrchestrator?.subscribeProjected&&(this._projectionUnsub=this.avatarOrchestrator.subscribeProjected((t=>{if(this._isDestroyed)return;const e=t?.lifecycle?.conversationSubstate;"speaking"===e?this._arm():this._disarm()})))}_unsubscribe(){if("function"==typeof this._projectionUnsub){try{this._projectionUnsub()}catch(t){}this._projectionUnsub=null}}_arm(){if(!this._micAnalyser)return;if(!this._avatarAnalyser&&!this._avatarAnalyserMissing){if(this._avatarAnalyser=this.talkingAvatar?.getSpeechAnalyzerNode?.()??null,!this._avatarAnalyser)return this._debugEvent("avatar-analyser-missing",{}),this._avatarAnalyserMissing=!0,void(this._armed=!1);this._avatarAnalyser.smoothingTimeConstant=Math.min(this._avatarAnalyser.smoothingTimeConstant??.4,.6),this._avatarBuffer=new Float32Array(this._avatarAnalyser.fftSize),this._debugEvent("avatar-analyser-ready",{fftSize:this._avatarAnalyser.fftSize})}if(this._armed)return;this._armed=!0,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1));const t="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();this._armedAt=t,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId||(this._rafId=requestAnimationFrame(this._monitorLoop)),this._debugEvent("armed",{micThreshold:this.config.micThreshold,avatarQuietFloor:this.config.avatarQuietFloor,minSignalRatio:this.config.minSignalRatio,minSignalRatioWhileSpeaking:this.config.minSignalRatioWhileSpeaking,minSignalDelta:this.config.minSignalDelta,absoluteMicOverride:this.config.absoluteMicOverride,minDurationMs:this.config.minDurationMs,cooldownMs:this.config.cooldownMs,warmupMs:this.config.warmupMs,speakingGuardMs:this.config.speakingGuardMs,minConsecutive:this.config.minConsecutive,hangoverMs:this.config.hangoverMs,bandpassHz:this.config.bandpassHz})}_disarm(){(this._armed||this._rafId)&&(this._armed=!1,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1)),this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this._debugEvent("disarmed",{}))}_monitorLoop=()=>{if(this._isDestroyed)return;if(!this._armed)return void(this._rafId=null);const t=performance.now(),e=this._lastFrameTs?t-this._lastFrameTs:16.7;this._lastFrameTs=t,"suspended"===this._audioCtx?.state&&(0===this._lastAudioResumeAttempt||t-this._lastAudioResumeAttempt>=1e3)&&(this._lastAudioResumeAttempt=t,this._audioCtx.resume().catch((()=>{})));const i=this._clamp01(this._readRms(this._micAnalyser,this._micBuffer)),a=this._avatarAnalyser?this._readRms(this._avatarAnalyser,this._avatarBuffer):0,n=this._clamp01(a),s=this._updateEnvelope("_micEnvelope",i,e),o=this._updateEnvelope("_avatarEnvelope",n,e),r=this._updateLeakEstimate({micSignal:s,avatarSignal:o,candidateActive:!!this._candidateSince}),c=o>(this.config.leakMinAvatar??.01)?.85*(r+(this.config.leakMargin??.012)):0,h=Math.max(0,s-o*c),l=o>5e-4?h/Math.max(o,5e-4):1/0,d=h-o,u=o<=this.config.avatarQuietFloor,p=h>=this.config.micThreshold,m=s>=this.config.absoluteMicOverride,g=t-(this._armedAt||t),y=g<(this.config.warmupMs??400),v=!u&&g<(this.config.speakingGuardMs??250);!m&&!this._candidateSince&&u&&!y&&0===this._consecHits&&h<1.2*this.config.micThreshold&&this._updateNoiseStats(h);const f=this._noiseCount>=(this.config.noiseMinSamples??90),b=this._noiseMean,_=this._getNoiseStd(),x=f?(h+1e-7)/(b+1e-7):0,k=this.config.noiseStdK??3.2,w=f&&h>=b+k*_,S=f&&x>=(this.config.minSnr??3),A=!!u||m||l>=(this.config.minSignalRatioWhileSpeaking??this.config.minSignalRatio)||d>=this.config.minSignalDelta,C=this.config.minAbsQuiet??0,R=!u||h>=C,T=u?R&&(m||(f?w||S:p)):m||p,L=!y&&!v,z=L&&T&&A,M=this.config.minConsecutive??4;if(z)this._consecHits+=1,this._lastQualifyTs=t;else{const e=this.config.hangoverMs??120,i=t-this._lastQualifyTs<=e;this._consecHits=i?this._consecHits:0}this._debugTick({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,leakApply:c,noiseMean:b,noiseStd:_,noiseSamples:this._noiseCount,snr:x,exceedsNoise:w,snrDominates:S,ratio:l,delta:d,meetsMicThreshold:p,avatarQuiet:u,absoluteOverride:m,absQuietOK:R,energyOK:T,energyQualified:T,competitionOK:A,noiseReady:f,warmup:y,speakingGuard:v,frameAllowed:L,frameQualifies:z,qualifies:z,consecutiveHits:this._consecHits,requiredHits:M,candidateDuration:this._candidateSince?t-this._candidateSince:0,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._consecHits>=M?this._candidateSince||(this._candidateSince=t,this._debugEvent("candidate-start",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d})):this._candidateSince&&!z&&t-this._lastQualifyTs>(this.config.hangoverMs??120)&&(this._debugEvent("candidate-reset",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d}),this._candidateSince=null,this._consecHits=0);const I=u?this.config.minDurationMs??200:this.config.minDurationWhileSpeakingMs??(this.config.minDurationMs??200)+60,E=this._candidateSince&&t-this._candidateSince>=I,P=t-this._lastTriggerTime>=this.config.cooldownMs;E&&P?this._emitBargeIn({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d,timestamp:t}):E&&!P&&this._debugEvent("cooldown-block",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._rafId=requestAnimationFrame(this._monitorLoop)};_emitBargeIn({micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d}){this._lastTriggerTime=d,this._candidateSince=null,this._consecHits=0,this._lastQualifyTs=0,this._debugEvent("trigger",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d});try{this.avatarOrchestrator?.sendEvent?.("VOICE_BARGE_IN",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d})}catch(u){}}_readRms(t,e){if(!t)return 0;try{t.getFloatTimeDomainData(e)}catch(a){return 0}let i=0;for(let n=0;n<e.length;n++){const t=e[n];i+=t*t}return Math.sqrt(i/e.length)}_teardown(){if(this._micStream&&(this._micStream.getTracks().forEach((t=>{try{t.stop()}catch(e){}})),this._micStream=null),this._micSource){try{this._micSource.disconnect()}catch(t){}this._micSource=null}if(this._micBpf){try{this._micBpf.disconnect()}catch(t){}this._micBpf=null}if(this._micAnalyser){try{this._micAnalyser.disconnect()}catch(t){}this._micAnalyser=null}if(this._audioCtx){try{this._audioCtx.close()}catch(t){}this._audioCtx=null}this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats(),this._lastFrameTs=0,this._lastAudioResumeAttempt=0}_debugTick(t){if(!this.config.debug)return;const e=performance.now?performance.now():Date.now();e-this._lastTickLog<150||(this._lastTickLog=e)}_debugEvent(t,e){this.config.debug}_updateEnvelope(t,e,i=16.7){const a="number"==typeof this[t]?this[t]:e,n=Math.min(Math.max(this.config.envelopeAttack,0),.999),s=Math.min(Math.max(this.config.envelopeRelease,0),.999),o=e>=a?n:s,r=Math.max(i/16.7,.1),c=a+(e-a)*(1-Math.pow(o,r)),h=this._clamp01(c);return this[t]=h,h}_updateLeakEstimate({micSignal:t,avatarSignal:e,candidateActive:i}){const a=this.config.leakMinAvatar??0,n=this.config.leakAdaptRate??.1,s=this.config.leakFloor??0,o=this.config.leakCeil??1,r="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();let c=this._leakEstimate??s;if(i||this._consecHits>0)return c;const h=this._noiseCount>=(this.config.noiseMinSamples??90),l=this._getNoiseStd(),d=this._noiseMean,u=h&&t>=d+(this.config.noiseStdK??3.2)*l;if(e>a&&t<.8*this.config.absoluteMicOverride&&!u){const i=t/Math.max(e,1e-5);c+=(Math.max(s,Math.min(i,o))-c)*n,this._leakEstimate=c,this._debugLeakUpdate({ratio:i,estimate:c}),this._lastAvatarBelowMin=null}else if(e<=a&&c>s){const t=this.config.leakDecayHoldMs??1e3,i=this.config.leakDecayRate??.1*n;null==this._lastAvatarBelowMin&&(this._lastAvatarBelowMin=r),e<=a?r-this._lastAvatarBelowMin>=t&&(c+=(s-c)*i):this._lastAvatarBelowMin=r,this._leakEstimate=Math.max(s,c)}return this._leakEstimate??s}_debugLeakUpdate({ratio:t,estimate:e}){this.config.debug&&this._debugEvent("leak-update",{ratio:t,estimate:e})}_resetNoiseStats(){this._noiseMean=0,this._noiseVar=0,this._noiseCount=0}_updateNoiseStats(t){const e=this._clamp01(t);if(!Number.isFinite(e))return;this._noiseCount>=500&&(this._noiseCount=Math.floor(350),this._noiseMean*=.95,this._noiseVar*=.9),this._noiseCount+=1;const i=e-this._noiseMean;this._noiseMean+=i/this._noiseCount;const a=e-this._noiseMean;this._noiseVar+=i*a}_getNoiseStd(){return this._noiseCount<2?0:Math.sqrt(Math.max(this._noiseVar/(this._noiseCount-1),0))}_clamp01(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:0}}let it=null;const at={setInstance(t){it=t},getItem:async t=>{if(!it)throw new Error("Storage instance not initialized");return it.getItem(t)},setItem:async(t,e)=>{if(!it)throw new Error("Storage instance not initialized");return it.setItem(t,e)},removeItem:async t=>{if(!it)throw new Error("Storage instance not initialized");return it.removeItem(t)}};class nt extends Error{constructor(t,{statusCode:e=null,reason:i=null}={}){super(t),this.name="LoginError",this.statusCode=e,this.reason=i}}async function st(t){try{const e=await fetch(`${t.serverBaseURL}/api/v1/chatbot/login`,{method:"POST",headers:{"Content-Type":"application/json","X-Sentifyd-Origin":t.targetApp},body:JSON.stringify({avatar_api_key:t.getAvatarAPIKey()})});if(!e.ok){const i=function(t){switch(t){case 404:return{message:"Avatar not found.",reason:"avatar-not-found",shouldStopRetrying:!0};case 401:return{message:"Unauthorized avatar login attempt.",reason:"unauthorized",shouldStopRetrying:!1};case 429:return{message:"Too many login attempts. Please retry later.",reason:"rate-limited",shouldStopRetrying:!1};default:return{message:`Login failed with status code ${t}.`,reason:"login-failed",shouldStopRetrying:!1}}}(e.status);throw i.shouldStopRetrying&&(t.retries=E.auth.maxLoginRetries),new nt(i.message,{statusCode:e.status,reason:i.reason})}const i=await e.json();await async function(t,e){try{const i=e?.data?.avatar_params;if(!i||!i.avatarId)throw new Error("Invalid avatar parameters received in login response.");const a=i.avatarId;t.id=a;const n={accessToken:e.data.access_token,refreshToken:e.data.refresh_token,avatarParameters:i};await t.updateAuthData(n),t.setConnected()}catch(i){throw new Error(`Failed to process login response: ${i.message}`)}}(t,i)}catch(e){throw e}}const ot=new class{constructor(t=1){this.max=t,this._fns=[],this._active=0}get remaining(){return this._fns.length}get active(){return this._active}take(t){this._fns.push(t),this._try()}_done(){this._active-=1,this._try()}_try(){if(this._active===this.max||0===this._fns.length)return;const t=this._fns.shift();this._active+=1,t&&t(this._done.bind(this))}}(1);class rt{constructor({serverBaseURL:t,getRefreshToken:e,updateAccessToken:i,onSuccess:a,onError:n}){this.serverBaseURL=t,this.getRefreshToken=e,this.onSuccess=a,this.onError=n,this.tokenRefreshIntervalId=null,this.updateAccessToken=i}startTokenRefreshInterval(){this.tokenRefreshIntervalId&&clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=setInterval((async()=>{try{await this.refreshAccessToken()}catch(t){}}),E.auth.tokenRefreshInterval)}stopTokenRefreshInterval(){this.tokenRefreshIntervalId&&(clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=null)}async refreshAccessToken(){return new Promise(((t,e)=>{ot.take((async i=>{try{const e=this.getRefreshToken();if(!e)throw new Error("No refresh token available");const i=await fetch(`${this.serverBaseURL}/api/v1/chatbot/token_exchange`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}});if(!i.ok){const t=`Failed to refresh JWT token (Status: ${i.status} ${i.statusText})`;throw"function"==typeof this.onError&&this.onError(new Error(t)),new Error(t)}const a=await i.json();if(!a?.data?.access_token)throw new Error("Invalid token data received during refresh.");this.updateAccessToken&&await this.updateAccessToken(a.data.access_token),"function"==typeof this.onSuccess&&this.onSuccess(a.data.access_token),t(!0)}catch(a){"function"==typeof this.onError&&this.onError(a),e(a)}finally{i()}}))}))}}class ct extends Q{#t;#e;#i;constructor(t="",e="",i=""){if(ct._instance)return ct._instance;super("authentication"),ct._instance=this,this.#t=t,this.tokenEndpoint=e,this.#e=null,this.#i=null,this.avatarParameters=null,this.id=i,this.serverBaseURL=E.auth.serverBaseURL||"",this.targetApp="",this.lastFailureDetails=null,this.tokenRefresher=new rt({serverBaseURL:this.serverBaseURL,getRefreshToken:()=>this.#i,updateAccessToken:async t=>await this.updateAuthData({accessToken:t}),onSuccess:()=>{},onError:t=>{this.handleAuthenticationFailure("Error refreshing access token",t)}})}async init(t="web",e="",i="",a=""){this.id=a,this.targetApp=t,this.#t=e,this.tokenEndpoint=i;try{return await this.authenticate(),this.startTokenRefreshInterval(),!0}catch(n){return this.handleAuthenticationFailure(`Error during authentication initialization: ${n.message}`,n),!1}}async authenticate(){for(this.retries=0,this.setConnecting();this.retries<E.auth.maxLoginRetries;)try{if(this.#t?.trim())await st(this);else{if(!this.tokenEndpoint?.trim()){const t="authenticate: No API key or token endpoint provided for authentication.";throw this.handleAuthenticationFailure(t),new Error(t)}await this.requestDataFromServer()}return void this.clearFailureDetails()}catch(t){if(this.setDisconnected(),this.recordFailure({message:`authenticate: Attempt #${this.retries+1} failed`,reason:t instanceof nt?t.reason:t?.message||null,statusCode:t instanceof nt&&"number"==typeof t.statusCode?t.statusCode:null}),this.retries++,this.retries>=E.auth.maxLoginRetries){const e=`authenticate: All ${E.auth.maxLoginRetries} authentication attempts failed.`;if(this.handleAuthenticationFailure(e,t),t instanceof Error)throw t;throw new Error(`${e} Last error: ${t}`)}await T(E.auth.loginRetryDelay)}}startTokenRefreshInterval(){this.tokenRefresher.startTokenRefreshInterval()}stopTokenRefreshInterval(){this.tokenRefresher.stopTokenRefreshInterval()}isTokenCloseToExpiration(){if(!this.#e)return!0;try{const{exp:t}=h(this.#e);if(!t)return!0;if(1e3*t-Date.now()<=E.auth.closeToExpirationLimit)return!0}catch(t){return!0}return!1}async callSentifydApi(t,e="POST",i=null){if(!this.isConnected())throw new Error("Cannot call the API without active authentication");const a=`${this.serverBaseURL}${t}`,n=new Headers({"Content-Type":"application/json"}),s=this.getAccessToken();if(!s)throw new Error("Cannot call the API without an access token");n.append("Authorization",`Bearer ${s}`);const o={method:e,headers:n,body:i?JSON.stringify(i):void 0};try{let t=await fetch(a,o);if(401===t.status)try{await this.authenticate();const e={...o,headers:{...o.headers,Authorization:`Bearer ${this.getAccessToken()}`}};if(t=await fetch(a,e),401===t.status)throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error(`API call failed: ${t.statusText} (Status: ${t.status})`)}catch(r){throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error("API call failed")}if(!t.ok)throw new Error(`API call failed: ${t.statusText} (Status: ${t.status})`);return await t.json()}catch(r){throw r}}async isAuthRequired(){const t=this.#a();return!(t&&t.accessToken&&t.refreshToken&&t.avatarParameters&&!this.isTokenCloseToExpiration())}async logout(){this.id&&await async function(t){if(t)try{await at.removeItem(`authData_${t}`)}catch(e){}}(this.id),this.stopTokenRefreshInterval(),this.#e=null,this.#i=null,this.avatarParameters=null,this.clearFailureDetails(),this.setDisconnected()}async#n(){if(!this.id)return!1;const t=await async function(t){if(!t)return null;try{const e=await at.getItem(`authData_${t}`);return e?JSON.parse(e):null}catch(e){return null}}(this.id);if(!t)return!1;try{return this.#e=t.accessToken,this.#i=t.refreshToken,this.avatarParameters=t.avatarParameters,await this.isAuthRequired()?(this.setDisconnected(),!1):(this.setConnected(),await this.updateAvatarParametersFromServer(),!0)}catch(e){return this.setDisconnected(),!1}}#a(){return this.id&&this.#e&&this.#i&&this.avatarParameters?{accessToken:this.#e,refreshToken:this.#i,avatarParameters:this.avatarParameters}:null}getAccessToken(){return this.#e||null}getRefreshToken(){return this.#i||null}getAvatarAPIKey(){return this.#t}async updateAccessToken(t){await this.updateAuthData({accessToken:t})}getAvatarParameters(){return this.avatarParameters||null}async updateAuthData({accessToken:t,refreshToken:e,avatarParameters:i}){const a=this.#a()||{};t&&(this.#e=t,a.accessToken=t),e&&(this.#i=e,a.refreshToken=e),i&&(this.avatarParameters=i,a.avatarParameters=i);try{await async function(t,e){if(t)try{await at.setItem(`authData_${t}`,JSON.stringify(e))}catch(i){}}(this.id,a),this.clearFailureDetails()}catch(n){}}async requestDataFromServer(){if(!this.tokenEndpoint?.trim())throw new Error("requestDataFromServer: Token URL is not specified.");try{const t=await fetch(this.tokenEndpoint,{method:"GET"});if(!t.ok)throw new Error(`requestDataFromServer: Failed to request tokens (Status: ${t.status} ${t.statusText})`);const e=await t.json();if(!this.#s(e))throw new Error("requestDataFromServer: Invalid token response received from server.");await this.updateAuthData({accessToken:e.tokens.accessToken,refreshToken:e.tokens.refreshToken,avatarParameters:e.avatarParameters}),this.setConnected()}catch(t){throw this.setDisconnected(),t}}#s(t){return t?.tokens?.accessToken&&t?.tokens?.refreshToken&&t?.avatarParameters}async updateAvatarParametersFromServer(){try{const t=await this.callSentifydApi("/api/v1/chatbot/get-avatar-params","POST");if(!t||!t.data||!t.data.avatar_params)return;this.avatarParameters=t.data.avatar_params,this.updateAuthData({avatarParameters:this.avatarParameters})}catch(t){}}handleAuthenticationFailure(t,e=null){this.recordFailure({message:t,reason:e instanceof nt?e.reason:e instanceof Error?e.message:null,statusCode:e instanceof nt&&"number"==typeof e.statusCode?e.statusCode:null}),this.setFailed()}recordFailure({message:t,reason:e=null,statusCode:i=null}={}){this.lastFailureDetails={message:t||"Unknown authentication error",reason:e??(t||"Unknown authentication error"),statusCode:i,timestamp:Date.now()}}clearFailureDetails(){this.lastFailureDetails=null}getLastFailureDetails(){return this.lastFailureDetails?{...this.lastFailureDetails}:null}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.stopTokenRefreshInterval(),this.isFailed()?this.setReconnecting():this.setConnecting();try{await this.authenticate(),this.isConnected()?this.startTokenRefreshInterval():this.setFailed()}catch(t){this.handleAuthenticationFailure("Authentication reconnect failed",t)}}}static resetInstance(){ct._instance=null}}class ht{constructor(t,e=l){this.avatarId=t,this.conversationData={id:void 0,transcript:[],currentTurnId:0},this.lastDetectedLanguage=null,this.uuidGenerator=e}get conversationId(){return this.conversationData.id}set conversationId(t){this.conversationData.id=t}get transcript(){return this.conversationData.transcript}set transcript(t){this.conversationData.transcript=t}get currentTurnId(){return this.conversationData.currentTurnId}set currentTurnId(t){this.conversationData.currentTurnId=t}incrementTurnId(){return this.conversationData.currentTurnId++,this.conversationData.currentTurnId}async getConversationData(){if(!this.avatarId)return null;const t=await at.getItem(`conversationData_${this.avatarId}`),e={id:void 0,transcript:[],currentTurnId:0};return this.conversationData=t?{...e,...JSON.parse(t)}:e,this.conversationData}async saveConversationData(){this.avatarId&&await at.setItem(`conversationData_${this.avatarId}`,JSON.stringify(this.conversationData))}async notifyConversationInit(){await this.getConversationData(),this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId())}async notifyConversationStart(t=!1){t?(await this.clearOngoingConversation(),await this.generateNewConversationId()):(await this.getConversationData(),this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId())),this.incrementTurnId()}async notifyConversationEnd(t){await this.clearOngoingConversation()}async clearOngoingConversation(){this.conversationData={id:void 0,transcript:[],currentTurnId:0};try{await at.removeItem(`conversationData_${this.avatarId}`)}catch(t){await this.saveConversationData()}}discardConversationHistory(){this.transcript.length=0,this.saveConversationData()}async generateNewConversationId(){const t=this.uuidGenerator();this.conversationId=t,await this.saveConversationData()}async appendMessage(t,e,i){if(!this.conversationId)return null;const a={speaker:i,messageText:L(t),time:e};return this.transcript.push(a),await this.saveConversationData(),a}handleConversationSuccessfulStart(t){!1===t?.isInProgress&&this.transcript.length>0&&0===this.currentTurnId&&this.discardConversationHistory()}}class lt{constructor(){if(lt._instance)return lt._instance;this._avatarId=null,this._avatarName="",this._avatarItem=null,this._trainingId=null,this._language="",this._autodetectLanguages=[],this._voice="",this._lipsyncType="words",this._wordsPerMinute=150,this._userData={username:"",phoneNumber:"",email:"",isTermsAccepted:!1},this.conversation=null,lt._instance=this,Object.seal(this)}static getInstance(){return lt._instance||(lt._instance=new lt),lt._instance}static hasInstance(){return null!==lt._instance&&void 0!==lt._instance}static resetInstance(){if(lt._instance)try{return lt._instance.destroy(),lt._instance=null,!0}catch(t){return!1}return!0}async init(t,e){const{avatarId:i,avatarName:a,trainingId:n,language:s,autodetectLanguages:o,voice:r,wordsPerMinute:c}=t;if(![i,a,e,s,r].every((t=>null!=t&&""!==t))||!Array.isArray(o))return!1;this._trainingId=null===n||""===n?null:n,this._avatarId=i,this._avatarName=a,this._avatarItem=e,this._language=s,this._autodetectLanguages=o,this._voice=r,this._lipsyncType=e?.lipsyncType||"words",this._wordsPerMinute=c||150;try{return this.conversation=new ht(this._avatarId),!0}catch(h){return!1}}get isUserDataDefined(){return this._userData.username&&!0===this._userData.isTermsAccepted}get avatarId(){return this._avatarId}set avatarId(t){this._avatarId=t,this.conversation&&(this.conversation.avatarId=t)}get avatarName(){return this._avatarName}set avatarName(t){"string"==typeof t&&""!==t.trim()&&(this._avatarName=t)}get avatarItem(){return this._avatarItem}set avatarItem(t){t&&"object"==typeof t&&(this._avatarItem=t)}get trainingId(){return this._trainingId}set trainingId(t){(null==t||"string"==typeof t&&""!==t.trim())&&(this._trainingId=t)}get language(){return this._language}set language(t){"string"==typeof t&&""!==t.trim()&&(this._language=t)}get autodetectLanguages(){return this._autodetectLanguages}set autodetectLanguages(t){Array.isArray(t)&&(this._autodetectLanguages=t)}get voice(){return this._voice}set voice(t){"string"==typeof t&&""!==t.trim()&&(this._voice=t)}get lipsyncType(){return this._lipsyncType}set lipsyncType(t){["words","visemes","blendshapes"].includes(t)&&(this._lipsyncType=t)}get wordsPerMinute(){return this._wordsPerMinute}set wordsPerMinute(t){"number"!=typeof t||t<=0||(this._wordsPerMinute=t)}get username(){return this._userData.username}set username(t){"string"==typeof t&&""!==t.trim()&&(this._userData.username=t)}get phoneNumber(){return this._userData.phoneNumber}set phoneNumber(t){"string"==typeof t&&""!==t.trim()&&(this._userData.phoneNumber=t)}get email(){return this._userData.email}set email(t){"string"==typeof t&&""!==t.trim()&&(this._userData.email=t)}get isTermsAccepted(){return this._userData.isTermsAccepted}set isTermsAccepted(t){"boolean"==typeof t&&(this._userData.isTermsAccepted=t)}destroy(){try{this.conversation&&"function"==typeof this.conversation.destroy&&this.conversation.destroy()}catch(t){}}}function dt(t){try{t?.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t?.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}}lt._instance=null;const ut=d({id:"avatarOrchestrator",predictableActionArguments:!0,context:({input:t})=>({bus:t?.bus??null,talkingAvatar:t?.talkingAvatar??null,chatSocket:t?.chatSocket??null,voiceBot:t?.voiceBot??null,conversation:t?.conversation??null,eventPayload:null,isPageVisible:!0,currentPage:"LoaderPage",pendingStart:null,userSilenced:!1,initFailed:!1,firstConnectionCompleted:!1}),type:"parallel",states:{lifecycle:{initial:"init",states:{init:{initial:"initializing",states:{initializing:{id:"initializing",on:{READY:{target:"complete",actions:["onLeaveInitializing"]},FAIL:{target:"failed",actions:u({initFailed:!0})}}},failed:{id:"failed",on:{RETRY:{target:"initializing"},CONNECT:{target:"initializing"}}},complete:{always:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}}}},checkingResume:{id:"checkingResume",invoke:{id:"checkResumeOnStart",src:"checkResumeActor",input:({context:t})=>({conversation:t.conversation,bus:t.bus}),onDone:[{target:"conversation.resumable",guard:({event:t})=>!!t.output?.resumable},{target:"conversation.stopped"}],onError:{target:"conversation.stopped"}}},conversation:{initial:"stopped",states:{stopped:{id:"stopped",on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_FOUND:{target:"resumable"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},CONVERSATION_TIMEOUT:{target:"#avatarOrchestrator.lifecycle.conversation.timedOut"},DISCONNECT:{actions:[]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},timedOut:{id:"timedOut",entry:[({context:t,event:e})=>{try{const i=e?.payload?.conversationId??t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_TimedOut",{conversationId:i})}catch(i){}}],on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},resumable:{id:"resumable",on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],RESUME_CONVERSATION:{target:"inProgress.startingConversation",actions:u({eventPayload:{fresh:!1}})},START_NEW_CONVERSATION:{target:"inProgress.startingConversation",actions:u({eventPayload:{fresh:!0}})},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},STOP:{target:"stopped",actions:["onStop"]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},paused:{id:"paused",entry:["onConversationPaused"],tags:["conversation_paused","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},RECONNECT:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],RESTORED_CONNECTION:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},initializingConversation:{id:"initializingConversation",invoke:{id:"initConversationActor",src:"initConversationActor",input:({context:t})=>({conversation:t.conversation,chatSocket:t.chatSocket,bus:t.bus}),onDone:{target:"stopped",actions:"onConversationInitSuccess"},onError:{target:"stopped",actions:[u({initFailed:!0}),"onConversationInitFailed"]}},on:{FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},inProgress:{id:"inProgress",tags:["conversation_in_progress"],on:{STOP:{target:"stopped",actions:["onStop"]},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},DISCONNECT:[{target:"paused",guard:"hasActiveConversation"},{target:"stopped"}],AUDIO_START:{target:"#speaking",actions:["onAudioStarted"]},AI_MESSAGE_RECEIVED:{actions:[({context:t,event:e})=>{const{message:i}=e?.payload||{};if("string"==typeof i&&""!==i.trim())try{t.bus.emit("event_command_UI_UpdateCurrentMessage",{speaker:"assistant",messageText:L(i)})}catch(a){}},({context:t,event:e})=>{const i=e?.payload?.structuredResponse;if(i?.avatar_mood)try{t.bus.emit("event_command_Avatar_SetAvatarMood",{mood:i.avatar_mood})}catch(a){}},({context:t,event:e})=>{const{message:i,time:a}=e?.payload||{};t.conversation&&i&&(async()=>{try{const n=a||(new Date).toLocaleTimeString(),s=await t.conversation.appendMessage(i,n,"assistant");try{t.bus.emit("event_status_Conversation_MessageAppended",s)}catch(e){}}catch(e){}})()},({self:t})=>{try{setTimeout((()=>{try{const e=t.getSnapshot?.();e?.matches?.("lifecycle.conversation.inProgress.thinking")&&t?.send?.({type:"IDLE"})}catch(e){}}),0)}catch(e){}}]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}},initial:"idle",states:{idle:{id:"idle",entry:["onIdle"],on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},LISTEN:"listening",THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})},SEND_TEXT_MESSAGE:{target:"processingTextMessage"},MIC_BUTTON:[{guard:"isRequestBlocked",actions:["onMicButtonBlocked"]},{target:"listening",actions:["onMicButtonStartListening"]}],AUDIO_END:{actions:["onAudioEnd"]}}},listening:{id:"listening",tags:["listening"],entry:["onListenEntry"],invoke:{id:"listenActor",src:"listenActor",input:({context:t})=>({voiceBot:t.voiceBot,bus:t.bus}),onError:{target:"idle",actions:["onListenFailed"]}},on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:["onIdle",u({eventPayload:({event:t})=>t.payload})]},SPEECH_RECOGNITION_COMPLETE:{target:"processingSpeechRecognition"},SEND_TEXT_MESSAGE:{target:"processingTextMessage",actions:[({context:t})=>{if(t.voiceBot){t.voiceBot.stopListening();try{t.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t.bus.emit("event_command_UI_ClearCaptions")}catch(e){}}}]},MIC_BUTTON:{target:"idle",actions:["setUserSilencedTrue","onMicButtonStopListening"]},IDLE:"idle",AUDIO_END:{actions:["onAudioEnd"]}}},processingSpeechRecognition:{id:"processingSpeechRecognition",invoke:{id:"speechRecognitionActor",src:"speechRecognitionActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSpeechRecognitionFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},processingTextMessage:{id:"processingTextMessage",invoke:{id:"sendTextMessageActor",src:"sendTextMessageActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSendTextMessageFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},thinking:{id:"thinking",tags:["thinking","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}}},startingConversation:{id:"startingConversation",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"startConversationService",src:"startConversationService",input:({context:t})=>({isNew:t.eventPayload?.fresh||!1,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:{target:"thinking",actions:"onConversationStartSuccess"},onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped",actions:[u({initFailed:!0}),"onConversationStartFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle"}},pendingAudioStart:{id:"pendingAudioStart",tags:["thinking","inputs_blocked"],after:{speechStartTimeout:{guard:"isPendingAudioStart",target:"#speaking",actions:["onAudioStartedFallback"]}},on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},speaking:{id:"speaking",tags:["speaking"],on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},STREAM_END:{actions:["onStreamEnd"],internal:!0},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},interruptingForRestart:{id:"interruptingForRestart",entry:["onEnsureCleanupComplete"],invoke:{src:"cleanupInterruptionActor",input:({context:t})=>({talkingAvatar:t.talkingAvatar,chatSocket:t.chatSocket,voiceBot:t.voiceBot}),onDone:{target:"startingConversation"},onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}},tags:["inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]}}}}},endingConversation:{id:"endingConversation",tags:["inputs_blocked"],invoke:{id:"endConversationActor",src:"endConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar,voiceBot:t.voiceBot,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Failed to end the conversation."})}catch(e){}}]}}},clearingConversation:{id:"clearingConversation",tags:["inputs_blocked"],invoke:{id:"clearConversationActor",src:"clearConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,talkingAvatar:t.talkingAvatar,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Failed to clear the conversation."})}catch(e){}}]}}}}}}},connection:{initial:"connected",states:{connected:{id:"connected",on:{DISCONNECT:"disconnected"}},disconnected:{id:"disconnected",on:{RECONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:t=>t.firstConnectionCompleted||!0})]},CONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:t=>t.firstConnectionCompleted||!0})]}}}}}},on:{INJECT_MODULES:{actions:[u((({context:t,event:e})=>({talkingAvatar:e.payload?.talkingAvatar??t.talkingAvatar,chatSocket:e.payload?.chatSocket??t.chatSocket,voiceBot:e.payload?.voiceBot??t.voiceBot,conversation:e.payload?.conversation??t.conversation}))),({context:t,self:e})=>{try{const i=e.getSnapshot?.();(i?.matches?.("lifecycle.conversation.stopped")||i?.matches?.("lifecycle.conversation.timedOut"))&&t.conversation&&e.send({type:"AVATAR_INITIALIZED"})}catch(i){}}]},PAGE_CHANGED:{actions:["onPageChanged","setCurrentPage"]},DEFER_START:{actions:["onDeferStart"]},VISIBILITY_CHANGED:{actions:["onVisibilityChanged"]},UI_CHATBOT_MODE:{actions:["onUiChatbotMode"]},CONVERSATION_ERROR:{actions:["onConversationError"]},TTS_ERROR:{actions:["onTtsError"]},INTERRUPT:{actions:[({context:t})=>{try{t.talkingAvatar?.interruptSpeaking?.()}catch{}try{t.chatSocket?.interruptCurrentTurn?.()}catch{}try{t.voiceBot?.stopListening?.()}catch{}try{t.bus?.emit?.("event_command_UI_ClearCaptions")}catch{}}]}}},{actions:{onPageChanged:({context:t,event:e,self:i})=>{try{const n=e?.payload?.newPage;if(!n)return;const s=i.getSnapshot?.(),o=!!s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart"),r=!!s?.hasTag?.("listening")||s?.matches?.("lifecycle.conversation.inProgress.listening");if("AvatarPage"!==n&&(o||r)&&(o?i.send({type:"INTERRUPT"}):r&&i.send({type:"IDLE"})),"AvatarPage"===n)try{const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&t.isPageVisible&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}catch(a){}}catch(n){}},setCurrentPage:u((({event:t})=>{const e=t?.payload?.newPage;return e?{currentPage:e}:{}})),onDeferStart:u((({context:t,event:e})=>{if(!t.isPageVisible){const i=e.payload?.fresh??!1;return null!==t.pendingStart&&t.pendingStart,{pendingStart:i}}return null!==t.pendingStart?{pendingStart:null}:{}})),onVisibilityChanged:u((({context:t,event:e,self:i})=>{const a=e&&(e.payload?.isVisible??e.isVisible),n=void 0===a?!!t.isPageVisible:!!a,s=n&&!t.isPageVisible;if(!n&&t.isPageVisible){if(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),t.talkingAvatar){t.talkingAvatar.interruptSpeaking?.();try{t.talkingAvatar.suspendRendering?.("visibility")}catch(o){}}i.send({type:"IDLE"})}else{if(s&&null!==t.pendingStart){const e=t.pendingStart;return i.send({type:"START_CONVERSATION",payload:{fresh:e}}),{isPageVisible:n,pendingStart:null}}s&&t.voiceBot&&i.getSnapshot().matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})}try{if(n&&"AvatarPage"===t.currentPage){const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}}catch(o){}return{isPageVisible:n}})),onListenEntry:({context:t})=>{t.voiceBot&&dt(t)},onListenFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Could not start listening. Please try again."})}catch(i){}},onIdle:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening().success)},onStop:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening())},onAudioStarted:({context:t,event:e})=>{const i=e?.payload?.audioStartTime??("undefined"!=typeof performance?performance.now():Date.now());try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:i})}catch(a){}},onAudioStartedFallback:({context:t})=>{const e="undefined"!=typeof performance?performance.now():Date.now();try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:e})}catch(i){}},onStreamStart:({context:t,event:e})=>{const{audioStream:i,lipsyncStream:a,turnId:n}=e.payload||{};t.voiceBot&&void 0!==n&&(t.voiceBot._currentTurnId=n,t.voiceBot._expectedTurnId=n),t.talkingAvatar&&i&&a&&t.talkingAvatar.startStreaming(i,a,n)},onInterruptSpeaking:({context:t,self:e})=>{if(t.voiceBot){const i=Date.now();if(i-t.voiceBot._lastInterruptionTime<t.voiceBot.INTERRUPTION_DEBOUNCE)return;const a=-1!==t.voiceBot._expectedTurnId,n=t.voiceBot._isHandlingAudioEnd,s=e.getSnapshot(),o=s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart");a&&o&&!n&&(t.voiceBot._expectedTurnId=-1,t.voiceBot._lastInterruptionTime=i),dt(t),t.voiceBot.stopListening().success}t.talkingAvatar&&t.talkingAvatar.interruptSpeaking(),t.chatSocket&&t.chatSocket.interruptCurrentTurn()},onEnsureCleanupComplete:({context:t,self:e})=>{},onSpeechRecognitionFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Voice input failed. Please try again."})}catch(i){}},onSendTextMessageFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Message failed to send. Please retry."})}catch(i){}},onUiChatbotMode:({context:t,event:e,self:i})=>{const a=e.payload;if(!a||void 0===a.isShown&&!a.chatbotMode)return;const n=a.chatbotMode;if(t.chatSocket&&(void 0!==n&&(t.chatSocket.chatbotMode=n),void 0!==a.isShown&&(t.chatSocket.isChatbotShown=a.isShown)),"CHAT"===n){const e=i.getSnapshot();if(e.matches("lifecycle.conversation.inProgress.speaking")||e.matches("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(dt(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("chat")}catch(s){}}else if("AVATAR"===n)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),n=e.matches?.("lifecycle.conversation.inProgress.idle"),s=!!t.isPageVisible;a&&n&&s&&i.send({type:"LISTEN"})}catch(s){}if(!1===a.isShown)try{const e=i.getSnapshot();if(e.matches?.("lifecycle.conversation.inProgress.speaking")||e.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking?.()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(dt(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches?.("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("ui-hidden")}catch(s){}}catch(s){}else if(!0===a.isShown)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),s=e.matches?.("lifecycle.conversation.inProgress.idle"),o=!!t.isPageVisible;"AVATAR"===(void 0!==n?n:t.chatSocket?.chatbotMode)&&a&&s&&o&&i.send({type:"LISTEN"})}catch(s){}try{const e=void 0!==n?n:t.chatSocket?.chatbotMode,i=void 0!==a.isShown?a.isShown:!1!==t.chatSocket?.isChatbotShown;if("AVATAR"===e&&i&&t.isPageVisible&&"AvatarPage"===t.currentPage)t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.();else if(t.talkingAvatar?.isRenderingActive?.()&&("CHAT"===e||!i||!t.isPageVisible||"AvatarPage"!==t.currentPage))try{t.talkingAvatar?.suspendRendering?.("conditions-change")}catch(s){}}catch(s){}},onLeaveDisconnected:({self:t})=>t.send({type:"RESTORED_CONNECTION"}),onLeaveInitializing:({self:t})=>t.send({type:"AVATAR_INITIALIZED"}),onStartingConversation:({context:t,event:e})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening(),t.voiceBot._expectedTurnId=-1),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()},onConversationStartSuccess:({context:t,event:e})=>{if(!t.conversation)return;const i=e.output||{};t.conversation.handleConversationSuccessfulStart?.(i),t.talkingAvatar&&t.talkingAvatar.startConversationStream().catch(console.error)},onConversationStartFailed:({context:t,event:e})=>{},onConversationInitFailed:({context:t,event:e})=>{},onAudioEnd:({context:t,event:e})=>{const{turnId:i}=e.payload||{};if(dt(t),t.voiceBot){if(-1===t.voiceBot._expectedTurnId||i!==t.voiceBot._expectedTurnId)return;t.voiceBot._expectedTurnId=-1,t.voiceBot._isHandlingAudioEnd=!0}t.chatSocket?.pendingDelayedActions?.length>0&&(P(t.chatSocket.pendingDelayedActions,t.bus),t.chatSocket.pendingDelayedActions=null),t.voiceBot&&setTimeout((()=>{t.voiceBot._isHandlingAudioEnd=!1}),50)},onStreamEnd:({context:t})=>{try{t.talkingAvatar?.finalizeTurn?.()}catch(e){}if(t.chatSocket?.pendingDelayedActions?.length>0){try{P(t.chatSocket.pendingDelayedActions,t.bus)}catch(e){}t.chatSocket.pendingDelayedActions=null}},onMicButtonBlocked:({context:t})=>{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Please wait for the AI response before starting to speak."})},onMicButtonStartListening:u((()=>({userSilenced:!1}))),setUserSilencedTrue:u((()=>({userSilenced:!0}))),onMicButtonStopListening:({context:t})=>{},onMicButtonInterruptSpeaking:u((()=>({userSilenced:!1}))),emitVoiceBargeInEvent:({context:t,event:e})=>{const i=e?.payload||{};try{t.bus?.emit?.("event_status_Speech_BargeInTriggered",{micLevel:i.micLevel,avatarLevel:i.avatarLevel,ratio:i.ratio,delta:i.delta,timestamp:i.timestamp})}catch(a){}},onVoiceBargeIn:u((()=>({userSilenced:!1}))),onAssistantMessage:({context:t,event:e})=>{try{t.bus.emit("event_command_UI_AutoScrollChat",{message:e?.payload?.message||e?.message})}catch(i){}},onConversationError:({context:t,event:e,self:i})=>{const{error:a,chatbotMode:n}=e.payload||{};if(!a)return;if(t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:a.message||"Conversation error. Please try again."}),908===a.code&&void 0!==a.conversationId)return void i.send({type:"CONVERSATION_TIMEOUT",payload:{conversationId:a.conversationId}});const s=i.getSnapshot();s.matches("lifecycle.conversation.inProgress.thinking")&&i.send({type:"IDLE"}),"AVATAR"===n&&s.matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})},onTtsError:({context:t,self:e})=>{t.chatSocket?.cleanupActiveStreams();const i=e.getSnapshot();i.matches("lifecycle.conversation.inProgress.speaking")||i.matches("lifecycle.conversation.inProgress.pendingAudioStart")?(t.talkingAvatar?.interruptSpeaking&&t.talkingAvatar.interruptSpeaking(),e.send({type:"IDLE"})):e.send({type:"IDLE"})},onConversationPaused:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening()),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()}},guards:{isRequestBlocked:({self:t})=>{try{const e=t.getSnapshot?.();return!!e?.hasTag?.("thinking")}catch(e){return!1}},isAvatarMode:({context:t})=>{try{return"AVATAR"===t?.chatSocket?.chatbotMode}catch(e){return!1}},hasActiveConversation:({context:t})=>{if(!t.conversation)return!1;try{const e=!!t.conversation.conversationId,i=(t.conversation.conversationData?.currentTurnId||0)>0,a=Array.isArray(t.conversation.conversationData?.transcript)&&t.conversation.conversationData.transcript.length>0;return e&&(i||a)}catch(e){return!1}},isPendingAudioStart:({self:t})=>{try{return t.getSnapshot?.().matches?.("lifecycle.conversation.inProgress.pendingAudioStart")}catch(e){return!1}}},actors:{startConversationService:p((async({input:t})=>{const{isNew:e,conversation:i,chatSocket:a,talkingAvatar:n}=t||{};if(!i||!a)throw new Error("Conversation or ChatSocket module not available");if(await Promise.resolve(),n?.conversationStreamActive)try{await(n.stopConversationStream?.())}catch(s){}return e&&i.conversationId&&await i.notifyConversationEnd(),await i.notifyConversationStart(e),await a.sendStartConversationEvent()})),initConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i}=t||{};if(!e)throw new Error("Conversation module not available");return await e.notifyConversationInit(),i&&await i.sendInitConversationEvent(),{initialized:!0}})),listenActor:p((async({input:t})=>{const{voiceBot:e}=t||{};if(!e)return{started:!1};const i=await e.startListening();if(!i.success)throw new Error(i.error||"Failed to start listening");return{started:!0}})),speechRecognitionActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.messageText)throw new Error("Invalid speech payload");const s=await a.appendMessage(i.messageText,z(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(r){}const o=await e.sendMessage(i,"AVATAR");if(!o.success)throw(void 0).bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:o.error||"Failed to send your spoken message. Try again later."}),new Error(o.error||"Failed to process speech input");return{sent:!0}})),sendTextMessageActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.message)throw new Error("Invalid text payload");const s=await a.appendMessage(i.message,z(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(h){}const o={messageText:i.message},r=i.chatbotMode||"CHAT",c=await e.sendMessage(o,r);if(!c.success)throw(void 0).bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:c.error||"Failed to send your message. Please try again."}),new Error(c.error||"Failed to send text message");return{sent:!0}})),saveAssistantMessageActor:p((async({input:t})=>{const{conversation:e,bus:i,message:a,time:n,notify:s}=t||{};if(e)try{const t=n||z(new Date),c=await e.appendMessage(a,t,"assistant");try{i?.emit("event_status_Conversation_MessageAppended",c)}catch(o){}try{"function"==typeof s&&s({message:c})}catch(r){}}catch(o){try{i?.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:"Failed to add the AI response."})}catch(r){}try{"function"==typeof s&&s({message:{speaker:"assistant",messageText:a,time:n||z(new Date)}})}catch(r){}}else try{"function"==typeof s&&s({message:{speaker:"assistant",messageText:a,time:n||z(new Date)}})}catch(r){}})),endConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i,talkingAvatar:a,voiceBot:n,payload:s}=t||{};if(!e)return!0;const{satisfactionScore:o=0}=s||{},r=e.conversationId;if(await e.notifyConversationEnd(o),i&&r)try{i.sendEndConversationEvent(r,o)}catch(c){}try{a?.interruptSpeaking?.()}catch(c){}try{await(a?.stopConversationStream?.())}catch(c){}try{a?.liveCaptions?.clearCaptions?.(),n?.stopListening?.()}catch(c){}return!0})),clearConversationActor:p((async({input:t})=>{const{conversation:e,talkingAvatar:i,payload:a}=t||{};if(!e)return!0;const{conversationId:n}=a||{};if(n===e.conversationId){await e.clearOngoingConversation();try{await(i?.stopConversationStream?.())}catch(s){}}return!0})),checkResumeActor:p((async({input:t})=>{const{conversation:e,bus:i}=t||{};if(!e)return{resumable:!1};try{const t=await(e.getConversationData?.());if(t?.id&&Array.isArray(t.transcript)&&t.transcript.length>0){try{i?.emit("event_status_Conversation_Found_Initialized")}catch(a){}return{resumable:!0}}}catch(n){throw n}return{resumable:!1}})),cleanupInterruptionActor:p((async({input:t})=>{const{talkingAvatar:e,chatSocket:i,voiceBot:a}=t||{};try{try{e?.liveCaptions?.clearCaptions?.()}catch(n){}if(a)try{a.stopListening?.()}catch(n){}try{e?.interruptSpeaking?.()}catch(n){}try{i?.interruptCurrentTurn?.()}catch(n){}return await new Promise((t=>setTimeout(t,10))),!0}catch(s){throw s}}))},delays:{thinkingTimeout:E?.chatbot?.thinkingTimeout,speechStartTimeout:Math.min(Math.max(E?.chatbot?.speechStartTimeout??8e3,2e3),6e4)}});class pt{constructor(t){if(!t)throw new Error("Cannot initialize AvatarOrchestrator: missing bus instance");this.bus=t,this.actor=null,this._pendingEvents=[],this._deferredModules=null,this.diagnostics=null}start(t={}){if(this._deferredModules&&(t={...t,...this._deferredModules},this._deferredModules=null),this.actor)t&&Object.keys(t).length>0&&this.injectModules(t);else if(this.actor=m(ut,{input:{bus:this.bus,...t}}).start(),this.actor.subscribe((t=>{this.handleStateTransition(t)})),this._pendingEvents.length>0){for(const t of this._pendingEvents)this.actor.send(t);this._pendingEvents.length=0}}handleStateTransition(t){t&&this.diagnostics&&t?.changed&&(this.diagnostics.logStateTransition(t.history?.value,t.value),t.matches?.("lifecycle.conversation.stopped")&&this.diagnostics.displayDiagnosticsInConsole())}sendEvent(t,e=null){const i={type:t,payload:e};this.actor?this.actor.send(i):this._pendingEvents.push(i)}is(t){return!!this.actor&&this.actor.getSnapshot().matches(t)}getCurrentState(){return this.actor?.getSnapshot().value}getSnapshot(){return this.actor?this.actor.getSnapshot():null}destroy(){this.actor?.stop(),this.actor=null,this.diagnostics=null,this._pendingEvents=[]}interruptSpeaking(){this.sendEvent("INTERRUPT")}transitionToListening(){this.sendEvent("LISTEN")}transitionToIdle(){this.sendEvent("IDLE")}injectModules(t={}){this.actor?this.actor.send({type:"INJECT_MODULES",payload:t}):this._deferredModules={...this._deferredModules||{},...t}}subscribeProjected(t){if(!this.actor)return()=>{};let e={};const i=this.actor.subscribe((i=>{const a={lifecycle:{initInitializing:i.matches?.("lifecycle.init.initializing")||!1,initFailed:i.matches?.("lifecycle.init.failed")||!1,convoStopped:i.matches?.("lifecycle.conversation.stopped")||!1,convoResumable:i.matches?.("lifecycle.conversation.resumable")||!1,convoInProgress:i.matches?.("lifecycle.conversation.inProgress")||!1,convoStarting:i.matches?.("lifecycle.conversation.inProgress.startingConversation")||!1,convoInitializing:i.matches?.("lifecycle.conversation.initializingConversation")||!1,conversationSubstate:i.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")?"pendingAudioStart":i.matches?.("lifecycle.conversation.inProgress.speaking")?"speaking":i.matches?.("lifecycle.conversation.inProgress.listening")?"listening":i.matches?.("lifecycle.conversation.inProgress.thinking")?"thinking":i.matches?.("lifecycle.conversation.inProgress.startingConversation")?"startingConversation":i.matches?.("lifecycle.conversation.inProgress.idle")?"idle":""},connection:{connected:i.matches?.("connection.connected")||!1,disconnected:i.matches?.("connection.disconnected")||!1},flags:{userSilenced:i.context?.userSilenced||!1,isPageVisible:!!i.context?.isPageVisible,pendingStart:"boolean"==typeof i.context?.pendingStart?i.context.pendingStart:null}};!function(t,e){if(t===e)return!0;if(!t||!e)return!1;const i=t.lifecycle,a=e.lifecycle;if(!i||!a)return!1;if(i.initInitializing!==a.initInitializing||i.initFailed!==a.initFailed||i.convoStopped!==a.convoStopped||i.convoResumable!==a.convoResumable||i.convoInProgress!==a.convoInProgress||i.convoStarting!==a.convoStarting||i.convoInitializing!==a.convoInitializing||i.conversationSubstate!==a.conversationSubstate)return!1;const n=t.connection,s=e.connection;if(!n||!s)return!1;if(n.connected!==s.connected||n.disconnected!==s.disconnected)return!1;const o=t.flags,r=e.flags;return!(!o||!r)&&o.userSilenced===r.userSilenced&&o.isPageVisible===r.isPageVisible&&o.pendingStart===r.pendingStart}(a,e)&&(e=a,t(a,i))}));return()=>i.unsubscribe()}}class mt{constructor(t,e){if(!t||!e)throw new Error("Cannot initialize connectionManager due to missing bus or avatarOrchestrator");this.connectionModules={},this._allConnectionsReady=!1,this._wasAllReady=!1,this.isReconnecting=!1,this.bus=t,this.avatarOrchestrator=e,this._reconnectTimer=null,this._retryDelay=E?.connection?.reconnectInitialDelay,this._maxDelay=E?.connection?.reconnectMaxDelay,this._factor=E?.connection?.reconnectFactor,this._reconnectHandler=async()=>{try{this._resetBackoff(),await this.reconnectFailedModules(!0)}catch(t){}},this.bus.on("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler)}get allConnectionsReady(){return this._allConnectionsReady}set allConnectionsReady(t){this._allConnectionsReady=t}registerNewConnectionModule(t,e=null){try{const i=new Q(t);e&&(i.reconnect=e),i.subscribe((()=>this.updateAvatarState())),this.connectionModules[t]=i}catch(i){}}registerConnectionModule(t){try{if(!t||!t.name||"function"!=typeof t.subscribe)throw new Error("Invalid module: must have 'name' property and 'subscribe' method");t.subscribe((()=>this.updateAvatarState())),this.connectionModules[t.name]=t}catch(e){}}setReconnectFunction(t,e){try{const i=this.connectionModules[t];if(!i)return;i.reconnect=e}catch(i){}}waitUntilReady(t=15e3){return new Promise(((e,i)=>{if(this._allConnectionsReady)return e(!0);let a,n;const s=()=>{a&&clearTimeout(a),n&&this.bus.off("connectionStateChanged",n)};a=setTimeout((()=>{s(),i(new Error("Connection timeout"))}),t),n=()=>{this._allConnectionsReady&&(s(),e(!0))},this.bus.on("connectionStateChanged",n)}))}updateAvatarState(){if(!this.avatarOrchestrator)return;const t=Object.values(this.connectionModules).every((t=>t.isConnected()));if(Object.values(this.connectionModules).some((t=>t.isFailed())),this.allConnectionsReady=t,this.bus.emit("connectionStateChanged"),t){if(this._clearReconnectTimer(),!this._wasAllReady)try{const t=this.avatarOrchestrator.getSnapshot?.();t?.matches?.("connection.disconnected"),this.avatarOrchestrator.sendEvent("RECONNECT"),(t?.matches?.("lifecycle.init.failed")||t?.matches?.("lifecycle.init.initializing"))&&this.avatarOrchestrator.sendEvent("CONNECT")}catch(e){}this._wasAllReady=!0}else{if(this._scheduleAutoReconnect(),this._wasAllReady)try{this.avatarOrchestrator.sendEvent("DISCONNECT")}catch(e){}this._wasAllReady=!1}}async reconnectFailedModules(t=!1){if(this.isReconnecting)return;this.isReconnecting=!0;const e=Object.values(this.connectionModules).filter((t=>t.isFailed()||t.isDisconnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(e),this.isReconnecting=!1,this.updateAvatarState(),t||this._stepBackoff()}async reconnectDisconnectedModules(){if(this.isReconnecting)return;this.isReconnecting=!0;const t=Object.values(this.connectionModules).filter((t=>!t.isConnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(t),this.isReconnecting=!1,this.updateAvatarState()}getConnectionReport(){let t=`System is ${this.allConnectionsReady?"Ready":"Not Ready"}\n\n`;for(const e of Object.values(this.connectionModules))t+=`${e.name}: ${e.isConnected()?"connected":"disconnected"}, \n`;return t}_scheduleAutoReconnect(){this._reconnectTimer||(this._reconnectTimer=setTimeout((async()=>{this._reconnectTimer=null,await this.reconnectFailedModules()}),this._retryDelay))}_clearReconnectTimer(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._resetBackoff()}_resetBackoff(){this._retryDelay=E?.connection?.reconnectInitialDelay}_stepBackoff(){this._retryDelay=Math.min(Math.ceil(this._retryDelay*this._factor),this._maxDelay)}destroy(){try{this._reconnectHandler&&(this.bus?.off("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler),this._reconnectHandler=null),this._clearReconnectTimer()}catch(t){}}}let gt,yt,vt;const ft=[0,0,0,0],bt=new g.Vector3,_t=new g.Vector3,xt=new g.Vector3,kt=new g.Vector3;new g.Plane,new g.Ray,new g.Euler;const wt=new g.Quaternion,St=new g.Quaternion,At=new g.Matrix4,Ct=new g.Matrix4;new g.Vector3;const Rt=new g.Vector3(0,0,1),Tt=new g.Vector3(1,0,0),Lt=new g.Vector3(0,1,0),zt=new g.Vector3(0,0,1);class Mt{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map((t=>t.name))}getValue(t,e){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const i=this.dict[t];let a;if("type"===e)a=i.type;else if("stiffness"===e)a=i.k.every((t=>t===i.k[0]))?i.k[0]:[...i.k];else if("damping"===e)a=i.c.every((t=>t===i.c[0]))?i.c[0]:[...i.c];else if("external"===e)a=i.ext<1?i.ext:null;else if("limits"===e)a=i.limits?.map((t=>null===t?null:[...t]));else if("deltaLocal"===e)a=i.dl?[...i.dl]:null;else if("excludes"===e)a=i.excludes?[...i.excludes.map((t=>{const e={bone:t.bone.name.slice(),radius:t.radius};return t.deltaLocal&&(e.deltaLocal=[...t.deltaLocal]),e}))]:null;else if("deltaWorld"===e)a=i.dw?[...i.dw]:null;else if("pivot"===e)a=i.pivot;else{if("helper"!==e)throw new Error("Unsupported property '"+e+"'.");a=i.helper}return a}setValue(t,e,i){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const a=this.dict[t];if("type"===e){if(!i)throw new Error("Parameter 'type' not set.");if("string"!=typeof i)throw new Error("Type must be a string.");switch(i){case"point":a.isPoint=!0,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!1;break;case"link":a.isPoint=!1,a.isX=!0,a.isY=!1,a.isZ=!0,a.isT=!1;break;case"mix1":a.isPoint=!1,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!1;break;case"mix2":a.isPoint=!1,a.isX=!0,a.isY=!1,a.isZ=!0,a.isT=!0;break;case"full":a.isPoint=!1,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!0;break;default:throw new Error("Unknown type'"+i+"'.")}a.type=i.slice()}else if("stiffness"===e){if(!i)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(i)&&i>=0)a.k=Array(4).fill(i);else{if(!Array.isArray(i)||4!==i.length||!i.every((t=>t>=0)))throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.");a.k=[...i]}}else if("damping"===e){if(!i)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(i)&&i>=0)a.c=Array(4).fill(i);else{if(!Array.isArray(i)||4!==i.length||!i.every((t=>t>=0)))throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.");a.c=[...i]}}else if("external"===e)if(null==i)a.ext=1;else{if(!(!Number.isNaN(i)&&i>=0&&i<=1))throw new Error("External (if set) must be a number between [0,1].");a.ext=i}else if("limits"===e)if(null==i)a.limits=null;else{if(!Array.isArray(i)||4!==i.length)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!i.every((t=>null===t||Array.isArray(t)&&2===t.length&&(null===t[0]||!Number.isNaN(t[0]))&&(null===t[1]||!Number.isNaN(t)))))throw new Error("Limit values must be null or numbers.");a.limits=[i[0]?[...i[0]]:null,i[1]?[...i[1]]:null,i[2]?[...i[2]]:null,i[3]?[...i[3]]:null]}else if("excludes"===e){if(null==i)a.excludes=null;else{if(!Array.isArray(i))throw new Error("Excludes (if set) must null, or an array.");a.excludes=[],i.forEach(((t,e)=>{if(!t.bone)throw new Error("Bone not specified in #"+e+" exclude.");if("string"!=typeof t.bone||0===t.bone.length)throw new Error("Bone name must be a non-empty string in #"+e+" exclude.");const i=this.armature.getObjectByName(t.bone);if(!i)throw new Error("Bone '"+t.bone+"' not found in #"+e+" exclude.");if(Number.isNaN(t.radius)&&t.radius>=0)throw new Error("Radius must be a non-negative number in #"+e+" exclude.");const n={bone:i,radius:t.radius,radiusSq:t.radius*t.radius,deltaLocal:null};if(t.deltaLocal){if(!Array.isArray(t.deltaLocal)||3!==t.deltaLocal.length||t.deltaLocal.some((t=>Number.isNaN(t))))throw new Error("deltaLocal must be an array of three numbers in #"+e+" exclude.");n.deltaLocal=[...t.deltaLocal]}a.excludes.push(n)}))}this.showHelpers()}else if("helper"===e){if(null==i)a.helper=null;else{if(!1!==i&&!0!==i)throw new Error("Helper, if set, must be false or true.");a.helper=i}this.showHelpers()}else if("pivot"===e)if(null==i)a.pivot=null;else{if(!1!==i&&!0!==i)throw new Error("Pivot, if set, must be false or true.");if(!0===i&&0===a.type)throw new Error("Point type bone can't be a pivot.");a.pivot=i}else if("deltaLocal"===e)if(null==i)a.dl=null;else{if(!Array.isArray(i)||3!==i.length)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!i.every((t=>!Number.isNaN(t))))throw new Error("deltaLocal values must be numbers.");a.dl=[...i]}else{if("deltaWorld"!==e)throw new Error("Unsupported property "+e);if(null==i)a.dw=null;else{if(!Array.isArray(i)||3!==i.length)throw new Error("deltaWorld, is set, must be an array of three values.");if(!i.every((t=>!Number.isNaN(t))))throw new Error("deltaWorld values must be numbers.");a.dw=[...i]}}}getConfig(){return this.data.map((t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach((i=>{gt=this.getValue(t.name,i),gt&&(e[i]=gt)})),e}))}sortBones(){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse((i=>{e.has(i)||(e.set(i,t),t++)})),this.data.sort(((t,i)=>e.get(t.bone)-e.get(i.bone))),this.data.forEach((t=>{gt=this.dict[t.boneParent.name],gt&&(gt.children||(gt.children=[]),gt.children.push(t))})),this.objectsUpdate=[];const i=new WeakSet,a=t=>t.parent?.isBone?[t,...a(t.parent)]:[t],n=t=>{a(t).forEach((t=>{i.has(t)||(this.objectsUpdate.push(t),i.add(t))}))};this.data.forEach((t=>{n(t.bone),t.excludes&&t.excludes.forEach((t=>{n(t.bone)}))})),this.objectsUpdate.sort(((t,i)=>e.get(t)-e.get(i)))}setup(t,e,i){this.dispose();const a=(t,e)=>{if(!t)throw this.dispose(),new Error(e)};a(t?.isScene,"First parameter must be Scene."),this.scene=t,a(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,a(Array.isArray(i),"Third parameter must be an array of bone configs."),this.config=i,this.config.forEach(((t,e)=>{const i="Config item #"+e+": ";a(t.bone,i+"Bone not specified.");const n=t.bone;a("string"==typeof n&&n.length>0,i+"Bone name must be a non-empty string.");const s=this.armature.getObjectByName(n);a(s,i+"Bone '"+n+"' not found."),a(s.parent?.isBone,i+"Bone must have a parent bone."),a(this.data.every((t=>t.bone!==s)),i+"Bone '"+n+"' already exists."),s.updateMatrixWorld(!0);const o={name:n,bone:s,boneParent:s.parent,vBasis:s.position.clone(),vWorld:s.parent.getWorldPosition(bt).clone(),qBasis:s.parent.quaternion.clone(),l:s.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};o.boneParent.matrixWorld.decompose(bt,wt,xt),bt.copy(Rt).applyQuaternion(wt).setY(0).normalize(),wt.premultiply(St.setFromUnitVectors(Rt,bt).invert()).normalize(),o.qWorldInverseYaw=wt.clone().normalize(),this.data.push(o),this.dict[n]=o;try{this.setValue(n,"type",t.type),this.setValue(n,"stiffness",t.stiffness),this.setValue(n,"damping",t.damping),this.setValue(n,"external",t.external),this.setValue(n,"limits",t.limits),this.setValue(n,"excludes",t.excludes),this.setValue(n,"deltaLocal",t.deltaLocal),this.setValue(n,"deltaWorld",t.deltaWorld),this.setValue(n,"pivot",t.pivot),this.setValue(n,"helper",t.helper)}catch(r){a(!1,i+r)}})),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,i,a,n,s;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,a=this.objectsUpdate.length;e<a;e++)s=this.objectsUpdate[e],s.updateMatrix(),null===s.parent?s.matrixWorld.copy(s.matrix):s.matrixWorld.multiplyMatrices(s.parent.matrixWorld,s.matrix),s.matrixWorldNeedsUpdate=!1;for(e=0,a=this.data.length;e<a;e++){if(s=this.data[e],bt.copy(s.vWorld),At.copy(s.boneParent.matrixWorld),Ct.copy(At).invert(),s.vWorld.setFromMatrixPosition(At),bt.applyMatrix4(Ct),bt.length()>.5&&bt.setLength(.5),bt.applyQuaternion(s.bone.quaternion),ft[0]=bt.x,ft[1]=bt.y,ft[2]=-bt.z,ft[3]=bt.length()/3,s.children)for(i=0,n=s.children.length;i<n;i++)gt=s.children[i],ft[0]-=gt.v[0]*t/3,ft[1]-=gt.v[1]*t/3,ft[2]+=gt.v[2]*t/3,ft[3]-=gt.v[3]*t/3;if(gt=this.opt.sensitivityFactor,ft[0]*=s.ext*gt,ft[1]*=s.ext*gt,ft[2]*=s.ext*gt,ft[3]*=s.ext*gt,s.isX&&(gt=ft[0]/t,s.ea[0]=(gt-s.ev[0])/t,s.ev[0]=gt,s.a[0]=-s.k[0]*s.p[0]-s.c[0]*s.v[0]-s.ea[0],s.p[0]+=s.v[0]*t+s.a[0]*t*t/2+ft[0],gt=s.v[0]+s.a[0]*t/2,gt=-s.k[0]*s.p[0]-s.c[0]*gt-s.ea[0],s.v[0]=s.v[0]+(gt+s.a[0])*t/2),s.isY&&(gt=ft[1]/t,s.ea[1]=(gt-s.ev[1])/t,s.ev[1]=gt,s.a[1]=-s.k[1]*s.p[1]-s.c[1]*s.v[1]-s.ea[1],s.p[1]+=s.v[1]*t+s.a[1]*t*t/2+ft[1],gt=s.v[1]+s.a[1]*t/2,gt=-s.k[1]*s.p[1]-s.c[1]*gt-s.ea[1],s.v[1]=s.v[1]+(gt+s.a[1])*t/2),s.isZ&&(gt=ft[2]/t,s.ea[2]=(gt-s.ev[2])/t,s.ev[2]=gt,s.a[2]=-s.k[2]*s.p[2]-s.c[2]*s.v[2]-s.ea[2],s.p[2]+=s.v[2]*t+s.a[2]*t*t/2+ft[2],gt=s.v[2]+s.a[2]*t/2,gt=-s.k[2]*s.p[2]-s.c[2]*gt-s.ea[2],s.v[2]=s.v[2]+(gt+s.a[2])*t/2),s.isT&&(gt=ft[3]/t,s.ea[3]=(gt-s.ev[3])/t,s.ev[3]=gt,s.a[3]=-s.k[3]*s.p[3]-s.c[3]*s.v[3]-s.ea[3],s.p[3]+=s.v[3]*t+s.a[3]*t*t/2+ft[3],gt=s.v[3]+s.a[3]*t/2,gt=-s.k[3]*s.p[3]-s.c[3]*gt-s.ea[3],s.v[3]=s.v[3]+(gt+s.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(s.v[0]*=1e-4,s.p[0]*=1e-4,s.v[1]*=1e-4,s.p[1]*=1e-4,s.v[2]*=1e-4,s.p[2]*=1e-4,s.v[3]*=1e-4,s.p[3]*=1e-4),ft[0]=s.p[0],ft[1]=s.p[1],ft[2]=s.p[2],ft[3]=s.p[3],gt=this.opt.movementFactor,ft[0]*=gt,ft[1]*=gt,ft[2]*=gt,ft[3]*=gt,s.dl&&(gt=s.dl,ft[0]+=gt[0],ft[1]+=gt[1],ft[2]+=gt[2]),s.dw&&(gt=s.dw,bt.set(s.vBasis.x+ft[0],s.vBasis.y+ft[1],s.vBasis.z+ft[2]),bt.applyMatrix4(At),bt.x+=gt[0],bt.y+=gt[1],bt.z+=gt[2],bt.applyMatrix4(Ct),ft[0]+=bt.x-s.vBasis.x,ft[1]+=bt.y-s.vBasis.y,ft[2]+=bt.z-s.vBasis.z),s.limits&&this.opt.isLimits&&(gt=s.limits,gt[0]&&(null!==gt[0][0]&&ft[0]<gt[0][0]&&(ft[0]=gt[0][0]),null!==gt[0][1]&&ft[0]>gt[0][1]&&(ft[0]=gt[0][1])),gt[1]&&(null!==gt[1][0]&&ft[1]<gt[1][0]&&(ft[1]=gt[1][0]),null!==gt[1][1]&&ft[1]>gt[1][1]&&(ft[1]=gt[1][1])),gt[2]&&(null!==gt[2][0]&&ft[2]<gt[2][0]&&(ft[2]=gt[2][0]),null!==gt[2][1]&&ft[2]>gt[2][1]&&(ft[2]=gt[2][1])),gt[3]&&(null!==gt[3][0]&&ft[3]<gt[3][0]&&(ft[3]=gt[3][0]),null!==gt[3][1]&&ft[3]>gt[3][1]&&(ft[3]=gt[3][1]))),s.isPoint)s.bone.position.set(s.vBasis.x+ft[0],s.vBasis.y+ft[1],s.vBasis.z-ft[2]);else if(s.boneParent.quaternion.copy(s.qBasis),s.pivot&&this.opt.isPivots&&(s.boneParent.updateWorldMatrix(!1,!1),s.boneParent.matrixWorld.decompose(bt,wt,xt),bt.copy(Rt).applyQuaternion(wt).setY(0).normalize(),wt.premultiply(St.setFromUnitVectors(Rt,bt).invert()).normalize(),s.boneParent.quaternion.multiply(wt.invert()),s.boneParent.quaternion.multiply(s.qWorldInverseYaw)),s.isZ&&(gt=Math.atan(ft[0]/s.l),wt.setFromAxisAngle(zt,-gt),s.boneParent.quaternion.multiply(wt)),s.isY&&(gt=s.l/3,gt*=Math.tanh(ft[1]/gt),s.bone.position.setLength(s.l+gt)),s.isX&&(gt=Math.atan(ft[2]/s.l),wt.setFromAxisAngle(Tt,-gt),s.boneParent.quaternion.multiply(wt)),s.isT&&(gt=1.5*Math.tanh(1.5*ft[3]),wt.setFromAxisAngle(Lt,-gt),s.boneParent.quaternion.multiply(wt)),s.boneParent.updateWorldMatrix(!1,!0),s.excludes&&this.opt.isExcludes)for(i=0,n=s.excludes.length;i<n;i++)gt=s.excludes[i],xt.set(0,0,0),gt.deltaLocal&&(xt.x+=gt.deltaLocal[0],xt.y+=gt.deltaLocal[1],xt.z+=gt.deltaLocal[2]),xt.applyMatrix4(gt.bone.matrixWorld),Ct.copy(s.boneParent.matrixWorld).invert(),xt.applyMatrix4(Ct),bt.copy(s.bone.position),bt.distanceToSquared(xt)>=gt.radiusSq||(vt=bt.length(),yt=xt.length(),yt>gt.radius+vt||yt<Math.abs(gt.radius-vt)||(yt=(yt*yt+vt*vt-gt.radiusSq)/(2*yt),xt.normalize(),kt.copy(xt).multiplyScalar(yt),yt=Math.sqrt(vt*vt-yt*yt),bt.subVectors(bt,kt).projectOnPlane(xt).normalize().multiplyScalar(yt),_t.subVectors(s.vBasis,kt).projectOnPlane(xt).normalize(),vt=_t.dot(bt),vt<0&&(vt=Math.sqrt(yt*yt-vt*vt),_t.multiplyScalar(vt),bt.add(_t)),bt.add(kt).normalize(),xt.copy(s.bone.position).normalize(),wt.setFromUnitVectors(xt,bt),s.boneParent.quaternion.premultiply(wt),s.boneParent.updateWorldMatrix(!1,!0)))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=void 0===t?this.helpers.isShowAll:!0===t,gt=this.helpers,this.data.forEach((t=>{(this.helpers.isShowAll||!0===t.helper)&&(gt.points.bones.push(t.bone),gt.points.pivots.push(t.pivot),0!==t.type&&gt.lines.bones.push(t.bone),t.excludes&&t.excludes.forEach((t=>{let e=!1;for(let i=0;i<gt.excludes.bones.length;i++)if(gt.excludes.bones[i]===t.bone&&gt.excludes.radii[i]===t.radius&&(null!==gt.excludes.deltaLocals[i]||null===t.deltaLocal)&&!(null!==gt.excludes.deltaLocals[i]&&null===t.deltaLocal||null!==gt.excludes.deltaLocals[i]&&gt.excludes.deltaLocals[i].some(((e,i)=>e!==t.deltaLocal[i])))){e=!0;break}e||(gt.excludes.bones.push(t.bone),gt.excludes.radii.push(t.radius),gt.excludes.deltaLocals.push(t.deltaLocal?[...t.deltaLocal]:null),gt.excludes.objects.push(null))})))})),gt=this.helpers.excludes,this.opt.isExcludes&&gt.bones.length&&gt.bones.forEach(((t,e)=>{const i=new g.SphereGeometry(gt.radii[e],6,6),a=new g.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});gt.objects[e]=new g.Mesh(i,a),gt.objects[e].renderOrder=997,t.add(gt.objects[e]),gt.deltaLocals[e]&&gt.objects[e].position.set(gt.deltaLocals[e][0],gt.deltaLocals[e][1],gt.deltaLocals[e][2])})),gt=this.helpers.points,gt.bones.length){this.helpers.isActive=!0;const t=new g.BufferGeometry,e=gt.bones.map((t=>[0,0,0])).flat();t.setAttribute("position",new g.Float32BufferAttribute(e,3));const i=new g.Color(this.opt.helperBoneColor1),a=new g.Color(this.opt.helperBoneColor2),n=gt.pivots.map((t=>t&&this.opt.isPivots?[a.r,a.g,a.b]:[i.r,i.g,i.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(n,3));const s=new g.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});gt.object=new g.Points(t,s),gt.object.renderOrder=998,gt.object.matrix=this.armature.matrixWorld,gt.object.matrixAutoUpdate=!1,this.scene.add(gt.object)}if(gt=this.helpers.lines,gt.bones.length){const t=new g.BufferGeometry,e=gt.bones.map((t=>[0,0,0,0,0,0])).flat();t.setAttribute("position",new g.Float32BufferAttribute(e,3));const i=new g.Color(this.opt.helperLinkColor1),a=new g.Color(this.opt.helperLinkColor2),n=gt.bones.map((t=>[i.r,i.g,i.b,a.r,a.g,a.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(n,3));const s=new g.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});gt.object=new g.LineSegments(t,s),gt.object.renderOrder=999,gt.object.matrix=this.armature.matrixWorld,gt.object.matrixAutoUpdate=!1,this.scene.add(gt.object)}}updateHelpers(){if(gt=this.helpers.points,gt.bones.length){Ct.copy(this.armature.matrixWorld).invert();const t=gt.object.geometry.getAttribute("position");for(let e=0,i=gt.bones.length;e<i;e++)At.multiplyMatrices(Ct,gt.bones[e].matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(e,bt.x,bt.y,bt.z);t.needsUpdate=!0,gt.object.updateMatrixWorld()}if(gt=this.helpers.lines,gt.bones.length){Ct.copy(this.armature.matrixWorld).invert();const t=gt.object.geometry.getAttribute("position");for(let e=0,i=0,a=gt.bones.length;e<a;e++,i+=2)At.multiplyMatrices(Ct,gt.bones[e].matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(i,bt.x,bt.y,bt.z),At.multiplyMatrices(Ct,gt.bones[e].parent.matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(i+1,bt.x,bt.y,bt.z);t.needsUpdate=!0,gt.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach((t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)})),gt=this.helpers.excludes,gt.objects.forEach(((t,e)=>{t&&(gt.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())})),gt.bones=[],gt.deltaLocals=[],gt.radii=[],gt.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const e=this.data[t];e.bone.position.copy(e.vBasis),e.boneParent.quaternion.copy(e.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}let It=null;const Et=new g.Quaternion,Pt=new g.Euler,Dt=new g.Vector3,Ht=new g.Vector3,Ot=new g.Box3;new g.Matrix4,new g.Matrix4,new g.Vector3,new g.Vector3(0,0,1);const Bt=new g.Vector3(1,0,0);new g.Vector3(0,1,0),new g.Vector3(0,0,1);class Ft{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:0,mixerGainSpeech:null,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:2,lightDirectColor:8947882,lightDirectIntensity:30,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.2,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.5,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new x,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach((t=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach((e=>{this.poseDelta.props[t+e+".quaternion"]={x:0,y:0,z:0}})),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((e=>{this.poseDelta.props[t+e+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[t+e+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[t+e+"3.quaternion"]={x:0,y:0,z:0}}))}));const i=new Set;Object.values(this.poseTemplates).forEach((t=>{Object.keys(this.propsToThreeObjects(t.props)).forEach((t=>i.add(t)))})),Object.keys(this.poseDelta.props).forEach((t=>{i.add(t)})),this.posePropNames=[...i],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:.1},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:.1},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,(t=>{t.alt[0].delay[0]=t.alt[1].delay[0]=2e3})),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"šŸ˜":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"šŸ™‚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"šŸ™ƒ":{link:"šŸ™‚"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"šŸ˜‡":{link:"😊"},"šŸ˜€":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜„":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜†":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"šŸ˜‹":{link:"šŸ˜"},"šŸ˜›":{link:"šŸ˜"},"šŸ˜›":{link:"šŸ˜"},"😜":{link:"šŸ˜"},"🤪":{link:"šŸ˜"},"šŸ˜‚":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"šŸ˜‚"},"šŸ˜…":{link:"šŸ˜‚"},"šŸ˜‰":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🄺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"šŸ˜ž":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"šŸ˜”":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"ā˜¹ļø":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🄰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"šŸ˜":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"šŸ˜"},"😔":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"šŸ˜’":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"šŸ™„":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"šŸ¤”":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"šŸ‘€":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😓":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"āœ‹":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"šŸ‘‹":{link:"āœ‹"},"šŸ‘":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"šŸ‘Ž":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"šŸ‘Œ":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"šŸ¤·ā€ā™‚ļø":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"šŸ¤·ā€ā™€ļø":{link:"šŸ¤·ā€ā™‚ļø"},"🤷":{link:"šŸ¤·ā€ā™‚ļø"},"šŸ™":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:t=>Math.max(t,(this.mtAvatar.eyesLookDown?.value||0+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:t=>Math.max(t,(this.mtAvatar.eyesLookDown?.value||0+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach((t=>this.lipsyncGetProcessor(t))),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath,this.b64Lookup="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let n=0;n<64;n++)this.b64Lookup["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(n)]=n;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let t=new Audio;if(t.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else{if(!t.canPlayType("audio/mp3"))throw new Error("There was no support for either OGG or MP3 audio.");this.ttsAudioEncoding="MP3"}}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new g.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=g.SRGBColorSpace,this.renderer.toneMapping=g.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new g.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new g.Scene,this.lightAmbient=new g.AmbientLight(new g.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new g.DirectionalLight(new g.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new g.SpotLight(new g.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const t=new g.PMREMGenerator(this.renderer);t.compileEquirectangularShader(),this.scene.environment=t.fromScene(new _).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new y(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new g.SkinnedMesh;const a=[];Object.entries({LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"}).forEach(((t,e)=>{const i=new g.Bone;i.name=t[0],t[1]?this.ikMesh.getObjectByName(t[1]).add(i):this.ikMesh.add(i),a.push(i)})),this.ikMesh.bind(new g.Skeleton(a)),this.dynamicbones=new Mt,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&"closed"!==this.audioCtx.state&&this.audioCtx.close(),this.audioCtx=t?new AudioContext({sampleRate:t}):new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){}this.streamWorkletNode=null}}valueFn(t){return"function"==typeof t?t():t}deepCopy(t,e=null){const i=JSON.parse(JSON.stringify(t));return e&&"function"==typeof e&&e(i),i}b64ToArrayBuffer(t){let e=3*t.length/4;"="===t[t.length-1]&&(e--,"="===t[t.length-2]&&e--);const i=new ArrayBuffer(e),a=new Uint8Array(i);let n,s,o,r,c,h=0;for(n=0;n<t.length;n+=4)s=this.b64Lookup[t.charCodeAt(n)],o=this.b64Lookup[t.charCodeAt(n+1)],r=this.b64Lookup[t.charCodeAt(n+2)],c=this.b64Lookup[t.charCodeAt(n+3)],a[h++]=s<<2|o>>4,a[h++]=(15&o)<<4|r>>2,a[h++]=(3&r)<<6|63&c;return i}concatArrayBuffers(t){if(1===t.length)return t[0];let e=0;for(let s=0;s<t.length;s++)e+=t[s].byteLength;let i=new ArrayBuffer(e),a=new Uint8Array(i),n=0;for(let s=0;s<t.length;s++)a.set(new Uint8Array(t[s]),n),n+=t[s].byteLength;return i}pcmToAudioBuffer(t){const e=new Int16Array(t),i=new Float32Array(e.length);for(let n=0;n<e.length;n++)i[n]=e[n]>=32768?-(65536-e[n])/32768:e[n]/32767;const a=this.audioCtx.createBuffer(1,i.length,this.opt.pcmSampleRate);return a.copyToChannel(i,0,0),a}propsToThreeObjects(t){const e={};for(let[i,a]of Object.entries(t)){const t=i.split(".");let n=Array.isArray(a.x)?this.gaussianRandom(...a.x):a.x,s=Array.isArray(a.y)?this.gaussianRandom(...a.y):a.y,o=Array.isArray(a.z)?this.gaussianRandom(...a.z):a.z;"position"===t[1]||"scale"===t[1]?e[i]=new g.Vector3(n,s,o):"rotation"===t[1]?(i=t[0]+".quaternion",e[i]=(new g.Quaternion).setFromEuler(new g.Euler(n,s,o,"XYZ")).normalize()):"quaternion"===t[1]&&(e[i]=new g.Quaternion(n,s,o,a.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach((e=>{t.material[e]&&null!==t.material[e]&&"function"==typeof t.material[e].dispose&&t.material[e].dispose()})),t.material.dispose())}addMixedMorphTarget(t,e,i,a=!1){t.forEach((t=>{if(!a&&t.morphTargetDictionary.hasOwnProperty(e))return;const n=t.geometry;let s=null,o=null;for(const[e,a]of Object.entries(i))if(t.morphTargetDictionary.hasOwnProperty(e)){const i=t.morphTargetDictionary[e],r=n.morphAttributes.position[i],c=n.morphAttributes.normal?.[i];s||(s=new g.Float32BufferAttribute(3*r.count,3),c&&(o=new g.Float32BufferAttribute(3*r.count,3)));for(let t=0;t<r.count;t++){const e=s.getX(t)+r.getX(t)*a,i=s.getY(t)+r.getY(t)*a,n=s.getZ(t)+r.getZ(t)*a;s.setXYZ(t,e,i,n)}if(c)for(let t=0;t<r.count;t++){const e=o.getX(t)+c.getX(t)*a,i=o.getY(t)+c.getY(t)*a,n=o.getZ(t)+c.getZ(t)*a;o.setXYZ(t,e,i,n)}}if(s){n.morphAttributes.position.push(s),o&&n.morphAttributes.normal.push(o);const i=n.morphAttributes.position.length-1;t.morphTargetInfluences[i]=0,t.morphTargetDictionary[e]=i}}))}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const i=new v;if(this.dracoEnabled){const t=new f;t.setDecoderPath(this.dracoDecoderPath),i.setDRACOLoader(t)}let a=await i.loadAsync(t.url,e);const n=[this.opt.modelRoot];if(this.posePropNames.forEach((t=>n.push(t.split(".")[0]))),n.forEach((t=>{if(!a.scene.getObjectByName(t))throw new Error("Avatar object "+t+" not found")})),this.stop(),this.avatar=t,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=a.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=a.animations,this.userData=a.userData,this.morphs=[],this.armature.traverse((t=>{t.morphTargetInfluences&&t.morphTargetInfluences.length&&t.morphTargetDictionary&&this.morphs.push(t),t.frustumCulled=!1})),0===this.morphs.length)throw new Error("Blend shapes not found");const s=new Set(this.mtCustoms);this.morphs.forEach((t=>{Object.keys(t.morphTargetDictionary).forEach((t=>s.add(t)))})),this.mtExtras.forEach((t=>{s.has(t.key)||(this.addMixedMorphTarget(this.morphs,t.key,t.mix),s.add(t.key))}));const o={};if(s.forEach((t=>{o[t]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(t)?this.mtMinExceptions[t]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(t)?this.mtMaxExceptions[t]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(t)?this.mtAccExceptions[t]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(t)?this.mtMaxVExceptions[t]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(t)?this.mtLimits[t]:null,onchange:this.mtOnchange.hasOwnProperty(t)?this.mtOnchange[t]:null,baseline:this.avatar.baseline?.hasOwnProperty(t)?this.avatar.baseline[t]:this.mtBaselineExceptions.hasOwnProperty(t)?this.mtBaselineExceptions[t]:this.mtBaselineDefault,ms:[],is:[]},o[t].value=o[t].baseline,o[t].applied=o[t].baseline;const e=this.mtAvatar[t];e&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach((i=>{o[t][i]=e[i]})),this.morphs.forEach((e=>{const i=e.morphTargetDictionary[t];void 0!==i&&(o[t].ms.push(e.morphTargetInfluences),o[t].is.push(i),e.morphTargetInfluences[i]=o[t].applied)}))})),this.mtAvatar=o,this.poseAvatar={props:{}},this.posePropNames.forEach((t=>{const e=t.split("."),i=this.armature.getObjectByName(e[0]);this.poseAvatar.props[t]=i[e[1]],this.poseBase.props.hasOwnProperty(t)?this.poseAvatar.props[t].copy(this.poseBase.props[t]):this.poseBase.props[t]=this.poseAvatar.props[t].clone(),this.poseDelta.props.hasOwnProperty(t)&&!this.poseTarget.props.hasOwnProperty(t)&&(this.poseTarget.props[t]=this.poseAvatar.props[t].clone()),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=2e3})),this.ikMesh.traverse((t=>{t.isBone&&t.position.copy(this.armature.getObjectByName(t.name).position)})),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(a.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(c){}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const r=new g.Vector3;this.objectLeftEye.getWorldPosition(r),this.avatarHeight=r.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if("full"!==(t=t||this.viewName)&&"upper"!==t&&"head"!==t&&"mid"!==t)return;if(!this.armature)return void(this.opt.cameraView=t);if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const i=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,a=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,n=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,s=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,o=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,r=this.camera.fov*(Math.PI/180);let c=-i*Math.tan(r/2),h=(1-a)*Math.tan(r/2),l=n;switch(this.viewName){case"head":l+=2,h=h*l+4*this.avatarHeight/5;break;case"upper":l+=4.5,h=h*l+2*this.avatarHeight/3;break;case"mid":l+=8,h=h*l+this.avatarHeight/3;break;default:l+=12,h*=l}c*=l,this.controlsEnd=new g.Vector3(c,h,0),this.cameraEnd=new g.Vector3(c,h,l).applyEuler(new g.Euler(s,o,0)),null===this.cameraClock&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||((t=t||{}).hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new g.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=0!==t.lightAmbientIntensity),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new g.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=0!==t.lightDirectIntensity),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new g.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=0!==t.lightSpotIntensity),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new g.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer.render(this.scene,this.camera)}onResize(){this.isAvatarOnly||(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,i]of Object.entries(this.poseTarget.props)){const a=this.poseAvatar.props[e];if(a){let n=(t-i.t)/i.d;n>1||!this.poseBase.props.hasOwnProperty(e)?a.copy(i):a.isQuaternion?a.copy(this.poseBase.props[e].slerp(i,this.easing(n))):a.isVector3&&a.copy(this.poseBase.props[e].lerp(i,this.easing(n)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(0===e.x&&0===e.y&&0===e.z)continue;Pt.set(e.x,e.y,e.z);const i=this.poseAvatar.props[t];i.isQuaternion?(Et.setFromEuler(Pt),i.multiply(Et)):i.isVector3&&i.add(Pt)}}updateMorphTargets(t){for(let[e,i]of Object.entries(this.mtAvatar)){if(!i.needsUpdate)continue;let a=null,n=null;if(null!==i.fixed){if(a=i.fixed,i.system=null,i.systemd=null,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.value===a){i.needsUpdate=!1;continue}}else null!==i.realtime?(i.ref=null,i.base=null,n=i.realtime):null!==i.system?(a=i.system,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,null!==i.systemd?0===i.systemd?(a=null,i.system=null,i.systemd=null):(i.systemd-=t,i.systemd<0&&(i.systemd=0),i.value===a&&(a=null)):i.value===a&&(a=null,i.system=null)):null!==i.newvalue?(i.ref=null,i.base=null,n=i.newvalue,i.newvalue=null):null!==i.base?(a=i.base,i.ref=null,i.value===a&&(a=null,i.base=null,i.needsUpdate=!1)):(i.ref=null,null!==i.baseline&&i.value!==i.baseline?(a=i.baseline,i.base=i.baseline):i.needsUpdate=!1);if(null!==a){let e=a-i.value;e>=0?e<.005?(n=a,i.v=0):(i.v<i.maxv&&(i.v+=i.acc*t),n=i.v>=0?i.value+e*(1-Math.exp(-i.v*t)):i.value+i.v*t*(1-Math.exp(i.v*t))):e>-.005?(n=a,i.v=0):(i.v>-i.maxv&&(i.v-=i.acc*t),n=i.v>=0?i.value+i.v*t*(1-Math.exp(-i.v*t)):i.value+e*(1-Math.exp(i.v*t)))}if(null!==i.limit){if(null!==n&&n!==i.value&&(i.value=n,null!==i.onchange&&i.onchange(n)),n=i.limit(i.value),n===i.applied)continue}else{if(null===n||n===i.value)continue;i.value=n,null!==i.onchange&&i.onchange(n)}switch(i.applied=n,i.applied<i.min&&(i.applied=i.min),i.applied>i.max&&(i.applied=i.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=i.applied/2,this.poseDelta.props["Spine.quaternion"].x=i.applied/8,this.poseDelta.props["Hips.quaternion"].x=i.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=i.applied/2,this.poseDelta.props["Spine.quaternion"].y=i.applied/2,this.poseDelta.props["Hips.quaternion"].y=i.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=i.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=i.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=i.applied/12,this.poseDelta.props["Spine.quaternion"].z=i.applied/12,this.poseDelta.props["Hips.quaternion"].z=i.applied/24;break;case"handFistLeft":case"handFistRight":const t=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(((e,a)=>{0===a?(this.poseDelta.props[t+e+"1.quaternion"].x=0,this.poseDelta.props[t+e+"2.quaternion"].z=("Left"===t?-1:1)*i.applied,this.poseDelta.props[t+e+"3.quaternion"].z=("Left"===t?-1:1)*i.applied):(this.poseDelta.props[t+e+"1.quaternion"].x=i.applied,this.poseDelta.props[t+e+"2.quaternion"].x=1.5*i.applied,this.poseDelta.props[t+e+"3.quaternion"].x=1.5*i.applied)}));break;case"chestInhale":const a=i.applied/20,n={x:a,y:a/2,z:3*a},s={x:1/(1+a)-1,y:1/(1+a/2)-1,z:1/(1+3*a)-1};this.poseDelta.props["Spine1.scale"]=n,this.poseDelta.props["Neck.scale"]=s,this.poseDelta.props["LeftArm.scale"]=s,this.poseDelta.props["RightArm.scale"]=s;break;default:for(let e=0,o=i.ms.length;e<o;e++)i.ms[e][i.is[e]]=i.applied}}}getPoseString(t,e=1e3){let i="{";return Object.entries(t).forEach(((t,a)=>{const n=t[0].split(".");if("position"===n[1]||"rotation"===n[1]||"quaternion"===n[1]){const s="quaternion"===n[1]?n[0]+".rotation":t[0],o=t[1].isQuaternion?(new g.Euler).setFromQuaternion(t[1]):t[1];i+=(a?", ":"")+"'"+s+"':{",i+="x:"+Math.round(o.x*e)/e,i+=", y:"+Math.round(o.y*e)/e,i+=", z:"+Math.round(o.z*e)/e,i+="}"}})),i+="}",i}getPoseTemplateProp(t){const e=t.split(".");let i=e[0]+"."+("rotation"===e[1]?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(i))return this.gesture[i].clone();{let t,a=e[0]+"."+("quaternion"===e[1]?"rotation":e[1]);if(this.poseWeightOnLeft||(a.startsWith("Left")?(a="Right"+a.substring(4),i="Right"+i.substring(4)):a.startsWith("Right")&&(a="Left"+a.substring(5),i="Left"+i.substring(5))),this.poseTarget.template.props.hasOwnProperty(i)){const e={};e[i]=this.poseTarget.template.props[i],t=this.propsToThreeObjects(e)[i]}else if(this.poseTarget.template.props.hasOwnProperty(a)){const e={};e[a]=this.poseTarget.template.props[a],t=this.propsToThreeObjects(e)[i]}return t&&!this.poseWeightOnLeft&&t.isQuaternion&&(t.x*=-1,t.w*=-1),t}}mirrorPose(t){const e={};for(let[i,a]of Object.entries(t))a.isQuaternion&&(i.startsWith("Left")?i="Right"+i.substring(4):i.startsWith("Right")&&(i="Left"+i.substring(5)),a.x*=-1,a.w*=-1),e[i]=a.clone(),e[i].t=a.t,e[i].d=a.d;return e}poseFactory(t,e=2e3){const i={template:t,props:this.propsToThreeObjects(t.props)};for(const[a,n]of Object.entries(i.props)){if(this.opt.modelMovementFactor<1&&t.standing&&("Hips.quaternion"===a||"Spine.quaternion"===a||"Spine1.quaternion"===a||"Spine2.quaternion"===a||"Neck.quaternion"===a||"LeftUpLeg.quaternion"===a||"LeftLeg.quaternion"===a||"RightUpLeg.quaternion"===a||"RightLeg.quaternion"===a)){const t=this.poseStraight[a],e=n.angleTo(t);n.rotateTowards(t,(1-this.opt.modelMovementFactor)*e)}n.t=this.animClock,n.d=e}return i}setPoseFromTemplate(t,e=2e3){const i=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),a=t&&t===this.poseCurrentTemplate,n=this.poseWeightOnLeft;let s=i?1e3:e;if(i?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout((()=>{this.setPoseFromTemplate(t,e)}),s)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,s),this.poseWeightOnLeft=!0,(!a&&!n||a&&n)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[o,r]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(o)&&(this.poseTarget.props[o].copy(r),this.poseTarget.props[o].t=r.t,this.poseTarget.props[o].d=r.d);Object.keys(this.poseDelta.props).forEach((t=>{this.poseTarget.props.hasOwnProperty(t)||(this.poseTarget.props[t]=this.poseBase.props[t].clone(),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=s)}))}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,i=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:i,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let t=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?t=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(t=this.avatar.baseline[e]),this.setBaselineValue(e,t)}this.mood.anims.forEach((t=>{let e=this.animQueue.findIndex((e=>e.template.name===t.name));-1!==e&&this.animQueue.splice(e,1),this.animQueue.push(this.animFactory(t,-1))}))}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if("eyesRotateY"===t){const t=this.getBaselineValue("eyeLookOutLeft");if(void 0===t)return;const e=this.getBaselineValue("eyeLookInLeft");if(void 0===e)return;if(void 0===this.getBaselineValue("eyeLookOutRight"))return;if(void 0===this.getBaselineValue("eyeLookInRight"))return;return t-e}if("eyesRotateX"===t){const t=this.getBaselineValue("eyesLookDown");if(void 0===t)return;const e=this.getBaselineValue("eyesLookUp");if(void 0===e)return;return t-e}return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){"eyesRotateY"===t?(this.setBaselineValue("eyeLookOutLeft",null===e?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",null===e?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",null===e?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",null===e?null:e>0?e:0)):"eyesRotateX"===t?(this.setBaselineValue("eyesLookDown",null===e?null:e>0?e:0),this.setBaselineValue("eyesLookUp",null===e?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if("eyesRotateY"===t){const t=this.getFixedValue("eyeLookOutLeft");if(null===t)return null;const e=this.getFixedValue("eyeLookInLeft");return null===e||null===this.getFixedValue("eyeLookOutRight")||null===this.getFixedValue("eyeLookInRight")?null:t-e}if("eyesRotateX"===t){const t=this.getFixedValue("eyesLookDown");if(null===t)return null;const e=this.getFixedValue("eyesLookUp");return null===e?null:t-e}return this.mtAvatar[t]?.fixed}setFixedValue(t,e,i=null){"eyesRotateY"===t?(this.setFixedValue("eyeLookOutLeft",null===e?null:e>0?e:0,i),this.setFixedValue("eyeLookInLeft",null===e?null:e>0?0:-e,i),this.setFixedValue("eyeLookOutRight",null===e?null:e>0?0:-e,i),this.setFixedValue("eyeLookInRight",null===e?null:e>0?e:0,i)):"eyesRotateX"===t?(this.setFixedValue("eyesLookDown",null===e?null:e>0?e:0,i),this.setFixedValue("eyesLookUp",null===e?null:e>0?0:-e,i)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,i=1,a=1,n=!1){const s={template:t,ts:[0],vs:{}};let o=t;for(;;)if(o.hasOwnProperty(this.stateName))o=o[this.stateName];else if(o.hasOwnProperty(this.moodName))o=o[this.moodName];else if(o.hasOwnProperty(this.poseName))o=o[this.poseName];else if(o.hasOwnProperty(this.viewName))o=o[this.viewName];else if(this.avatar.body&&o.hasOwnProperty(this.avatar.body))o=o[this.avatar.body];else{if(!o.hasOwnProperty("alt"))break;{let t=o.alt[0];if(o.alt.length>1){const e=Math.random();let i=0;for(let a=0;a<o.alt.length;a++){let n=this.valueFn(o.alt[a].p);if(i+=void 0===n?(1-i)/(o.alt.length-1-a):n,e<i){t=o.alt[a];break}}}o=t}}let r=this.valueFn(o.delay)||0;if(Array.isArray(r)&&(r=this.gaussianRandom(...r)),o.hasOwnProperty("dt"))o.dt.forEach(((t,e)=>{let i=this.valueFn(t);Array.isArray(i)&&(i=this.gaussianRandom(...i)),s.ts[e+1]=s.ts[e]+i}));else{let t=Object.values(o.vs).reduce(((t,e)=>e.length>t?e.length:t),0);s.ts=Array(t+1).fill(0)}s.ts=n?s.ts.map((t=>r+t*i)):s.ts.map((t=>this.animClock+r+t*i));for(let[c,h]of Object.entries(o.vs)){const t=this.getBaselineValue(c),e=h.map((e=>null===(e=this.valueFn(e))?null:"function"==typeof e?e:"string"==typeof e||e instanceof String?e.slice():Array.isArray(e)?"gesture"===c?e.slice():(void 0===t?0:t)+a*this.gaussianRandom(...e):"boolean"==typeof e?e:e instanceof Object&&e.constructor===Object?Object.assign({},e):(void 0===t?0:t)+a*e));"eyesRotateY"===c?(s.vs.eyeLookOutLeft=[null,...e.map((t=>t>0?t:0))],s.vs.eyeLookInLeft=[null,...e.map((t=>t>0?0:-t))],s.vs.eyeLookOutRight=[null,...e.map((t=>t>0?0:-t))],s.vs.eyeLookInRight=[null,...e.map((t=>t>0?t:0))]):"eyesRotateX"===c?(s.vs.eyesLookDown=[null,...e.map((t=>t>0?t:0))],s.vs.eyesLookUp=[null,...e.map((t=>t>0?0:-t))]):s.vs[c]=[null,...e]}for(let c of Object.keys(s.vs))for(;s.vs[c].length<=s.ts.length;)s.vs[c].push(s.vs[c][s.vs[c].length-1]);return t.hasOwnProperty("mood")&&(s.mood=this.valueFn(t.mood).slice()),e&&(s.loop=e),s}valueAnimationSeq(t,e,i,a,n,s=null){t=this.valueFn(t),n<i&&(n=i),n>a&&(n=a);let o=((e=this.valueFn(e))-t)/(a-i);return s&&(o*=s((n-i)/(a-i))),o*n+(t-o*i)}gaussianRandom(t,e,i=1,a=5){let n=0;for(let s=0;s<a;s++)n+=Math.random();return t+Math.pow(n/a,i)*(e-t)}sigmoidFactory(t){function e(e){return 1/(1+Math.exp(-t*e))-.5}var i=.5/e(1);return function(t){return i*e(2*Math.max(Math.min(t,1),0)-1)+.5}}convertRange(t,e,i){return(t-e[0])*(i[1]-i[0])/(e[1]-e[0])+i[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e/=this.animSlowdownRate,this.animClock+=e;let i,a,n,s,o=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),i=2,n=10;i<n;i++)this.volumeFrequencyData[i]>o&&(o=this.volumeFrequencyData[i]);this.listeningVolume=(this.listeningVolume+o)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(o=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),i=2,n=10;i<n;i++)this.volumeFrequencyData[i]>o&&(o=this.volumeFrequencyData[i]);let r=null,c=null;const h=[];for(i=0,n=this.animQueue.length;i<n;i++){const t=this.animQueue[i];if(!(this.animClock<t.ts[0])){for(a=t.ndx||0,s=t.ts.length;a<s&&!(this.animClock<t.ts[a]);a++)for(let[e,i]of Object.entries(t.vs))if(this.mtAvatar.hasOwnProperty(e)){if(null===i[a+1])continue;const n=this.mtAvatar[e];if(null===i[a]&&(i[a]=n.value),a===s-1)n.newvalue=i[a];else{n.newvalue=i[a+1];const s=t.ts[a+1]-t.ts[a];let o=1;s>1e-4&&(o=(this.animClock-t.ts[a])/s),o<1&&(n.easing&&(o=n.easing(o)),n.newvalue=(1-o)*i[a]+o*n.newvalue),n.ref&&n.ref!==t.vs&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=t.vs}if(o)switch(e){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":n.newvalue*=1+o/255-.5}n.needsUpdate=!0}else"eyeContact"===e&&null!==i[a]&&!1!==r?r=Boolean(i[a]):"headMove"===e&&null!==i[a]&&!1!==c?0===i[a]?c=!1:(Math.random()<i[a]&&(c=!0),i[a]=null):null!==i[a]&&(h.push({mt:e,val:i[a]}),i[a]=null);a===s?(t.hasOwnProperty("mood")&&this.setMood(t.mood),t.loop?(s=!this.isSpeaking||"head"!==t.template.name&&"eyes"!==t.template.name?1:4,this.animQueue[i]=this.animFactory(t.template,t.loop>0?t.loop-1:t.loop,1,1/s)):(this.animQueue.splice(i--,1),n--)):t.ndx=a-1}}for(let l=0,d=h.length;l<d;l++)switch(a=h[l].val,h[l].mt){case"speak":this.speakText(a);break;case"subtitles":this.onSubtitles&&"function"==typeof this.onSubtitles&&this.onSubtitles(a);break;case"pose":this.poseName=a,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...a);break;case"function":a&&"function"==typeof a&&a();break;case"moveto":Object.entries(a.props).forEach((t=>{t[1]?this.poseTarget.props[t[0]].copy(t[1]):this.poseTarget.props[t[0]].copy(this.getPoseTemplateProp(t[0])),this.poseTarget.props[t[0]].t=this.animClock,this.poseTarget.props[t[0]].d=t[1]&&t[1].d?t[1].d:t.duration||2e3}));break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},a.x?new g.Vector3(a.x,a.y,a.z):null,!0,a.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},a.x?new g.Vector3(a.x,a.y,a.z):null,!0,a.d)}if((r||c)&&(Pt.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),Pt.x=Math.max(-.9,Math.min(.9,2*Pt.x-.5)),Pt.y=Math.max(-.9,Math.min(.9,-2.5*Pt.y)),r?(Object.assign(this.mtAvatar.eyesLookDown,{system:Pt.x<0?-Pt.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:Pt.x<0?0:Pt.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:Pt.y<0?-Pt.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:Pt.y<0?0:Pt.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:Pt.y<0?0:Pt.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:Pt.y<0?-Pt.y:0,needsUpdate:!0}),c&&(i=-this.mtAvatar.bodyRotateY.value,a=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[i,i,0],headRotateX:[a,a,0],headRotateZ:[-i/4,-i/4,0]}})))):(i=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,a=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,i,i,0],headRotateX:[null,a,a,0],headRotateZ:[null,-i/4,-i/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),("full"!==this.viewName||this.isAvatarOnly)&&(i=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],a=this.mtAvatar[i],a.needsUpdate||Object.assign(a,{base:(this.mood.baseline[i]||0)+(1+o/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),(this.isSpeaking||this.isListening)&&r?o>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=o):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),i=this.volumeHeadTarget-this.volumeHeadCurrent,a=Math.abs(i),a>1e-4&&(s=a*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/a)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(i)*Math.min(a,s)),Math.abs(this.volumeHeadCurrent)>1e-4&&(Et.setFromAxisAngle(Bt,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(Et)),Ot.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(Dt),Dt.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(Ht),Ht.sub(this.armature.position),this.objectHips.position.y-=Ot.min.y/2,this.objectHips.position.x-=(Dt.x+Ht.x)/4,this.objectHips.position.z-=(Dt.z+Ht.z)/2,this.dynamicbones.update(e),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(null!==this.cameraClock&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let t=(new g.Spherical).setFromVector3(this.cameraStart),i=(new g.Spherical).setFromVector3(this.cameraEnd);t.phi+=this.easing(this.cameraClock/1e3)*(i.phi-t.phi),t.theta+=this.easing(this.cameraClock/1e3)*(i.theta-t.theta),t.radius+=this.easing(this.cameraClock/1e3)*(i.radius-t.radius),t.makeSafe(),this.camera.position.setFromSpherical(t),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(t.setFromVector3(this.controlsStart),i.setFromVector3(this.controlsEnd),t.phi+=this.easing(this.cameraClock/1e3)*(i.phi-t.phi),t.theta+=this.easing(this.cameraClock/1e3)*(i.theta-t.theta),t.radius+=this.easing(this.cameraClock/1e3)*(i.radius-t.radius),t.makeSafe(),this.controls.target.setFromSpherical(t)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach((t=>{this.morphs.forEach((e=>{const i=e.morphTargetDictionary["viseme_"+t];void 0!==i&&(e.morphTargetInfluences[i]=0)}))}))}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const a="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const e=Object.assign({"./lipsync-de.mjs":()=>import("./lipsync-de-C2V1AwVF.js"),"./lipsync-en.mjs":()=>import("./lipsync-en-qcS35m6x.js"),"./lipsync-fi.mjs":()=>import("./lipsync-fi-OWUVeE-b.js"),"./lipsync-fr.mjs":()=>import("./lipsync-fr-wVng3ZAI.js"),"./lipsync-lt.mjs":()=>import("./lipsync-lt-CYf-0Xtf.js")}),i=`./lipsync-${t.toLowerCase()}.mjs`;if(e[i])return void e[i]().then((e=>{e&&e[a]&&(this.lipsync[t]=new e[a])}))}catch(i){}const n=e+"lipsync-"+t.toLowerCase()+".mjs";import(n).then((e=>{this.lipsync[t]=new e[a]}))}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,i=null,a=null){const n=/[!\.\?\n\p{Extended_Pictographic}]/gu,s=/[ ]/gu,o=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/gu,r=/[\p{Extended_Pictographic}]/gu,c=(e=e||{}).lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let h="",l="",d=0,u=[],p=[];const m=Array.from(this.segmenter.segment(t),(t=>t.segment));for(let g=0;g<m.length;g++){const t=g===m.length-1,y=m[g].match(o);let v=m[g].match(n);const f=m[g].match(r),b=m[g].match(s);if(v&&!t&&!f&&m[g+1].match(n)&&(v=!1),i&&(h+=m[g]),y&&(a&&!a.every((t=>g<t[0]||g>t[1]))||(l+=m[g])),(b||v||t)&&(l.length&&(l=this.lipsyncPreProcessText(l,c),l.length&&u.push({mark:d,word:l})),h.length&&(p.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[h]}}),h=""),l.length)){const t=this.lipsyncWordsToVisemes(l,c);if(t&&t.visemes&&t.visemes.length){const e=t.times[t.visemes.length-1]+t.durations[t.visemes.length-1];for(let i=0;i<t.visemes.length;i++)p.push({mark:d,template:{name:"viseme"},ts:[(t.times[i]-.6)/e,(t.times[i]+.5)/e,(t.times[i]+t.durations[i]+.5)/e],vs:{["viseme_"+t.visemes[i]]:[null,"PP"===t.visemes[i]||"FF"===t.visemes[i]?.9:.6,0]}})}l="",d++}if(v||t){if(u.length||t&&p.length){const t={anim:p};i&&(t.onSubtitles=i),u.length&&!e.avatarMute&&(t.text=u,e.avatarMood&&(t.mood=e.avatarMood),e.ttsLang&&(t.lang=e.ttsLang),e.ttsVoice&&(t.voice=e.ttsVoice),e.ttsRate&&(t.rate=e.ttsRate),e.ttsVoice&&(t.pitch=e.ttsPitch),e.ttsVolume&&(t.volume=e.ttsVolume)),this.speechQueue.push(t),u=[],l="",d=0,p=[]}if(f){let t=this.animEmojis[m[g]];t&&t.link&&(t=this.animEmojis[t.link]),t&&this.speechQueue.push({emoji:t})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let e=await fetch(t),i=await e.arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(i),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch(t){}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let e=await fetch(t),i=await e.arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(i)}else{const t=this.audioCtx.sampleRate,e=this.audioCtx.createBuffer(2,t,t);e.getChannelData(0)[0]=1,e.getChannelData(1)[0]=1,this.audioReverbNode.buffer=e}}setMixerGain(t,e=null,i=0){null!==t&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+i)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),null!==e&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+i)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,i=null){const a=(e=e||{}).lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,n={};if(t.words){let e=[];for(let n=0;n<t.words.length;n++){const s=t.words[n],o=t.wtimes[n];let r=t.wdurations[n];if(s.length&&(i&&e.push({template:{name:"subtitles"},ts:[o],vs:{subtitles:[" "+s]}}),!t.visemes)){const t=this.lipsyncPreProcessText(s,a),i=this.lipsyncWordsToVisemes(t,a);if(i&&i.visemes&&i.visemes.length){const t=i.times[i.visemes.length-1]+i.durations[i.visemes.length-1],a=Math.min(r,Math.max(0,r-150*i.visemes.length));let n=.6+this.convertRange(a,[0,r],[0,.4]);if(r=Math.min(r,200*i.visemes.length),t>0)for(let s=0;s<i.visemes.length;s++){const a=o+i.times[s]/t*r,c=i.durations[s]/t*r;e.push({template:{name:"viseme"},ts:[a-Math.min(60,2*c/3),a+Math.min(25,c/2),a+c+Math.min(60,c/2)],vs:{["viseme_"+i.visemes[s]]:[null,"PP"===i.visemes[s]||"FF"===i.visemes[s]?.9:n,0]}})}}}}if(t.visemes)for(let i=0;i<t.visemes.length;i++){const a=t.visemes[i],n=t.vtimes[i],s=t.vdurations[i];e.push({template:{name:"viseme"},ts:[n-2*s/3,n+s/2,n+s+s/2],vs:{["viseme_"+a]:[null,"PP"===a||"FF"===a?.9:.6,0]}})}if(t.markers)for(let i=0;i<t.markers.length;i++){const a=t.markers[i],n=t.mtimes[i];e.push({template:{name:"markers"},ts:[n],vs:{function:[a]}})}e.length&&(n.anim=e)}if(t.audio&&(n.audio=t.audio),t.anim?.name){let e=this.animFactory(t.anim,!1,1,1,!0);n.anim?n.anim.push(e):n.anim=[e]}i&&(n.onSubtitles=i),Object.keys(n).length&&(this.speechQueue.push(n),this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(this.armature&&(!this.isAudioPlaying||t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const t=this.audioPlaylist.shift();if("suspended"===this.audioCtx.state||"interrupted"===this.audioCtx.state){const t=this.audioCtx.resume(),i=new Promise(((t,e)=>setTimeout((()=>e("p2")),1e3)));try{await Promise.race([t,i])}catch(e){return void this.playAudio(!0)}}let i;if(Array.isArray(t.audio)){let e=this.concatArrayBuffers(t.audio);i=this.pcmToAudioBuffer(e)}else i=t.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=i,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",(()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)}),{once:!0});let a=0;t.anim&&(a=Math.abs(Math.min(0,...t.anim.map((t=>Math.min(...t.ts))))),t.anim.forEach((t=>{for(let e=0;e<t.ts.length;e++)t.ts[e]=this.animClock+t.ts[e]+a;this.animQueue.push(t)}))),this.audioSpeechSource.start(a/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async startSpeaking(t=!1){if(this.armature&&(!this.isSpeaking||t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let t=this.speechQueue.shift();if(t.emoji){this.lookAtCamera(500);let e=t.emoji.dt.reduce(((t,e)=>t+e),0);this.animQueue.push(this.animFactory(t.emoji)),setTimeout(this.startSpeaking.bind(this),e,!0)}else if(t.break)setTimeout(this.startSpeaking.bind(this),t.break,!0);else if(t.audio)this.lookAtCamera(500),this.speakWithHands(),this.audioPlaylist.push({anim:t.anim,audio:t.audio}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio();else if(t.text){this.lookAtCamera(500);try{let e="<speak>";t.text.forEach(((t,i)=>{i>0&&(e+=" <mark name='"+t.mark+"'/>"),e+=t.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')})),e+="</speak>";const i={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&"function"==typeof this.opt.jwtGet&&(i.headers.Authorization="Bearer "+await this.opt.jwtGet());const a=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),i),n=await a.json();if(200===a.status&&n&&n.audioContent){const e=this.b64ToArrayBuffer(n.audioContent),i=await this.audioCtx.decodeAudioData(e);this.speakWithHands();const a=[0];let s=0;t.text.forEach(((t,e)=>{if(e>0){let e=a[a.length-1];n.timepoints[s]&&(e=1e3*n.timepoints[s].timeSeconds,n.timepoints[s].markName===""+t.mark&&s++),a.push(e)}}));const o=[{mark:0,time:0}];a.forEach(((t,e)=>{if(e>0){let i=t-a[e-1];o[e-1].duration=i,o.push({mark:e,time:t})}}));let r=1e3*i.duration;r>this.opt.ttsTrimEnd&&(r-=this.opt.ttsTrimEnd),o[o.length-1].duration=r-o[o.length-1].time,t.anim.forEach((t=>{const e=o[t.mark];if(e)for(let i=0;i<t.ts.length;i++)t.ts[i]=e.time+t.ts[i]*e.duration+this.opt.ttsTrimStart})),this.audioPlaylist.push({anim:t.anim,audio:i}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}catch(e){this.startSpeaking(!0)}}else t.anim?(this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),t.anim.forEach(((t,e)=>{for(let i=0;i<t.ts.length;i++)t.ts[i]=this.animClock+10*e;this.animQueue.push(t)})),setTimeout(this.startSpeaking.bind(this),10*t.anim.length,!0)):t.marker?("function"==typeof t.marker&&t.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch(t){}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch(t){}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,i=null,a=null,n=null){if(this.stopSpeaking(),this.isStreaming=!0,void 0!==t.waitForAudioChunks&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=i,this.onMetrics=n,void 0!==t.sampleRate){const e=t.sampleRate;"number"==typeof e&&e>=8e3&&e<=96e3&&e!==this.audioCtx.sampleRate&&this.initAudioGraph(e)}if(void 0!==t.gain&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||0===this.streamWorkletNode.numberOfOutputs||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch(s){}if(!this.workletLoaded)try{const t=function(){if(It)return It;const t=new Blob(['class PlaybackWorklet extends AudioWorkletProcessor {\r\n static FSM = {\r\n IDLE: 0,\r\n PLAYING: 1,\r\n };\r\n\r\n constructor(options) {\r\n super();\r\n this.port.onmessage = this.handleMessage.bind(this);\r\n\r\n this._sampleRate = options?.processorOptions?.sampleRate || sampleRate;\r\n this._scale = 1 / 32768; // PCM16 -> float\r\n\r\n // Silence detection threshold (1 second) as a fallback safety net\r\n const silenceDurationSeconds = 1.0;\r\n this._silenceThresholdBlocks = Math.ceil((this._sampleRate * silenceDurationSeconds) / 128);\r\n\r\n // Metrics configuration via options\r\n const metricsCfg = options?.processorOptions?.metrics || {};\r\n this._metricsEnabled = metricsCfg.enabled !== false;\r\n const intervalHz = (typeof metricsCfg.intervalHz === "number" && metricsCfg.intervalHz > 0)\r\n ? metricsCfg.intervalHz : 2;\r\n // Metrics state (low-overhead)\r\n this._framesProcessed = 0;\r\n this._underrunBlocks = 0;\r\n this._maxQueueSamples = 0;\r\n this._lastMetricsSentAtFrame = 0;\r\n // Convert to frames between reports\r\n this._metricsIntervalFrames = Math.max(128, Math.round(this._sampleRate / intervalHz));\r\n\r\n this.reset();\r\n }\r\n\r\n /**\r\n * Resets the worklet to its initial IDLE state.\r\n */\r\n reset() {\r\n this._bufferQueue = [];\r\n this._currentChunk = null;\r\n this._currentChunkOffset = 0;\r\n this._state = PlaybackWorklet.FSM.IDLE;\r\n\r\n this._noMoreDataReceived = false;\r\n this._silenceFramesCount = 0;\r\n this._hasSentEnded = false;\r\n // Reset max queue tracker only when going idle\r\n this._maxQueueSamples = 0;\r\n }\r\n\r\n handleMessage(event) {\r\n const { type, data } = event.data;\r\n\r\n // INTERRUPT: The main thread wants to stop immediately.\r\n if (type === "stop") {\r\n this.reset();\r\n // Send final metrics showing cleared state\r\n if (this._metricsEnabled) {\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: PlaybackWorklet.FSM.IDLE,\r\n queuedSamples: 0,\r\n queuedMs: 0,\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n }\r\n return;\r\n }\r\n\r\n // Main thread has signaled that no more audio chunks will be sent for this utterance.\r\n if (type === "no-more-data") {\r\n this._noMoreDataReceived = true;\r\n return;\r\n }\r\n\r\n // Update metrics configuration at runtime\r\n if (type === "config-metrics" && data && typeof data === "object") {\r\n if ("enabled" in data) this._metricsEnabled = !!data.enabled;\r\n if (typeof data.intervalHz === "number" && data.intervalHz > 0) {\r\n const intervalHz = data.intervalHz;\r\n this._metricsIntervalFrames = Math.max(128, Math.round(this._sampleRate / intervalHz));\r\n }\r\n // Reset pacing so the next report aligns with new interval\r\n this._lastMetricsSentAtFrame = this._framesProcessed;\r\n return;\r\n }\r\n\r\n // New audio data has arrived.\r\n if (type === "audioData" && data instanceof ArrayBuffer) {\r\n this._noMoreDataReceived = false;\r\n // If we were idle, this new data kicks off the playback.\r\n if (this._state === PlaybackWorklet.FSM.IDLE) {\r\n this._state = PlaybackWorklet.FSM.PLAYING;\r\n this.port.postMessage({ type: "playback-started" });\r\n }\r\n\r\n // We only queue data if we are in the PLAYING state. This prevents\r\n // data from a previous, interrupted stream from lingering.\r\n if (this._state === PlaybackWorklet.FSM.PLAYING) {\r\n // Store as Int16Array view to avoid constructing it in process()\r\n this._bufferQueue.push(new Int16Array(data));\r\n this._silenceFramesCount = 0; // Reset silence counter on new data\r\n }\r\n }\r\n }\r\n\r\n process(inputs, outputs, parameters) {\r\n const outputChannel = outputs[0]?.[0];\r\n if (!outputChannel) {\r\n return true; // Keep alive even if output is temporarily disconnected\r\n }\r\n\r\n // If we are not playing, just output silence and wait.\r\n if (this._state !== PlaybackWorklet.FSM.PLAYING) {\r\n outputChannel.fill(0);\r\n return true; // Always return true to keep the processor alive\r\n }\r\n\r\n // Core PLAYING Logic\r\n const blockSize = outputChannel.length;\r\n let samplesCopied = 0;\r\n\r\n while (samplesCopied < blockSize) {\r\n if (!this._currentChunk || this._currentChunkOffset >= this._currentChunk.length) {\r\n if (this._bufferQueue.length > 0) {\r\n this._currentChunk = this._bufferQueue.shift();\r\n this._currentChunkOffset = 0;\r\n } else {\r\n // Buffer is empty. Check for end conditions.\r\n const isTimedOut = this._silenceFramesCount > this._silenceThresholdBlocks;\r\n\r\n if (this._noMoreDataReceived || isTimedOut) {\r\n // END OF PLAYBACK: Either explicitly signaled or timed out.\r\n if (!this._hasSentEnded) {\r\n this.port.postMessage({ type: "playback-ended" });\r\n this._hasSentEnded = true;\r\n }\r\n // Send final metrics showing cleared state\r\n if (this._metricsEnabled) {\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: PlaybackWorklet.FSM.IDLE,\r\n queuedSamples: 0,\r\n queuedMs: 0,\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n }\r\n this.reset(); // Reset to IDLE state for reuse\r\n break; // Exit while loop\r\n } else {\r\n // BUFFER UNDERRUN (LAG): Play silence and wait for more data.\r\n this._silenceFramesCount++;\r\n if (this._metricsEnabled) this._underrunBlocks++;\r\n break; // Exit while loop\r\n }\r\n }\r\n }\r\n\r\n // If we have a chunk (could be a new one from the logic above), process it.\r\n if (this._currentChunk) {\r\n const samplesToCopy = Math.min(\r\n blockSize - samplesCopied,\r\n this._currentChunk.length - this._currentChunkOffset\r\n );\r\n // Directly write to outputChannel to avoid extra copy\r\n const src = this._currentChunk;\r\n const baseSrc = this._currentChunkOffset;\r\n const baseDst = samplesCopied;\r\n const scale = this._scale;\r\n for (let i = 0; i < samplesToCopy; i++) {\r\n outputChannel[baseDst + i] = src[baseSrc + i] * scale;\r\n }\r\n\r\n this._currentChunkOffset += samplesToCopy;\r\n samplesCopied += samplesToCopy;\r\n }\r\n }\r\n\r\n // Zero-fill the remainder, if any, once per block\r\n if (samplesCopied < blockSize) {\r\n outputChannel.fill(0, samplesCopied);\r\n }\r\n\r\n // Update metrics (optional)\r\n if (this._metricsEnabled) {\r\n this._framesProcessed += blockSize;\r\n\r\n // Track queue depth in samples (approximate)\r\n let queuedSamples = 0;\r\n if (this._currentChunk) queuedSamples += Math.max(0, this._currentChunk.length - this._currentChunkOffset);\r\n for (let i = 0; i < this._bufferQueue.length; i++) queuedSamples += this._bufferQueue[i].length;\r\n if (queuedSamples > this._maxQueueSamples) this._maxQueueSamples = queuedSamples;\r\n\r\n // Periodically send metrics to main thread\r\n if (this._framesProcessed - this._lastMetricsSentAtFrame >= this._metricsIntervalFrames) {\r\n this._lastMetricsSentAtFrame = this._framesProcessed;\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: this._state,\r\n queuedSamples,\r\n queuedMs: Math.round((queuedSamples / this._sampleRate) * 1000),\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n // Don\'t reset max tracker - keep session peak until idle\r\n }\r\n }\r\n\r\n // ALWAYS return true to keep the processor alive for reuse.\r\n return true;\r\n }\r\n}\r\n\r\nregisterProcessor("playback-worklet", PlaybackWorklet);\r\n'],{type:"application/javascript"});return It=URL.createObjectURL(t),It}(),e=this.audioCtx.audioWorklet.addModule(t),i=new Promise(((t,e)=>setTimeout((()=>e(new Error("Worklet loading timed out"))),5e3)));await Promise.race([e,i]),this.workletLoaded=!0}catch(o){throw new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=t=>{if("playback-started"===t.data.type&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(s){}if("playback-ended"===t.data.type&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch(s){}if(this.onMetrics&&"metrics"===t.data.type)try{this.onMetrics(t.data)}catch(s){}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch(s){}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=a||null,"suspended"===this.audioCtx.state||"interrupted"===this.audioCtx.state){const t=this.audioCtx.resume(),e=new Promise(((t,e)=>setTimeout((()=>e("p2")),1e3)));try{await Promise.race([t,e])}catch(s){return}}}streamNotifyEnd(){this.isStreaming&&this.streamWorkletNode&&this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch(e){}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch(e){}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch(t){}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&"visemes"==this.streamLipsyncType)for(let i=0;i<t.visemes.length;i++){const a=t.visemes[i],n=e+t.vtimes[i],s=t.vdurations[i],o={template:{name:"viseme"},ts:[n-2*s/3,n+s/2,n+s+s/2],vs:{["viseme_"+a]:[null,"PP"===a||"FF"===a?.9:.6,0]}};this.animQueue.push(o)}if(t.words&&(this.onSubtitles||"words"==this.streamLipsyncType))for(let i=0;i<t.words.length;i++){const a=t.words[i],n=t.wtimes[i];let s=t.wdurations[i];if(a.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+n],vs:{subtitles:[" "+a]}}),"words"==this.streamLipsyncType)){const t=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,i=this.lipsyncPreProcessText(a,t),o=this.lipsyncWordsToVisemes(i,t);if(o&&o.visemes&&o.visemes.length){const t=o.times[o.visemes.length-1]+o.durations[o.visemes.length-1],i=Math.min(s,Math.max(0,s-150*o.visemes.length));let a=.6+this.convertRange(i,[0,s],[0,.4]);if(s=Math.min(s,200*o.visemes.length),t>0)for(let r=0;r<o.visemes.length;r++){const i=e+n+o.times[r]/t*s,c=o.durations[r]/t*s;this.animQueue.push({template:{name:"viseme"},ts:[i-Math.min(60,2*c/3),i+Math.min(25,c/2),i+c+Math.min(60,c/2)],vs:{["viseme_"+o.visemes[r]]:[null,"PP"===o.visemes[r]||"FF"===o.visemes[r]?.9:a,0]}})}}}}if(t.anims&&"blendshapes"==this.streamLipsyncType)for(let i=0;i<t.anims.length;i++){let a=t.anims[i];a.delay+=e;let n=this.animFactory(a,!1,1,1,!0);this.animQueue.push(n)}}}streamAudio(t){if(this.isStreaming&&this.streamWorkletNode){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",void 0!==t.audio){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const i=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=i,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const i=new Int16Array(t.audio.length);for(let e=0;e<t.audio.length;e++){let a=Math.max(-1,Math.min(1,t.audio[e]));i[e]=a<0?32768*a:32767*a}e.data=i.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime)return this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),void this.streamLipsyncQueue.push(t);this.streamWaitForAudioChunks||this.streamAudioStartTime||(this.streamAudioStartTime=this.animClock),this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,i=(Math.random()-.5)/4,a=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==a&&this.animQueue.splice(a,1);const n={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[i],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*i],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(n))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new g.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),Dt.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),Ht.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(Dt,Ht).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera)return void this.lookAhead(t)}else if(this.opt.avatarIgnoreCamera)return void this.lookAhead(t);return void this.lookAt(null,null,t)}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),Dt.setFromMatrixPosition(this.objectLeftEye.matrixWorld),Ht.setFromMatrixPosition(this.objectRightEye.matrixWorld),Dt.add(Ht).divideScalar(2),Et.copy(this.armature.quaternion),Et.multiply(this.poseTarget.props["Hips.quaternion"]),Et.multiply(this.poseTarget.props["Spine.quaternion"]),Et.multiply(this.poseTarget.props["Spine1.quaternion"]),Et.multiply(this.poseTarget.props["Spine2.quaternion"]),Et.multiply(this.poseTarget.props["Neck.quaternion"]),Et.multiply(this.poseTarget.props["Head.quaternion"]);const i=(new g.Vector3).subVectors(e,Dt).normalize(),a=Math.atan2(i.x,i.z),n=Math.asin(-i.y);Pt.set(n,a,0,"YXZ");const s=(new g.Quaternion).setFromEuler(Pt),o=(new g.Quaternion).copy(s).multiply(Et.clone().invert());Pt.setFromQuaternion(o,"YXZ");let r=Pt.x/(40/24)+.2,c=Pt.y/(9/4),h=Math.min(.6,Math.max(-.3,r)),l=Math.min(.8,Math.max(-.8,c)),d=(Math.random()-.5)/4,u=(Math.random()-.5)/4;if(t){let e=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==e&&this.animQueue.splice(e,1);const i={name:"lookat",dt:[750,t],vs:{bodyRotateX:[h+d],bodyRotateY:[l+u],eyesRotateX:[-3*d+.1],eyesRotateY:[-5*u],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(i))}}lookAt(t,e,i){if(!this.camera)return;const a=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const n=(new g.Vector3).setFromMatrixPosition(this.objectLeftEye.matrixWorld),s=(new g.Vector3).setFromMatrixPosition(this.objectRightEye.matrixWorld),o=(new g.Vector3).addVectors(n,s).divideScalar(2);o.project(this.camera);let r=(o.x+1)/2*a.width+a.left,c=-(o.y-1)/2*a.height+a.top;null===t&&(t=r),null===e&&(e=c),Et.copy(this.armature.quaternion),Et.multiply(this.poseTarget.props["Hips.quaternion"]),Et.multiply(this.poseTarget.props["Spine.quaternion"]),Et.multiply(this.poseTarget.props["Spine1.quaternion"]),Et.multiply(this.poseTarget.props["Spine2.quaternion"]),Et.multiply(this.poseTarget.props["Neck.quaternion"]),Et.multiply(this.poseTarget.props["Head.quaternion"]),Pt.setFromQuaternion(Et);let h=Pt.x/(40/24),l=Pt.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),u=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),p=Math.max(window.innerWidth-r,r),m=Math.max(window.innerHeight-c,c),y=this.convertRange(e,[c-m,c+m],[-.3,.6])-h+d,v=this.convertRange(t,[r-p,r+p],[-.8,.8])-l+u;y=Math.min(.6,Math.max(-.3,y)),v=Math.min(.8,Math.max(-.8,v));let f=(Math.random()-.5)/4,b=(Math.random()-.5)/4;if(i){let t=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==t&&this.animQueue.splice(t,1);const e={name:"lookat",dt:[750,i],vs:{bodyRotateX:[y+f],bodyRotateY:[v+b],eyesRotateX:[-3*f+.1],eyesRotateY:[-5*b],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(e))}}touchAt(t,e){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect(),a=new g.Vector2((t-i.left)/i.width*2-1,-(e-i.top)/i.height*2+1),n=new g.Raycaster;n.setFromCamera(a,this.camera);const s=n.intersectObject(this.armature);if(s.length>0){const t=s[0].point,e=new g.Vector3,i=new g.Vector3;this.objectLeftArm.getWorldPosition(e),this.objectRightArm.getWorldPosition(i),e.distanceToSquared(t)<i.distanceToSquared(t)?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},t,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},t,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach((t=>{let e=t+".quaternion";this.poseTarget.props[e].copy(this.getPoseTemplateProp(e)),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3}));return s.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new g.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new g.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const i=[],a=[];i.push(100+Math.round(500*Math.random())),a.push({duration:1e3,props:{"LeftHand.quaternion":(new g.Quaternion).setFromEuler(new g.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":(new g.Quaternion).setFromEuler(new g.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach((t=>{a[0].props[t+".quaternion"]=this.ikMesh.getObjectByName(t).quaternion.clone()})),i.push(1e3+Math.round(500*Math.random())),a.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach((t=>{a[1].props[t+".quaternion"]=null}));const n=this.animFactory({name:"talkinghands",delay:t,dt:i,vs:{moveto:a}});this.animQueue.push(n)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&!1===this.isRunning&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},i=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=i&&"function"==typeof i?i:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,i=10,a=0,n=.01){if(!this.armature)return;let s=this.animClips.find((e=>e.url===t+"-"+a));if(s){let t=this.animQueue.find((t=>"pose"===t.template.name));t&&(t.ts[0]=1/0),Object.entries(s.pose.props).forEach((t=>{this.poseBase.props[t[0]]=t[1].clone(),this.poseTarget.props[t[0]]=t[1].clone(),this.poseTarget.props[t[0]].t=0,this.poseTarget.props[t[0]].d=1e3})),this.mixer=new g.AnimationMixer(this.armature),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const e=Math.ceil(i/s.clip.duration),a=this.mixer.clipAction(s.clip);a.setLoop(g.LoopRepeat,e),a.clampWhenFinished=!0,a.fadeIn(.5).play()}else{const s=new b;let o=await s.loadAsync(t,e);if(o&&o.animations&&o.animations[a]){let s=o.animations[a];const r={};s.tracks.forEach((t=>{t.name=t.name.replaceAll("mixamorig","");const e=t.name.split(".");if("position"===e[1]){for(let e=0;e<t.values.length;e++)t.values[e]=t.values[e]*n;r[t.name]=new g.Vector3(t.values[0],t.values[1],t.values[2])}else"quaternion"===e[1]?r[t.name]=new g.Quaternion(t.values[0],t.values[1],t.values[2],t.values[3]):"rotation"===e[1]&&(r[e[0]+".quaternion"]=(new g.Quaternion).setFromEuler(new g.Euler(t.values[0],t.values[1],t.values[2],"XYZ")).normalize())}));const c={props:r};r["Hips.position"]&&(r["Hips.position"].y<.5?c.lying=!0:c.standing=!0),this.animClips.push({url:t+"-"+a,clip:s,pose:c}),this.playAnimation(t,e,i,a,n)}}}stopAnimation(){if(this.mixer=null,this.gesture)for(let[e,i]of Object.entries(this.gesture))i.t=this.animClock,i.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(i),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find((t=>"pose"===t.template.name));t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,i=5,a=0,n=.01){if(!this.armature)return;let s=this.poseTemplates[t];if(!s){const e=this.animPoses.find((e=>e.url===t+"-"+a));e&&(s=e.pose)}if(s){this.poseName=t,this.mixer=null;let e=this.animQueue.find((t=>"pose"===t.template.name));e&&(e.ts[0]=this.animClock+1e3*i+2e3),this.setPoseFromTemplate(s)}else{const s=new b;let o=await s.loadAsync(t,e);if(o&&o.animations&&o.animations[a]){let s=o.animations[a];const r={};s.tracks.forEach((t=>{t.name=t.name.replaceAll("mixamorig","");const e=t.name.split(".");"position"===e[1]?r[t.name]=new g.Vector3(t.values[0]*n,t.values[1]*n,t.values[2]*n):"quaternion"===e[1]?r[t.name]=new g.Quaternion(t.values[0],t.values[1],t.values[2],t.values[3]):"rotation"===e[1]&&(r[e[0]+".quaternion"]=(new g.Quaternion).setFromEuler(new g.Euler(t.values[0],t.values[1],t.values[2],"XYZ")).normalize())}));const c={props:r};r["Hips.position"]&&(r["Hips.position"].y<.5?c.lying=!0:c.standing=!0),this.animPoses.push({url:t+"-"+a,pose:c}),this.playPose(t,e,i,a,n)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,i=!1,a=1e3){if(!this.armature)return;let n=this.gestureTemplates[t];if(n){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let s=this.animQueue.findIndex((t=>"talkinghands"===t.template.name));-1!==s&&(this.animQueue[s].ts=this.animQueue[s].ts.map((t=>0))),this.gesture=this.propsToThreeObjects(n),i&&(this.gesture=this.mirrorPose(this.gesture)),"namaste"===t&&"M"===this.avatar.body&&(this.gesture["RightArm.quaternion"].rotateTowards(new g.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new g.Quaternion(0,1,0,0),-.25));for(let[t,e]of Object.entries(this.gesture))e.t=this.animClock,e.d=a,this.poseTarget.props.hasOwnProperty(t)&&(this.poseTarget.props[t].copy(e),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=a);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,a),1e3*e))}let s=this.animEmojis[t];if(s&&(s&&s.link&&(s=this.animEmojis[s.link]),s)){this.lookAtCamera(500);const t=this.animFactory(s);if(t.gesture=!0,e&&Number.isFinite(e)){const i=t.ts[0],a=t.ts[t.ts.length-1]-i;if(1e3*e-a>0){const n=[];for(let e=1;e<t.ts.length;e++)n.push(t.ts[e]-t.ts[e-1]);const o=s.template?.rescale||n.map((t=>t/a)),r=1e3*e-a;t.ts=t.ts.map(((t,e,a)=>0===e?i:a[e-1]+n[e-1]+o[e-1]*r))}else{const n=1e3*e/a;t.ts=t.ts.map((t=>i+n*(t-i)))}}this.animQueue.push(t)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const e=Object.entries(this.gesture);this.gesture=null;for(const[i,a]of e)this.poseTarget.props.hasOwnProperty(i)&&(this.poseTarget.props[i].copy(this.getPoseTemplateProp(i)),this.poseTarget.props[i].t=this.animClock,this.poseTarget.props[i].d=t)}let e=this.animQueue.findIndex((t=>t.gesture));-1!==e&&this.animQueue.splice(e,1)}ikSolve(t,e=null,i=!1,a=null){const n=new g.Vector3,s=new g.Vector3,o=new g.Vector3,r=new g.Vector3,c=new g.Quaternion,h=new g.Vector3,l=new g.Vector3,d=new g.Vector3,u=this.ikMesh.getObjectByName(t.root);u.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),u.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&i&&e.applyQuaternion(this.armature.quaternion).add(u.position);const p=this.ikMesh.getObjectByName(t.effector),m=t.links;m.forEach((t=>{t.bone=this.ikMesh.getObjectByName(t.link),t.bone.quaternion.copy(this.getPoseTemplateProp(t.link+".quaternion"))})),u.updateMatrixWorld(!0);const y=t.iterations||10;if(e)for(let v=0;v<y;v++){let t=!1;for(let i=0,a=m.length;i<a;i++){const a=m[i].bone;a.matrixWorld.decompose(r,c,h),c.invert(),s.setFromMatrixPosition(p.matrixWorld),o.subVectors(s,r),o.applyQuaternion(c),o.normalize(),n.subVectors(e,r),n.applyQuaternion(c),n.normalize();let u=n.dot(o);u>1?u=1:u<-1&&(u=-1),u=Math.acos(u),u<1e-5||(void 0!==m[i].minAngle&&u<m[i].minAngle&&(u=m[i].minAngle),void 0!==m[i].maxAngle&&u>m[i].maxAngle&&(u=m[i].maxAngle),l.crossVectors(o,n),l.normalize(),Et.setFromAxisAngle(l,u),a.quaternion.multiply(Et),a.rotation.setFromVector3(d.setFromEuler(a.rotation).clamp(new g.Vector3(void 0!==m[i].minx?m[i].minx:-1/0,void 0!==m[i].miny?m[i].miny:-1/0,void 0!==m[i].minz?m[i].minz:-1/0),new g.Vector3(void 0!==m[i].maxx?m[i].maxx:1/0,void 0!==m[i].maxy?m[i].maxy:1/0,void 0!==m[i].maxz?m[i].maxz:1/0))),a.updateMatrixWorld(!0),t=!0)}if(!t)break}a&&m.forEach((t=>{this.poseTarget.props[t.link+".quaternion"].copy(t.bone.quaternion),this.poseTarget.props[t.link+".quaternion"].t=this.animClock,this.poseTarget.props[t.link+".quaternion"].d=a}))}dispose(){this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect()),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const Nt={dance:["dance\\M_Dances_007.fbx","dance\\M_Dances_008.fbx","dance\\M_Dances_009.fbx","dance\\M_Dances_011.fbx","dance\\F_Dances_001.fbx","dance\\F_Dances_004.fbx","dance\\F_Dances_005.fbx","dance\\F_Dances_006.fbx","dance\\F_Dances_007.fbx","dance\\M_Dances_001.fbx","dance\\M_Dances_002.fbx","dance\\M_Dances_003.fbx","dance\\M_Dances_004.fbx","dance\\M_Dances_005.fbx","dance\\M_Dances_006.fbx"],expression:["expression\\M_Standing_Expressions_016.fbx","expression\\M_Standing_Expressions_017.fbx","expression\\M_Standing_Expressions_018.fbx","expression\\M_Talking_Variations_001.fbx","expression\\M_Talking_Variations_002.fbx","expression\\M_Talking_Variations_003.fbx","expression\\M_Talking_Variations_004.fbx","expression\\M_Talking_Variations_005.fbx","expression\\M_Talking_Variations_006.fbx","expression\\M_Talking_Variations_007.fbx","expression\\M_Talking_Variations_008.fbx","expression\\M_Talking_Variations_009.fbx","expression\\M_Talking_Variations_010.fbx","expression\\F_Talking_Variations_001.fbx","expression\\F_Talking_Variations_002.fbx","expression\\F_Talking_Variations_003.fbx","expression\\F_Talking_Variations_004.fbx","expression\\F_Talking_Variations_005.fbx","expression\\F_Talking_Variations_006.fbx","expression\\M_Standing_Expressions_001.fbx","expression\\M_Standing_Expressions_002.fbx","expression\\M_Standing_Expressions_004.fbx","expression\\M_Standing_Expressions_005.fbx","expression\\M_Standing_Expressions_006.fbx","expression\\M_Standing_Expressions_007.fbx","expression\\M_Standing_Expressions_008.fbx","expression\\M_Standing_Expressions_009.fbx","expression\\M_Standing_Expressions_010.fbx","expression\\M_Standing_Expressions_011.fbx","expression\\M_Standing_Expressions_012.fbx","expression\\M_Standing_Expressions_013.fbx","expression\\M_Standing_Expressions_014.fbx","expression\\M_Standing_Expressions_015.fbx"],locomotion:["locomotion\\M_CrouchedWalk_Backwards_002.fbx","locomotion\\M_Falling_Idle_002.fbx","locomotion\\M_Jog_001.fbx","locomotion\\M_Jog_003.fbx","locomotion\\M_Jog_Backwards_001.fbx","locomotion\\M_Jog_Jump_001.fbx","locomotion\\M_Jog_Jump_002.fbx","locomotion\\M_Jog_Strafe_Left_001.fbx","locomotion\\M_Jog_Strafe_Right_001.fbx","locomotion\\M_Run_001.fbx","locomotion\\M_Run_Backwards_002.fbx","locomotion\\M_Run_Jump_001.fbx","locomotion\\M_Run_Jump_002.fbx","locomotion\\M_Run_Strafe_Left_002.fbx","locomotion\\M_Run_Strafe_Right_002.fbx","locomotion\\M_Walk_001.fbx","locomotion\\M_Walk_002.fbx","locomotion\\M_Walk_Backwards_001.fbx","locomotion\\M_Walk_Jump_001.fbx","locomotion\\M_Walk_Jump_002.fbx","locomotion\\M_Walk_Jump_003.fbx","locomotion\\M_Walk_Strafe_Left_002.fbx","locomotion\\M_Walk_Strafe_Right_002.fbx","locomotion\\F_Crouch_Strafe_Left.fbx","locomotion\\F_Crouch_Strafe_Right.fbx","locomotion\\F_Crouch_Walk_001.fbx","locomotion\\F_CrouchedWalk_Backwards_001.fbx","locomotion\\F_Falling_Idle_000.fbx","locomotion\\F_Falling_Idle_001.fbx","locomotion\\F_Jog_001.fbx","locomotion\\F_Jog_Backwards_001.fbx","locomotion\\F_Jog_Jump_Small_001.fbx","locomotion\\F_Jog_Strafe_Left_002.fbx","locomotion\\F_Jog_Strafe_Right_002.fbx","locomotion\\F_Run_001.fbx","locomotion\\F_Run_Backwards_001.fbx","locomotion\\F_Run_Jump_001.fbx","locomotion\\F_Run_Strafe_Left_001.fbx","locomotion\\F_Run_Strafe_Right_001.fbx","locomotion\\F_Walk_002.fbx","locomotion\\F_Walk_003.fbx","locomotion\\F_Walk_Backwards_001.fbx","locomotion\\F_Walk_Jump_001.fbx","locomotion\\F_Walk_Jump_002.fbx","locomotion\\F_Walk_Strafe_Left_001.fbx","locomotion\\F_Walk_Strafe_Right_001.fbx","locomotion\\M_Crouch_Strafe_Left_002.fbx","locomotion\\M_Crouch_Strafe_Right_002.fbx","locomotion\\M_Crouch_Walk_003.fbx"],idle:["idle\\M_Standing_Idle_Variations_001.fbx","idle\\M_Standing_Idle_Variations_002.fbx","idle\\M_Standing_Idle_Variations_003.fbx","idle\\M_Standing_Idle_Variations_004.fbx","idle\\M_Standing_Idle_Variations_005.fbx","idle\\M_Standing_Idle_Variations_006.fbx","idle\\M_Standing_Idle_Variations_007.fbx","idle\\M_Standing_Idle_Variations_008.fbx","idle\\M_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_Variations_010.fbx","idle\\F_Standing_Idle_001.fbx","idle\\F_Standing_Idle_Variations_001.fbx","idle\\F_Standing_Idle_Variations_002.fbx","idle\\F_Standing_Idle_Variations_003.fbx","idle\\F_Standing_Idle_Variations_004.fbx","idle\\F_Standing_Idle_Variations_005.fbx","idle\\F_Standing_Idle_Variations_006.fbx","idle\\F_Standing_Idle_Variations_007.fbx","idle\\F_Standing_Idle_Variations_008.fbx","idle\\F_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_001.fbx","idle\\M_Standing_Idle_002.fbx"]};function Ut(t){return t&&0!==t.length?t[Math.floor(Math.random()*t.length)]:null}function Vt(t,e,...i){return t.filter((t=>!!t.includes(`${e}_`)&&i.every((e=>t.includes(e)))))}const $t={maxChars:E.captions.maxCharactersPerCaption,minChars:E.captions.minCharactersPerCaption,softChars:Math.floor(.75*E.captions.maxCharactersPerCaption),pauseBreakMs:350,preferBreakAfter:/[.!?…]|—|–|;/,softBreakAfter:/,|:/};class jt{constructor(){this.currentCaptions=[],this.currentCaptionIndex=0,this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this._playAttemptActive=!1}isBoundaryTypeValid(t){return"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType}handleWordBoundaryEvent(t){if(!this.isBoundaryTypeValid(t))return;const e=t.text,i=t.audioOffset,a=t.duration;let n=this.currentCaptions[this.currentCaptions.length-1],s=null;if(n&&Number.isFinite(n._lastEndOffsetMs)&&(s=i-n._lastEndOffsetMs),!n||function(t,e,i){const a=t.text,n=a.length,s=$t.preferBreakAfter.test(a.slice(-1)),o=$t.softBreakAfter.test(a.slice(-1));return!!t.isDisplayed||null!=i&&i>=$t.pauseBreakMs&&n>=$t.minChars||(r=n)+(r?1:0)+e.length>$t.maxChars||!!(s&&n>=$t.minChars)||!!(n>=$t.softChars&&o);var r}(n,e,s)){const t={text:e,audioOffset:i,duration:a,isDisplayed:!1,_lastEndOffsetMs:i+a,get renderText(){return(t=this.text)?` ${t.trim()} `:" ";var t}};this.currentCaptions.push(t)}else n.text=(r=e,((o=n.text).length>0&&!/\s$/.test(o)&&!/^[\s.,!?;:…)]/.test(r)?o+" "+r:o+r).replace(/\s{2,}/g," ")),n.duration+=a,n._lastEndOffsetMs=i+a;var o,r;if(/^[\s.,!?;:…()\[\]{}'"—–-]$/.test(e)){const t=this.currentCaptions[this.currentCaptions.length-1];t&&(t.text=t.text.replace(/\s+([.,!?;:…)\]}])/g,"$1").replace(/([([{])\s+/g,"$1").replace(/\s{2,}/g," ").trim())}}playCaptions(t,e){this._playAttemptActive=!0;const i=async()=>{this._playAttemptActive&&(this.currentCaptions.length>0&&!this.currentCaptions[0].isDisplayed?(this._playAttemptActive=!1,this.startCaptionDisplay(t,e)):(await this.wait(100),i()))};i()}startCaptionDisplay(t,e){this.currentCaptionIndex=0,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null;const i=()=>{if(this.currentCaptionIndex>=this.currentCaptions.length)return void(this.settleTimeoutId=setTimeout((()=>{this.settleTimeoutId=null,this.currentCaptionIndex>=this.currentCaptions.length?t(!1):i()}),100));const a=this.currentCaptions[this.currentCaptionIndex];if(!a)return void t(!1);const n=Math.max(0,a.audioOffset-(performance.now()-e));this.displayTimeoutId=setTimeout((()=>{this.displayTimeoutId=null,this.currentCaptions[this.currentCaptionIndex]?(a.isDisplayed=!0,t(!0,a.text),this.durationTimeoutId=setTimeout((()=>{this.durationTimeoutId=null,this.currentCaptionIndex++,i()}),a.duration)):t(!1)}),n)};i()}clearCaptions(){this._playAttemptActive=!1,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this.currentCaptions=[],this.currentCaptionIndex=0}wait(t){return new Promise((e=>setTimeout(e,t)))}destroy(){this.clearCaptions()}}const qt=["eyeBlinkLeft","eyeLookDownLeft","eyeLookInLeft","eyeLookOutLeft","eyeLookUpLeft","eyeSquintLeft","eyeWideLeft","eyeBlinkRight","eyeLookDownRight","eyeLookInRight","eyeLookOutRight","eyeLookUpRight","eyeSquintRight","eyeWideRight","jawForward","jawLeft","jawRight","jawOpen","mouthClose","mouthFunnel","mouthPucker","mouthLeft","mouthRight","mouthSmileLeft","mouthSmileRight","mouthFrownLeft","mouthFrownRight","mouthDimpleLeft","mouthDimpleRight","mouthStretchLeft","mouthStretchRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthPressLeft","mouthPressRight","mouthLowerDownLeft","mouthLowerDownRight","mouthUpperUpLeft","mouthUpperUpRight","browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","noseSneerLeft","noseSneerRight","tongueOut","headRotateZ"],Wt=["sil","aa","aa","O","E","RR","I","U","O","O","O","I","kk","RR","nn","SS","CH","TH","FF","DD","kk","PP"];class Qt extends Q{constructor(t,e){super("talkingAvatar"),this.bus=t,this.avatarOrchestrator=e,this.talkingAvatar=null,this.isFullBody=!0,this.bodyGender="M",this.resetSpeakData(),this.prevViseme=null,this.frameDuration=1e3/E.constants.FRAME_RATE,this.currentTurnId=null,this.isStoppingSpeaking=!1,this._endedTurns=new Set,this.conversationStreamActive=!1,this._pendingEndReason=null,this._audioStartSent=!1,this._busHandlers=[],this.liveCaptions=new jt}resetSpeakData(){this.speak={audio:[],visemes:[],vtimes:[],vdurations:[],words:[],wtimes:[],wdurations:[],markers:[],mtimes:[],anim:{}},this.azureBlendShapes={frames:[],sbuffer:[],orderBuffer:{}},this.prevViseme=null}finalizeTurn(){this.handlePendingVisemes(),this.talkingAvatar.streamNotifyEnd(),this.resetSpeakData()}async init(t,e){try{this.talkingAvatar=new Ft(e,{ttsEndpoint:"/gtts/",cameraZoomEnable:!1,cameraPanEnable:!1,cameraRotateEnable:!1,cameraView:"full",avatarMood:"happy"});const i="male"===t.gender?"M":"F";this.bodyGender=i,await this.talkingAvatar.showAvatar({url:t.url,body:i}),this.addEventListeners(),this.setConnected(),this.lipsyncType=t.lipsyncType}catch(i){throw this.setFailed(),new Error("Error initializing TalkingAvatar: "+i)}}isRenderingActive(){return!!this.talkingAvatar?.isRunning}async suspendRendering(t="hidden"){if(this.isRenderingActive()){try{this.talkingAvatar?.streamInterrupt?.()}catch(e){}try{this.audioReader?.cancel()}catch(e){}try{this.lipsyncReader?.cancel()}catch(e){}if(this.conversationStreamActive)try{await this.stopConversationStream()}catch(e){}try{this.talkingAvatar?.stop?.()}catch(e){}try{this.liveCaptions?.clearCaptions?.()}catch(e){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}try{const e=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:e,reason:t})}catch(e){}}}async resumeRendering(){if(!this.isRenderingActive()){try{this.talkingAvatar?.start?.()}catch(t){}try{const t=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:t,reason:"resume"})}catch(t){}}}getSpeechAnalyzerNode(){return this.talkingAvatar?.audioAnalyzerNode??null}startStreamPump(t){try{this.audioReader=t.readable.getReader()}catch(i){return}const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.audioReader.read();if(a)return;if(this.currentTurnId!==e){try{this.audioReader.cancel()}catch(t){}return}this._notifyAudioStart(e),this.handleSpeechSynthesizingChunk({audio:i})}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}startLipsyncPump(t){this.lipsyncReader=t.readable.getReader();const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.lipsyncReader.read();if(a)break;if(this.currentTurnId!==e){try{this.lipsyncReader.cancel()}catch(t){}break}switch(i.type){case"viseme":this.handleAddVisemeToStreaming(i);break;case"word":this.handleReceivedWordBoundaryEvent(i);break;case"blend":this.handleAddBlendShapestoStreaming(i)}}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}handleAudioEndOnce(t,e){const i=t??"__null__";this._endedTurns.has(i)||(this._endedTurns.add(i),this.avatarOrchestrator.sendEvent("AUDIO_END",{turnId:t,reason:e}))}async startConversationStream(){if(this.isRenderingActive()&&!this.conversationStreamActive)try{await this.talkingAvatar.streamStart({lipsyncType:this.lipsyncType,sampleRate:24e3},(({turnId:t,audioStartTime:e}={})=>{const i=t??this.currentTurnId;this._notifyAudioStart(i,e)}),(()=>{const t=this._pendingEndReason||"completed";this._pendingEndReason=null,this.handleAudioEndOnce(this.currentTurnId,t),this.currentTurnId&&(this.currentTurnId=null)})),this.conversationStreamActive=!0}catch(t){throw this.conversationStreamActive=!1,t}}async stopConversationStream(){if(this.conversationStreamActive)try{this.talkingAvatar.streamStop(),this.conversationStreamActive=!1}catch(t){this.conversationStreamActive=!1}}addEventListeners(){const t=(t,e)=>{this.bus.on(t,e),this._busHandlers.push([t,e])};t("event_command_Avatar_SetAvatarView",(t=>{this.setView(t.view)})),t("event_command_Avatar_SetAvatarMood",(t=>{this.talkingAvatar.setMood(t.mood)})),t("event_command_Avatar_PlayOrStopGesture",(t=>{"stop"!==t.gesture?this.talkingAvatar.playGesture(t.gesture,t.duration,t.mirror,t.ms):this.talkingAvatar.stopGesture()})),t("event_command_Avatar_PlayOrStopAnimation",(t=>{if("stop"===t.animation)return void this.talkingAvatar.stopAnimation();const e=function(t,e="M"){let i=[];switch(t){case"dance":i=Vt(Nt.dance,e,"Dances");break;case"expression_talking":i=Vt(Nt.expression,e,"Talking_Variations");break;case"expression_standing":i=Vt(Nt.expression,e,"Standing_Expressions");break;case"idle_standing":i=Vt(Nt.idle,e,"Standing_Idle");break;case"locomotion_walk":i=Vt(Nt.locomotion,e,"Walk_");break;case"locomotion_walk_backwards":i=Vt(Nt.locomotion,e,"Walk_Backwards");break;case"locomotion_walk_jump":i=Vt(Nt.locomotion,e,"Walk_Jump");break;case"locomotion_walk_strafe_left":i=Vt(Nt.locomotion,e,"Walk_Strafe_Left");break;case"locomotion_walk_strafe_right":i=Vt(Nt.locomotion,e,"Walk_Strafe_Right");break;case"locomotion_run":i=Vt(Nt.locomotion,e,"Run_");break;case"locomotion_run_backwards":i=Vt(Nt.locomotion,e,"Run_Backwards");break;case"locomotion_run_jump":i=Vt(Nt.locomotion,e,"Run_Jump");break;case"locomotion_run_strafe_left":i=Vt(Nt.locomotion,e,"Run_Strafe_Left");break;case"locomotion_run_strafe_right":i=Vt(Nt.locomotion,e,"Run_Strafe_Right");break;case"locomotion_jog":i=Vt(Nt.locomotion,e,"Jog_");break;case"locomotion_jog_backwards":i=Vt(Nt.locomotion,e,"Jog_Backwards");break;case"locomotion_jog_jump":i=Vt(Nt.locomotion,e,"Jog_Jump");break;case"locomotion_jog_strafe_left":i=Vt(Nt.locomotion,e,"Jog_Strafe_Left");break;case"locomotion_jog_strafe_right":i=Vt(Nt.locomotion,e,"Jog_Strafe_Right");break;case"locomotion_crouch_walk":i=Vt(Nt.locomotion,e,"Crouch_Walk");break;case"locomotion_crouch_strafe_left":i=Vt(Nt.locomotion,e,"Crouch_Strafe_Left");break;case"locomotion_crouch_strafe_right":i=Vt(Nt.locomotion,e,"Crouch_Strafe_Right");break;case"locomotion_crouchedwalk_backwards":i=Vt(Nt.locomotion,e,"CrouchedWalk_Backwards");break;case"locomotion_falling_idle":i=Vt(Nt.locomotion,e,"Falling_Idle");break;default:i=[]}return Ut(i)||Ut(Nt.locomotion.filter((t=>t.includes(`${e}_Walk_`))))||"locomotion\\M_Walk_001.fbx"}(t.animation,this.bodyGender);this.playAnimation(e,t.dur)})),t("event_command_Avatar_ControlAvatarLookAt",(t=>{"ahead"!==t.target?"point"!==t.target?"camera"!==t.target?"eye_contact"!==t.target||this.talkingAvatar.makeEyeContact(t.t):this.talkingAvatar.lookAtCamera(t.t):this.talkingAvatar.lookAt(t.x,t.y,t.t):this.talkingAvatar.lookAhead(t.t)})),t("event_command_UI_ClearCaptions",(()=>{try{this.liveCaptions?.clearCaptions?.()}catch(t){}}))}onResize(){this.talkingAvatar&&this.talkingAvatar.onResize()}handleSpeechSynthesizingChunk(t){switch(this.lipsyncType){case"blendshapes":this.talkingAvatar.streamAudio({audio:t.audio,anims:this.azureBlendShapes?.sbuffer.splice(0,this.azureBlendShapes?.sbuffer.length)});break;case"visemes":this.talkingAvatar.streamAudio({audio:t.audio,visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)});break;case"words":this.talkingAvatar.streamAudio({audio:t.audio,words:this.speak.words.splice(0,this.speak.words.length),wtimes:this.speak.wtimes.splice(0,this.speak.wtimes.length),wdurations:this.speak.wdurations.splice(0,this.speak.wdurations.length)})}}handleAddVisemeToStreaming(t){const e=Wt[t?.visemeId||0],i=t?.audioOffset||0;if(this.prevViseme){const t=this.prevViseme;let e=i-t.vtime;e<40&&(e=40),this.speak.visemes.push(t.viseme),this.speak.vtimes.push(t.vtime),this.speak.vdurations.push(e)}this.prevViseme={viseme:e,vtime:i}}handleAddBlendShapestoStreaming(t){const e=t?.BlendShapes;if(!e||0===e.length)return;const i=this._getBlendColumns(),a=e.length,n=Object.create(null);for(let o=0;o<i.length;o++){const[t,s]=i[o],r=new Float32Array(a);for(let i=0;i<a;i++){const a=e[i];r[i]=Array.isArray(a)||ArrayBuffer.isView(a)?a[t]??0:0}n[s]=r}const s=null!=t?.AudioOffset?Math.round(t.AudioOffset/1e4):(t?.FrameIndex||0)*this.frameDuration;this.azureBlendShapes.sbuffer.push({name:"blendshapes",delay:s,dt:this._getDtArray(a),vs:n})}handleReceivedWordBoundaryEvent(t){try{this.liveCaptions.handleWordBoundaryEvent(t)}catch(s){}const e=this.speak,i=t.text,a=t.audioOffset,n=t.duration;"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType&&e.words.length?e.words[e.words.length-1]+=i:"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType?(e.words.push(i),e.wtimes.push(a),e.wdurations.push(n)):"SpeechSynthesisBoundaryType.Sentence"===t.boundaryType&&a>500&&(e.markers.push((()=>{this.talkingAvatar.lookAtCamera(500)})),e.mtimes.push(a-500))}handlePendingVisemes(t=null){if("visemes"===this.lipsyncType&&this.prevViseme){const e=this.prevViseme;t||(t=100),this.speak.visemes.push(e.viseme),this.speak.vtimes.push(e.vtime),this.speak.vdurations.push(t),this.prevViseme=null}"visemes"===this.lipsyncType&&this.speak.visemes.length&&this.talkingAvatar.streamAudio({visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)}),"blendshapes"===this.lipsyncType&&this.azureBlendShapes.sbuffer.length&&this.talkingAvatar.streamAudio({anims:this.azureBlendShapes.sbuffer.splice(0,this.azureBlendShapes.sbuffer.length)})}async startStreaming(t,e,i){if(this.currentTurnId=i,this.isStoppingSpeaking=!1,this._audioStartSent=!1,!this.isRenderingActive()){try{t?.cancel?.()}catch(n){}try{e?.cancel?.()}catch(n){}return this.handleAudioEndOnce(i,"suppressed"),void(this.currentTurnId=null)}const a=i;this._endedTurns.delete(a??"__null__");try{this.startStreamPump(t),this.startLipsyncPump(e),this.conversationStreamActive||await this.startConversationStream()}catch(s){this.handleAudioEndOnce(a,"error"),this.currentTurnId===a&&(this.currentTurnId=null),this.isStoppingSpeaking=!1}}_notifyAudioStart(t,e=null){if(this._audioStartSent)return;this._audioStartSent=!0;const i=e??("undefined"!=typeof performance?performance.now():Date.now()),a=t??this.currentTurnId,n=a||0===a?{turnId:a,audioStartTime:i}:{audioStartTime:i},s=()=>{try{this.avatarOrchestrator?.sendEvent("AUDIO_START",n)}catch(t){}};"function"==typeof queueMicrotask?queueMicrotask(s):setTimeout(s,0)}interruptSpeaking(){if(!this.isStoppingSpeaking){this.isStoppingSpeaking=!0,this.conversationStreamActive&&this.talkingAvatar.streamInterrupt(),this.audioReader?.cancel(),this.lipsyncReader?.cancel(),this._pendingEndReason="interrupted";try{this.liveCaptions?.clearCaptions?.()}catch(t){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(t){}this.isStoppingSpeaking=!1}}setView(t){switch(t){case"full":this.talkingAvatar.setView("full");break;case"mid":this.talkingAvatar.setView("mid");break;case"upper":this.talkingAvatar.setView("upper");break;case"head":this.talkingAvatar.setView("head")}}playAnimation(t,e){const i=`https://sentifydfrontend.blob.core.windows.net/animationclips/${t}`;this.setView("full"),this.talkingAvatar.playAnimation(i,null,e)}reconnect(){}async destroy(){for(const[t,e]of this._busHandlers)try{this.bus.off(t,e)}catch{}this._busHandlers.length=0,this.isStoppingSpeaking=!1,this.conversationStreamActive&&await this.stopConversationStream(),this.talkingAvatar?.stop(),this.talkingAvatar=null}_getBlendColumns(){if(!this._blendCols){this._blendCols=[];for(let t=0;t<qt.length;t++){const e=qt[t];e&&this._blendCols.push([t,e])}}return this._blendCols}_getDtArray(t){this._dtCache||(this._dtCache=new Map);let e=this._dtCache.get(t);return e||(e=new Array(t).fill(this.frameDuration),this._dtCache.set(t,e)),e}}class Gt{constructor(t){if(!t)throw new Error("Cannot initialize SpeakingAvatar due to missing bus instance");this.voiceBot=null,this.chatSocket=null,this.bus=t,this.avatarOrchestrator=new pt(t),this.avatarOrchestrator.start(),this.connectionManager=this.createConnectionManager(this.bus,this.avatarOrchestrator),this.sessionData=lt.getInstance(),this.auth=new ct,this.connectionManager.registerConnectionModule(this.auth),this.voiceBargeInDetector=null}createConnectionManager(t,e){if(!t||!e)throw new Error("Missing dependencies for ConnectionManager creation.");return new mt(t,e)}async init(t){if(!t?.avatarContainer||!t.avatarAPIKey&&!t.tokenEndpoint||!t.avatarId||!t.targetApp)return!1;try{await this.initializeAuthentication(t);const{avatarParameters:e,avatarItem:i}=await this.setupAvatarData();return!(!e||!i||(this.avatarModule=new Qt(this.bus,this.avatarOrchestrator),await this.sessionData.init(e,i),await Promise.all([this.initializeChatSocket(),this.initializeVoiceBot(),this.initializeAvatarScene(i,t.avatarContainer)]),this.avatarOrchestrator.injectModules({talkingAvatar:this.avatarModule,chatSocket:this.chatSocket,voiceBot:this.voiceBot,conversation:this.sessionData.conversation}),await this.initializeVoiceBargeInDetector(),await this.connectionManager.waitUntilReady(),this.avatarOrchestrator.sendEvent("READY","SpeakingAAvatar.init"),0))}catch(e){return!1}}async initializeAuthentication(t){if(!(await this.auth.init(t.targetApp,t.avatarAPIKey||"",t.tokenEndpoint||"",t.avatarId)))throw new Error("Authentication initialization failed.")}async setupAvatarData(){const t=await this.auth.getAvatarParameters();if(!t)throw new Error("Failed to retrieve avatar parameters from authentication");return{avatarParameters:t,avatarItem:this.constructAvatarItem(t)}}constructAvatarItem(t){let e=t.avatarUrl;"ReadyPlayerMe"===t.avatarSource&&(e+="?morphTargets=ARKit,Oculus+Visemes,mouthOpen,mouthSmile,eyesClosed,eyesLookUp,eyesLookDown&textureSizeLimit=1024&textureFormat=png");let i=t.lipsyncType||"visemes";return{id:t.avatarSourceId,type:E?.avatar?.type,url:e,source:t.avatarSource,bodyType:t.bodyType,gender:t.gender,lipsyncType:i}}async initializeChatSocket(){try{X.resetInstance?.()}catch{}this.chatSocket=X.getInstance(this.bus,this.auth,this.sessionData,this.avatarOrchestrator),this.connectionManager.registerConnectionModule(this.chatSocket),await this.chatSocket.init()}async initializeVoiceBot(){this.voiceBot=await K.build(this.bus,this.avatarOrchestrator,this.auth,this.sessionData),this.connectionManager.registerConnectionModule(this.voiceBot.speechService)}async initializeVoiceBargeInDetector(){if(!this.voiceBargeInDetector&&!1!==E?.speech?.bargeIn?.enabled)try{this.voiceBargeInDetector=new et({talkingAvatar:this.avatarModule,avatarOrchestrator:this.avatarOrchestrator,config:E?.speech?.bargeIn}),await this.voiceBargeInDetector.init()}catch(t){this.voiceBargeInDetector=null}}async setBargeInEnabled(t){if(E?.speech?.bargeIn&&(E.speech.bargeIn.enabled=t),t)this.voiceBargeInDetector||this.avatarModule&&this.avatarOrchestrator&&await this.initializeVoiceBargeInDetector();else if(this.voiceBargeInDetector){try{this.voiceBargeInDetector.destroy()}catch(e){}this.voiceBargeInDetector=null}}async initializeAvatarScene(t,e){try{if(!this.avatarModule)throw new Error("Avatar module not initialized.");this.connectionManager.registerConnectionModule(this.avatarModule),await this.avatarModule.init(t,e)}catch(i){throw i}}destroy(){try{X.resetInstance?.()}catch{}this.voiceBot?.destroy?.(),this.voiceBargeInDetector?.destroy?.(),this.voiceBargeInDetector=null,this.avatarModule?.destroy?.(),this.connectionManager?.destroy?.(),this.sessionData?.destroy?.(),this.auth?.destroy?.(),this.avatarOrchestrator?.destroy?.()}}class Yt extends EventTarget{constructor(){super(),this._listeners=new Map,this._disposers=new Set,this._isDisposed=!1,this._globalListeners=new Set}on(t,e){if(this._isDisposed)return()=>{};if("*"===t)return this.onAll(e);const i=t=>{try{const i=t.detail;e(i)}catch(i){}};this._listeners.has(t)||this._listeners.set(t,new Map),this._listeners.get(t).set(e,i),this.addEventListener(t,i);const a=()=>{this._isDisposed||(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e),this._disposers.delete(a))};return this._disposers.add(a),a}off(t,e){if("*"===t)return this.offAll(e);const i=this._listeners.get(t)?.get(e);i&&(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e))}emit(t,e=void 0){if(this._isDisposed)return;const i=new CustomEvent(t,{detail:e,bubbles:!1,cancelable:!1});this.dispatchEvent(i),this._globalListeners.forEach((i=>{try{i(t,e)}catch(a){}}))}onAll(t){if(this._isDisposed)return()=>{};this._globalListeners.add(t);const e=()=>{this._isDisposed||(this._globalListeners.delete(t),this._disposers.delete(e))};return this._disposers.add(e),e}offAll(t){this._globalListeners.delete(t)}clear(){this._listeners.forEach(((t,e)=>{t.forEach(((t,i)=>{this.removeEventListener(e,t)}))})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear()}dispose(){this._isDisposed||(this._disposers.forEach((t=>{try{t()}catch(e){}})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear(),this._isDisposed=!0)}get disposerCount(){return this._disposers.size}get isDisposed(){return this._isDisposed}get listenerCount(){let t=this._globalListeners.size;return this._listeners.forEach((e=>{t+=e.size})),t}}class Xt{constructor(t,e){this.bus=t,this.dismissableContainer=e,this.dismissableAlerts=new Map,this.bus.on("event_command_Alerts_ShowDismissableAlert",(t=>{const e=t?.errorMessage||"An error occurred",i=t?.className||"alert-danger";this.showDismissableAlert(e,i)}))}showDismissableAlert(t,e){if(this.dismissableAlerts.has(t))return;if(this.dismissableAlerts.size>=E.alerts.maxAlerts){const t=this.dismissableAlerts.keys().next().value,e=this.dismissableAlerts.get(t);e&&(e.hideToast(),this.dismissableAlerts.delete(t))}const i=C({text:t,duration:E.alerts.dismissableAlertDuration,close:!0,gravity:"top",position:"left",stopOnFocus:!0,className:`alert ${e}`,selector:this.dismissableContainer,callback:()=>{this.dismissableAlerts.delete(t)}});i.showToast(),this.dismissableAlerts.set(t,i)}}const Zt=t=>/[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(t);class Jt{#o=null;#r="wakeLock"in navigator;get isActive(){return!!this.#o}get isSupported(){return this.#r}async request(){const t="undefined"!=typeof process&&process.env&&"test"===process.env.NODE_ENV,e="undefined"!=typeof document&&"visible"===document.visibilityState;if(this.#r&&!this.isActive&&!t&&e)try{this.#o=await navigator.wakeLock.request("screen"),this.#o.addEventListener("release",(()=>{this.#o=null}))}catch(i){}}async release(){try{await(this.#o?.release())}finally{this.#o=null,this.#r}}}const Kt=k`
1
+ import{io as t}from"socket.io-client";import{AudioConfig as e,SpeechRecognizer as i,ResultReason as a,CancellationReason as n,CancellationErrorCode as s,SpeechConfig as o,PropertyId as r,AutoDetectSourceLanguageConfig as c}from"microsoft-cognitiveservices-speech-sdk";import"js-cookie";import{jwtDecode as h}from"jwt-decode";import{v4 as l}from"uuid";import{createMachine as d,assign as u,fromPromise as p,createActor as m}from"xstate";import*as g from"three";import{OrbitControls as y}from"three/addons/controls/OrbitControls.js";import{GLTFLoader as v}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as f}from"three/addons/loaders/DRACOLoader.js";import{FBXLoader as b}from"three/addons/loaders/FBXLoader.js";import{RoomEnvironment as _}from"three/addons/environments/RoomEnvironment.js";import x from"three/addons/libs/stats.module.js";import{html as k,nothing as S,css as w,LitElement as A}from"lit";import C from"toastify-js";import{styleMap as R}from"lit/directives/style-map.js";const T=t=>new Promise((e=>setTimeout(e,t))),L=t=>t?t.replace(/<prosody[^>]*>([\s\S]*?)<\/prosody>/gi,"$1").replace(/#\*[\s\S]*?\*#/g,""):t,z=t=>(t instanceof Date?t:new Date(t)).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});function I(){return"undefined"!=typeof window&&window.VITE_APP_SOCKET_URL?window.VITE_APP_SOCKET_URL:"https://sentifyd-serve.agreeablestone-0bc8c055.swedencentral.azurecontainerapps.io"}const M=I(),E={auth:{tokenRefreshInterval:6e5,speechTokenInterval:42e4,maxLoginRetries:3,loginRetryDelay:5e3,closeToExpirationLimit:6e4,speechTokenRetries:5,serverBaseURL:I()},avatar:{type:"gltf"},constants:{HEADROLL_BLENDSHAPE_INDEX:52,LEFTEYE_BLENDSHAPE_INDEX:53,RIGHTEYE_BLENDSHAPE_INDEX:54,FRAME_RATE:60},dom:{avatarDivId:"#avatar-container",toastifyDivId:"#toastify-container",canvasWidth:400,canvasHeight:500,headerAndFooterHeight:166,controlsHeight:90,smallDisplayWidth:768,smallScreenSafetyPadding:24},renderer:{alpha:!0,antialias:!0},speech:{authorizationEndPoint:"/api/v1/chatbot/get-speech-token",maxDurationTimeout:6e5,vad:{segmentationSilenceMs:1700,initialSilenceMs:12e3,semantic:!0},bargeIn:{enabled:!0,debug:!1}},captions:{wordsPerMinute:140,maxCharactersPerCaption:40,minCharactersPerCaption:15,captionChangeDelay:200,captionTimeout:1500},alerts:{maxAlerts:3,dismissableAlertDuration:4500},chatbot:{streaming:!1,thinkingTimeout:15e3,speakingTimeout:24e4},test:{stateTestMode:!1,enableDiagnostics:!1},connection:{reconnectInitialDelay:2e3,reconnectMaxDelay:3e4,reconnectFactor:1.6}},P=async(t,e)=>{for(const i of t){const{name:t}=i;switch(t){case"RequestUserData":await D(e);break;case"EndConversation":await H(e);break;case"DisableCaptions":await O(e);break;case"EnableCaptions":await F(e);break;case"SwitchToChatMode":await B(e);break;case"SwitchToAvatarMode":await N(e);break;case"SetAvatarView":await U(e,i.view);break;case"SetAvatarMood":await V(e,i.mood);break;case"PlayOrStopAvatarGesture":await $(e,i.gesture,i.dur||3,i.mirror||!1,i.ms||1e3);break;case"PlayOrStopAvatarAnimation":await j(e,i.animation,i.dur||3);break;case"ControlAvatarLookAt":await q(e,i.target,i.t||1e3,i.x||0,i.y||0)}}},D=async t=>{t.emit("event_command_UI_RequestUserData")},H=async t=>{t.emit("event_command_UI_EndConversation")},O=async t=>{t.emit("event_command_UI_DisableCaptions")},F=async t=>{t.emit("event_command_UI_EnableCaptions")},B=async t=>{t.emit("event_command_UI_SwitchToChatMode")},N=async t=>{t.emit("event_command_UI_SwitchToAvatarMode")},U=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarView",{view:e})},V=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarMood",{mood:e})},$=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_PlayOrStopGesture",{gesture:e,duration:i,mirror:a,ms:n})},j=async(t,e,i)=>{t.emit("event_command_Avatar_PlayOrStopAnimation",{animation:e,dur:i})},q=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_ControlAvatarLookAt",{target:e,t:i,x:a,y:n})};class W{constructor(t,e=null){this.validateDependencies({auth:t}),this.socketUrl=M,this.auth=t,this.socket=null,this.isAuthenticating=!1,this.onConnectionStatusChange=e}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize WebSocketManager due to missing dependencies: ${e.join(", ")}`)}async connect(){this.socket?.connected&&this.disconnect();const e=this.auth.getAccessToken();return new Promise(((i,a)=>{this.socket=t(this.socketUrl,{auth:{token:`Bearer ${e}`},path:"/socket.io",reconnection:!0,reconnectionAttempts:5,reconnectionDelay:500,reconnectionDelayMax:1e4}),this.registerWebsocketEventHandlers(i,a)}))}isSocketConnected(){return this.socket?.connected}isInitialised(){return null!==this.socket}disconnect(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null)}registerWebsocketEventHandlers(t,e){this.socket.removeAllListeners(),this.socket.io.on("error",(t=>{})),this.socket.io.on("reconnect",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("connected")})),this.socket.io.on("reconnect_attempt",(t=>{})),this.socket.io.on("reconnect_error",(t=>{})),this.socket.io.on("reconnect_failed",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("failed"),this.socket=null,e(new Error("Websocket connection failed after maximum retries."))})),this.socket.on("connect",(()=>{this.socket.io.engine,this.onConnectionStatusChange&&this.onConnectionStatusChange("connected"),t()})),this.socket.on("connect_error",(t=>{t.message.includes("Token expired")||t.message.includes("Invalid token")?this.reAuthenticate():(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),e?.(t))})),this.socket.on("disconnect",(t=>{this.socket&&this.socket.active||this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")})),this.socket.onAny(((t,...e)=>{}))}reAuthenticate(){this.isAuthenticating||(this.isAuthenticating=!0,this.auth.authenticate().then((()=>{this.connect(),this.isAuthenticating=!1})).catch((t=>{this.isAuthenticating=!1,this.onConnectionStatusChange("failed")})))}on(t,e){this.socket&&this.socket.on(t,e)}off(t,e){this.socket&&(e?this.socket.off(t,e):this.socket.off(t))}emit(t,e,i){this.isSocketConnected()?i?this.socket.emit(t,e,i):this.socket.emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}async emitWithResponse(t,e){return new Promise(((i,a)=>{this.isSocketConnected()?this.socket.emit(t,e,(t=>{i(t)})):(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),a(new Error("Socket not connected")))}))}timeoutEmit(t,e,i,a){this.isSocketConnected()?a?this.socket.timeout(i).emit(t,e,a):this.socket.timeout(i).emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}destroy(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null),this.isAuthenticating=!1,this.onConnectionStatusChange=null}}class G{constructor(t){if(!t||"string"!=typeof t)throw new Error("ConnectionModule requires a valid name");this.name=t,this.connectionState="disconnected",this.subscribers=[]}isConnecting(){return"connecting"===this.connectionState}isDisconnected(){return"disconnected"===this.connectionState}isReconnecting(){return"reconnecting"===this.connectionState}isConnected(){return"connected"===this.connectionState}isFailed(){return"failed"===this.connectionState}setConnected(){this.updateConnectionState("connected")}setDisconnected(){this.updateConnectionState("disconnected")}setConnecting(){this.updateConnectionState("connecting")}setReconnecting(){this.updateConnectionState("reconnecting")}setFailed(){this.updateConnectionState("failed")}updateConnectionState(t){return!!["connected","connecting","reconnecting","disconnected","failed"].includes(t)&&this.connectionState!==t&&(this.connectionState,this.connectionState=t,this.notifySubscribers(),!0)}reconnect(){}subscribe(t){return"function"==typeof t&&!this.subscribers.includes(t)&&(this.subscribers.push(t),!0)}unsubscribe(t){if("function"!=typeof t)return!1;const e=this.subscribers.length;return this.subscribers=this.subscribers.filter((e=>e!==t)),this.subscribers.length<e}notifySubscribers(){0!==this.subscribers.length&&[...this.subscribers].forEach(((t,e)=>{try{t(this.connectionState,this.name)}catch(i){}}))}destroy(){try{this.subscribers=[],this.connectionState="disconnected"}catch(t){}}getStateInfo(){return{name:this.name,state:this.connectionState,subscriberCount:this.subscribers.length}}}class Q{constructor(t,e,i){this.id=t,this.state="CREATED",this.abortController=new AbortController,this.audio=(t=>{let e,i=!1;return{readable:new ReadableStream({start(a){e=a,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}i=!0}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this.lipsync=(t=>{let e,i=!1;return{readable:new ReadableStream({start(i){e=i,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this._watchdog=setTimeout((()=>{this._watchdog=null,i?.(this)}),e)}activate(){this.state="ACTIVE"}finish(){if("FINISHED"!==this.state){this.state="FINISHED",clearTimeout(this._watchdog);try{this.audio.close()}catch{}try{this.lipsync.close()}catch{}this.abortController.abort("turn finished")}}abort(){"FINISHED"!==this.state&&(this.state="STOPPING",this.abortController.abort("turn interrupted"),clearTimeout(this._watchdog))}get isActive(){return"ACTIVE"===this.state}get done(){return"FINISHED"===this.state}}const Y=12e4;class X extends G{static _instance=null;constructor(t,e,i,a){if(X._instance)return X._instance;super("chatSocket"),this.validateDependencies({bus:t,auth:e,sessionData:i,avatarOrchestrator:a}),this.socketManager=new W(e,(t=>this.updateConnectionState(t))),this.isChatbotShown=!0,this.chatbotMode="AVATAR",this.bus=t,this.sessionData=i,this.auth=e,this.avatarOrchestrator=a,this.pendingDelayedActions=null,this.turn=null,this.INTERRUPT_WATCHDOG=15e3,X._instance=this}static getInstance(t,e,i,a){return X._instance||(X._instance=new X(t,e,i,a)),X._instance}_isDataForCurrentTurn(){return!!this.turn&&!this.turn.done&&this.turn.id===this.sessionData.conversation.currentTurnId}static resetInstance(){X._instance&&(X._instance._cleanup(),X._instance=null)}_cleanup(){this.cleanupActiveStreams(),this.removeTTSEventHandlers(),this.socketManager?.disconnect(),this.pendingDelayedActions=null,this.turn=null,this.audioStream=null,this.lipsyncStream=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize ChatSocket due to missing dependencies: ${e.join(", ")}`)}async init(){if(!this.sessionData||!this.sessionData.avatarName||!this.sessionData.language)throw new Error("Missing required session data for chat connection.");this.sessionData.trainingId;try{this.setConnecting(),await this.socketManager.connect()}catch(t){this.setDisconnected()}this.registerTTSEventHandlers()}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting();try{if(await this.socketManager.connect(),!this.socketManager.isSocketConnected())throw new Error("Socket still not connected after connect()");this.registerTTSEventHandlers(),this.setConnected()}catch(t){this.setFailed()}}}removeTTSEventHandlers(){this.socketManager&&["conversation_ai_reply","tts_stream_start","tts_viseme","tts_word","tts_blend","tts_error","tts_chunk","tts_stream_end"].forEach((t=>{this.socketManager.off(t)}))}registerTTSEventHandlers(){this.removeTTSEventHandlers(),this.socketManager.on("conversation_ai_reply",(t=>this.handleConversationResponse(t))),this.socketManager.on("tts_stream_start",(t=>{t?.turnId,this.turn&&this.turn.id===this.sessionData.conversation.currentTurnId||this.prepareStreamsForTurn(this.sessionData.conversation.currentTurnId),this.turn.activate(),this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("STREAM_START",{audioStream:this.audioStream,lipsyncStream:this.lipsyncStream,turnId:this.turn.id})})),this.socketManager.on("tts_viseme",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed&&this.turn&&this.turn.isActive)try{this.lipsyncStream.push({type:"viseme",...t})}catch(e){if(e.message?.includes("closed readable stream"))return}})),this.socketManager.on("tts_word",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"word",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_blend",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"blend",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_error",(t=>{this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("TTS_ERROR",{error:t})})),this.socketManager.on("tts_chunk",(t=>{if(this._isDataForCurrentTurn()&&this.audioStream&&!this.audioStream.isClosed){if(!this.turn||!this.turn.isActive||!this.audioStream)return;try{this.audioStream.push(t)}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_stream_end",(t=>{const e=t?.turnId;t?.reason,this.turn&&e===this.turn.id&&(this.turn.finish(),this.avatarOrchestrator.sendEvent("STREAM_END"),this.turn=null)}))}async handleConversationResponse(t){if(this.sessionData?.conversation?.conversationId)if("success"===t?.status)t?.error,await this.processAIResponse(t);else if("error"===t?.status){const e={...t.error};t.conversationId&&!e.conversationId&&(e.conversationId=t.conversationId),this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:e,chatbotMode:this.chatbotMode})}else this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"No response from server. Please try again."},chatbotMode:this.chatbotMode})}async sendInitConversationEvent(){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((t,e)=>{this.socketManager.timeoutEmit("init_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,streaming:!1},Y,((i,a)=>{i||"success"!==a?.status?e(new Error(i||a?.error?.message||"Conversation init failed")):t({initialized:!0})}))}))}async sendStartConversationEvent(t=!1){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((e,i)=>{this.socketManager.timeoutEmit("start_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,turnId:this.sessionData.conversation.currentTurnId,streaming:!1,isTermsAccepted:!0===this.sessionData.isTermsAccepted,isResume:t},Y,(async(t,a)=>{if(t||"success"!==a?.status){const e=a?.error?.code,n=t||a?.error?.message||"Conversation start failed";i(new Error(e?`${e}: ${n}`:n))}else try{await this.processAIResponse(a),e(a)}catch(n){i(n)}}))}))}sendEndConversationEvent(t,e){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("end_conversation",{conversationId:t,satisfactionScore:e,chatbotMode:this.chatbotMode},(e=>{"success"===e?.status?this.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t}):e?.status}))}prepareStreamsForTurn(t){this.turn&&!this.turn.done&&this.turn.abort(),this.turn=new Q(t,this.INTERRUPT_WATCHDOG,(t=>{this.socketManager.emit("interrupt_tts",{turnId:t.id})})),this.audioStream=this.turn.audio,this.lipsyncStream=this.turn.lipsync}async processAIResponse(t){try{const e=t?.data?.actions||[],i=e.filter((t=>!1!==t.immediate)),a=e.filter((t=>!1===t.immediate));if(i.length>0&&await P(i,this.bus),a.length>0&&(this.pendingDelayedActions=a),"resume_silent"===t.data?.dataType)return;if("message"===t.data?.dataType?await this.receiveMessage(t.data,t.timestamp):"avatar_structured_response"===t.data?.dataType?await this.receiveAvatarStructuredResponse(t.data,t.timestamp):t?.data?.messageContent&&await this.receiveMessage(t.data,t.timestamp),"CHAT"===this.chatbotMode&&this.pendingDelayedActions&&this.pendingDelayedActions.length>0)try{await P(this.pendingDelayedActions,this.bus)}finally{this.pendingDelayedActions=null}}catch(e){this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"Error getting a response. Please try again."},chatbotMode:this.chatbotMode})}}async receiveAvatarStructuredResponse(t,e){if(!t?.structuredResponse)throw new Error("Avatar response is invalid");const i=z(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,structuredResponse:t.structuredResponse,chatbotMode:this.chatbotMode})}async receiveMessage(t,e){if(!t?.messageContent)throw new Error("Message is invalid");const i=z(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,chatbotMode:this.chatbotMode})}async sendMessage(t,e="CHAT"){if(this.pendingDelayedActions=null,!this.sessionData.trainingId||!t?.messageText)return{success:!1,error:"Missing required field(s)"};if(!this.sessionData.conversation.conversationId)return{success:!1,error:"No conversation found. Start a conversation first."};try{const i=this.sessionData.conversation.incrementTurnId();"AVATAR"===e?this.prepareStreamsForTurn(i):this.turn&&(this.turn.abort(),this.turn=null),this.socketManager.emit("user_chat_message",{trainingId:this.sessionData.trainingId,avatarId:this.sessionData.avatarId,userName:this.sessionData.username,conversationId:this.sessionData.conversation.conversationId,turnId:i,message:t.messageText,messageDuration:t?.messageDuration||0,chatbotMode:e,detectedLanguage:t?.detectedLanguage||this.sessionData.language,voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,streaming:E.chatbot.streaming||!1});const a=z(new Date);return this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:t.messageText,time:a,chatbotMode:e}),this.sessionData.conversation.lastDetectedLanguage=t?.detectedLanguage,{success:!0}}catch(i){return{success:!1,error:i.message||"An error occurred while sending the message"}}}sendUserData(){const t=this.sessionData.conversation.incrementTurnId();if(this.prepareStreamsForTurn(t),this.avatarOrchestrator){const t=this.avatarOrchestrator.getSnapshot(),e=t?.matches("lifecycle.conversation.inProgress.thinking");e||this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:"[User data update]",time:z(new Date),chatbotMode:this.chatbotMode})}if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("update_user_data",{conversationId:this.sessionData.conversation.conversationId,turnId:t,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",chatbotMode:this.chatbotMode,lipsyncType:this.sessionData.lipsyncType,userData:{username:this.sessionData.username,phoneNumber:this.sessionData.phoneNumber,email:this.sessionData.email,isTermsAccepted:this.sessionData.isTermsAccepted}},(async t=>{"success"===t?.status?this.processAIResponse(t):t?.status}))}cleanupActiveStreams(){this.turn&&this.turn.abort()}async interruptCurrentTurn(){if(!this.turn)return{status:"warning",message:"No active turn"};try{return this.turn.abort(),await this.socketManager.emitWithResponse("interrupt_tts",{turnId:this.turn.id,chatbotMode:this.chatbotMode})}catch(t){return{status:"error",message:"Interruption failed"}}}destroy(){this.socketManager?.destroy()}}class Z{constructor({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n,autoDetectLanguage:s}={}){this.validateDependencies({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n}),this.bus=a,this.avatarOrchestrator=n,this.speechConfig=e,this.recognizer=t,this.audioConfig=i,this.messageText="",this.messageDuration=0,this.detectedLanguage="",this.isMessageSent=!1,this.isListening=!1,this.isMicDetected=!0,this.autoDetectLanguage=s,this.languageDurations={},this._isStopping=!1,this.maxDurationTimeoutId=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize SpeechRecognition due to missing dependencies: ${e.join(", ")}`)}static async build(t,e,i,a){if(!t)throw new Error("speechConfig is required");const{recognizer:n,audioConfig:s}=await this.init(t,e),o=new Z({recognizer:n,speechConfig:t,audioConfig:s,bus:i,avatarOrchestrator:a,autoDetectLanguage:!!e});return o._registerRecognizerEvents(),o}static async init(t,a){try{const n=e.fromDefaultMicrophoneInput();let s=null;return s=a?i.FromConfig(t,a,n):new i(t,n),{recognizer:s,audioConfig:n}}catch(n){throw new Error("Error in SpeechRecognition initialization: "+n)}}static async checkMicrophoneAccess(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Media devices not supported");if(0===(await navigator.mediaDevices.enumerateDevices()).filter((t=>"audioinput"===t.kind)).length)throw new Error("No microphone devices found");return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach((t=>t.stop())),!0}catch(t){throw new Error(`Microphone access issue: ${t.message}`)}}start(){try{this._isStopping=!1,clearTimeout(this.maxDurationTimeoutId),this.messageText="",this.messageDuration=0,this.isMessageSent=!1,this.autoDetectLanguage&&(this.languageDurations={}),this.recognizeNewMessage(),this._setMaxDurationTimeout()}catch(t){this.stop()}}stop(){if(!this._isStopping){this._isStopping=!0;try{this.recognizer&&this.recognizer.stopContinuousRecognitionAsync()}catch(t){}finally{this.isListening=!1,this._isStopping=!1}clearTimeout(this.maxDurationTimeoutId)}}sendMessage(){if(!this.isMessageSent&&this.messageText&&this.messageText.trim())try{this.autoDetectLanguage?this.detectedLanguage=this._determineMainLanguage():this.detectedLanguage=this.speechConfig.speechRecognitionLanguage,this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:this.messageDuration,detectedLanguage:this.detectedLanguage}),this.isMessageSent=!0}catch(t){}}simulateRecognition(){this.avatarOrchestrator.transitionToListening(),this.messageText="Hello, how are you doing today?",this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:3e3,detectedLanguage:"en-US"})}recognizeNewMessage(){try{this._startRecognizer()}catch(t){this._emitAlert("alertMicrophoneStartFailed"),this.stop()}}_startRecognizer(){this.recognizer.startContinuousRecognitionAsync((()=>{this.avatarOrchestrator.is("listening"),this.isListening=!0}),(async t=>{await this._handleRecognitionStartupError(t),this.isMicDetected=!1,this.stop()}))}async _handleRecognitionStartupError(t){let e="alertMicrophoneCheckSettings";try{await Z.checkMicrophoneAccess(),e="alertSpeechRecognitionSetupFailed"}catch(i){e=this._isBrowserPermissionError(i)?"alertMicrophoneAccessDenied":this._isBrowserDeviceError(i)?"alertNoMicrophoneDetected":"alertMicrophoneError"}this._emitAlert(e)}_isBrowserPermissionError(t){if(t&&"object"==typeof t)return"NotAllowedError"===t.name||"PermissionDeniedError"===t.name||"SecurityError"===t.name;const e=t.toString().toLowerCase();return e.includes("permission")||e.includes("notallowed")||e.includes("denied")}_isBrowserDeviceError(t){if(t&&"object"==typeof t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name;const e=t.toString().toLowerCase();return e.includes("notfound")||e.includes("device")||e.includes("microphone not found")}close(){this.stop(),this.recognizer&&(this.recognizer.close(),this.recognizer.dispose(!0),this.recognizer=void 0)}_registerRecognizerEvents(){this.recognizer.recognized=(t,e)=>{if(!this._isStopping&&this.isListening&&!this.isMessageSent&&e.result.reason===a.RecognizedSpeech&&""!==e.result.text){if(this.messageText=(this.messageText?this.messageText+" ":"")+e.result.text,this.messageDuration+=e.result.duration,this.autoDetectLanguage){const t=e.result.language,i=e.result.duration;this.languageDurations[t]?this.languageDurations[t]+=i:this.languageDurations[t]=i}this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText}),this._completeRecognitionTurn()}},this.recognizer.recognizing=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||""!==e.result.text&&this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText+" "+e.result.text})},this.recognizer.speechStartDetected=(t,e)=>{},this.recognizer.speechEndDetected=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||this.messageText?.trim()&&this._completeRecognitionTurn()},this.recognizer.canceled=(t,e)=>{e.reason===n.Error&&this._handleAzureSpeechError(e),this.stop()}}_handleAzureSpeechError(t){const e=t.errorCode,i=t.errorDetails||"No additional details available";let a="",n=!1;switch(e){case s.NoError:a="alertSomeErrorOccurred";break;case s.AuthenticationFailure:a="alertVoiceServicesUnavailable",n=!0;break;case s.BadRequestParameters:a="alertServiceTemporarilyUnavailable";break;case s.TooManyRequests:a="alertTooManyRequests";break;case s.ConnectionFailure:a="alertConnectionIssue";break;case s.ServiceTimeout:a="alertResponseTimeout";break;case s.ServiceError:a="alertServiceTemporarilyUnavailable";break;case s.RuntimeError:a="alertSomeErrorOccurred";break;case s.Forbidden:a="alertServiceBusy";break;default:a="alertSomeErrorOccurred"}n&&this.bus.emit("event_error_VoiceBot_ExpiredOrInvalidToken",i),this.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:a})}_emitAlert(t,e={}){if("string"!=typeof t||!this.bus)return;if(["alertMicrophoneStartFailed","alertMicrophoneCheckSettings","alertMicrophoneAccessDenied","alertNoMicrophoneDetected","alertMicrophoneError"].includes(t)&&this._isChatModeActive())return;const i={messageKey:t,...e};this.bus.emit("event_command_Alerts_ShowDismissableAlert",i)}_isChatModeActive(){try{const t=this.avatarOrchestrator?.getSnapshot?.(),e=t?.context?.chatSocket?.chatbotMode;return"CHAT"===e}catch(t){return!1}}_setMaxDurationTimeout(){this.maxDurationTimeoutId=setTimeout((()=>{this._completeRecognitionTurn()}),E.speech.maxDurationTimeout)}_completeRecognitionTurn(){this._isStopping||this.stop(),this.sendMessage()}_determineMainLanguage(){let t=null,e=0;for(const[i,a]of Object.entries(this.languageDurations))a>e&&(e=a,t=i);return t}destroy(){try{this.close()}catch(t){}}}class K extends G{constructor(t,e){super("speech-token"),this.auth=t,this.refreshTokenCallback=e,this.tokenRefreshLoop=null}async requestAuthorizationToken(t=E.auth.speechTokenRetries){for(let i=1;i<=t;i++)try{const t=await this.fetchSpeechToken();return this.setConnected(),t}catch(e){if(i===t)throw this.setFailed(),new Error(`Failed to fetch speech token after ${t} attempts`)}}async fetchSpeechToken(){try{const t=await this.auth.callSentifydApi(E.speech.authorizationEndPoint,"POST"),{token:e}=t.data;if(!e)throw new Error("Invalid token structure received from API.");return t.data}catch(t){throw new Error("Failed to fetch data from API.")}}async startTokenRefreshLoop(){await this.stopTokenRefreshLoop(),this.tokenRefreshLoop=setInterval((async()=>{try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),this.setConnected()}catch(t){this.setDisconnected()}}),E.auth.speechTokenInterval)}async stopTokenRefreshLoop(){this.tokenRefreshLoop&&(clearInterval(this.tokenRefreshLoop),this.tokenRefreshLoop=null)}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting(),await this.stopTokenRefreshLoop();try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),await this.startTokenRefreshLoop()}catch(t){this.setFailed()}}}}class J{constructor({speechService:t,speechConfig:e,autoDetectSourceLanguageConfig:i,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}={}){this.validateDependencies({speechService:t,speechConfig:e,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}),this.sessionData=r,this.speechService=t,this.speechConfig=e,this.speechRecognizer=a,this.bus=n,this.avatarOrchestrator=o,this.autoDetectSourceLanguageConfig=i,this._currentTurnId=0,this._expectedTurnId=0,this._lastInterruptionTime=0,this.INTERRUPTION_DEBOUNCE=100,this._isHandlingAudioEnd=!1,this.registerEventListeners(),this.speechService.startTokenRefreshLoop()}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize VoiceBot due to missing dependencies: ${e.join(", ")}`)}registerEventListeners(){this._busHandlers=this._busHandlers||[];const t=t=>{this.getNewSpeechToken()};this.bus.on("event_error_VoiceBot_ExpiredOrInvalidToken",t),this._busHandlers.push(["event_error_VoiceBot_ExpiredOrInvalidToken",t])}static async build(t,e,i,a){const{speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r}=await this.init(a,t,i,e);return new J({speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r,bus:t,auth:i,avatarOrchestrator:e,sessionData:a})}static async init(t,e,i,a){try{const n=t?.language||"en-US",s=(t?.voice,t?.autodetectLanguages||[]);let h=null,l=null;const d=new K(i,(t=>{h&&(h.authorizationToken=t)})),{token:u,region:p}=await d.requestAuthorizationToken();if(!u||!p)throw new Error("Failed to get authorization token");h=o.fromAuthorizationToken(u,p);const m=E?.speech?.vad??{},g=t?.speech?.vad??t?.vad??{},y=g.segmentationSilenceMs??m.segmentationSilenceMs??800,v=g.initialSilenceMs??m.initialSilenceMs??8e3;h.setProperty(r.Speech_SegmentationSilenceTimeoutMs,String(y)),h.setProperty(r.SpeechServiceConnection_InitialSilenceTimeoutMs,String(v));const f=g.strategy??m.strategy,b=g.semantic??m.semantic,_="string"==typeof f?f:!0===b?"Semantic":null;_&&h.setProperty(r.Speech_SegmentationStrategy,_),"multilingual"===n?s.length>0?l=c.fromLanguages(s):h.speechRecognitionLanguage="en-US":h.speechRecognitionLanguage=n;const x=await Z.build(h,l,e,a);return{speechService:d,speechConfig:h,autoDetectSourceLanguageConfig:l,speechRecognizer:x}}catch(n){throw new Error("Error in VoiceBot initialization",{cause:n})}}async getNewSpeechToken(){try{const{token:t}=await this.speechService.requestAuthorizationToken();this.speechConfig.authorizationToken=t}catch(t){}}isConversationInProgress(){return!!this.sessionData?.conversation?.conversationId}async startListening(){if(this.speechRecognizer.isListening)return{success:!0,alreadyListening:!0};try{return this.speechRecognizer.isMicDetected||(this.speechRecognizer.close(),this.speechRecognizer=await Z.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator),this.speechRecognizer.isMicDetected=!0),this.speechRecognizer.start(),{success:!0,started:!0}}catch(t){return{success:!1,error:t.message||"Failed to start speech recognition"}}}stopListening(){try{return this.speechRecognizer.stop(),{success:!0}}catch(t){return{success:!1,error:t.message||"Failed to stop speech recognition"}}}async updateSpeechLanguage(t){this.speechConfig.speechRecognitionLanguage=t,this.speechRecognizer.close(),this.speechRecognizer=await Z.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator)}destroy(){this._busHandlers?.forEach((([t,e])=>this.bus.off(t,e))),this._busHandlers=[],this.speechRecognizer?.destroy(),this.speechService?.stopTokenRefreshLoop()}}const tt={enabled:!0,micThreshold:.0033,avatarQuietFloor:.009,minSignalRatio:1.2,minSignalRatioWhileSpeaking:.38,minSignalDelta:.0028,absoluteMicOverride:.012,minDurationMs:200,cooldownMs:1500,envelopeAttack:.6,envelopeRelease:.8,leakAdaptRate:.06,leakFloor:0,leakCeil:.25,leakMargin:.012,leakDecayHoldMs:300,leakDecayRate:.2,leakMinAvatar:.01,noiseStdK:3.4,minSnr:3.2,noiseMinSamples:90,warmupMs:400,speakingGuardMs:200,minConsecutive:3,hangoverMs:100,minAbsQuiet:.0032,bandpassHz:[350,3400],minDurationWhileSpeakingMs:260,debug:!1};class et{constructor({talkingAvatar:t,avatarOrchestrator:e,config:i}={}){this.talkingAvatar=t,this.avatarOrchestrator=e,this.config={...tt,...i||{}},this._audioCtx=null,this._micStream=null,this._micSource=null,this._micBpf=null,this._micAnalyser=null,this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._armed=!1,this._candidateSince=null,this._lastTriggerTime=0,this._rafId=null,this._projectionUnsub=null,this._isDestroyed=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._lastFrameTs=0,this._lastAudioResumeAttempt=0,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats()}async init(){if(this.config.enabled)try{await this._ensureMicAnalyser(),this._subscribeToState()}catch(t){this._teardown()}}destroy(){this._isDestroyed=!0,this._unsubscribe(),this._disarm(),this._teardown()}async _ensureMicAnalyser(){if(this._micAnalyser)return;if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("Media devices API not available");this._audioCtx=this._audioCtx||new(window.AudioContext||window.webkitAudioContext);const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1}});this._micStream=t,this._micSource=this._audioCtx.createMediaStreamSource(t),this._micBpf=this._audioCtx.createBiquadFilter(),this._micBpf.type="bandpass";const[e,i]=Array.isArray(this.config.bandpassHz)&&2===this.config.bandpassHz.length?this.config.bandpassHz:[300,3e3],a=Math.max(10,Math.min(e,i||e)),n=Math.max(1.5*a,i||10*a),s=Math.sqrt(a*n);this._micBpf.frequency.value=Number.isFinite(s)?s:1e3;const o=Math.log2(n/a),r=Math.sinh(Math.log(2)/2*Math.max(o,.01)),c=r>0?1/(2*r):1;this._micBpf.Q.value=Math.max(.5,Math.min(4,c||1)),this._micAnalyser=this._audioCtx.createAnalyser(),this._micAnalyser.fftSize=512,this._micAnalyser.smoothingTimeConstant=.4,this._micSource.connect(this._micBpf).connect(this._micAnalyser),this._micBuffer=new Float32Array(this._micAnalyser.fftSize),this._debugEvent("mic-ready",{sampleRate:this._audioCtx.sampleRate,fftSize:this._micAnalyser.fftSize})}_subscribeToState(){this.avatarOrchestrator?.subscribeProjected&&(this._projectionUnsub=this.avatarOrchestrator.subscribeProjected((t=>{if(this._isDestroyed)return;const e=t?.lifecycle?.conversationSubstate;"speaking"===e?this._arm():this._disarm()})))}_unsubscribe(){if("function"==typeof this._projectionUnsub){try{this._projectionUnsub()}catch(t){}this._projectionUnsub=null}}_arm(){if(!this._micAnalyser)return;if(!this._avatarAnalyser&&!this._avatarAnalyserMissing){if(this._avatarAnalyser=this.talkingAvatar?.getSpeechAnalyzerNode?.()??null,!this._avatarAnalyser)return this._debugEvent("avatar-analyser-missing",{}),this._avatarAnalyserMissing=!0,void(this._armed=!1);this._avatarAnalyser.smoothingTimeConstant=Math.min(this._avatarAnalyser.smoothingTimeConstant??.4,.6),this._avatarBuffer=new Float32Array(this._avatarAnalyser.fftSize),this._debugEvent("avatar-analyser-ready",{fftSize:this._avatarAnalyser.fftSize})}if(this._armed)return;this._armed=!0,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1));const t="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();this._armedAt=t,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId||(this._rafId=requestAnimationFrame(this._monitorLoop)),this._debugEvent("armed",{micThreshold:this.config.micThreshold,avatarQuietFloor:this.config.avatarQuietFloor,minSignalRatio:this.config.minSignalRatio,minSignalRatioWhileSpeaking:this.config.minSignalRatioWhileSpeaking,minSignalDelta:this.config.minSignalDelta,absoluteMicOverride:this.config.absoluteMicOverride,minDurationMs:this.config.minDurationMs,cooldownMs:this.config.cooldownMs,warmupMs:this.config.warmupMs,speakingGuardMs:this.config.speakingGuardMs,minConsecutive:this.config.minConsecutive,hangoverMs:this.config.hangoverMs,bandpassHz:this.config.bandpassHz})}_disarm(){(this._armed||this._rafId)&&(this._armed=!1,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1)),this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this._debugEvent("disarmed",{}))}_monitorLoop=()=>{if(this._isDestroyed)return;if(!this._armed)return void(this._rafId=null);const t=performance.now(),e=this._lastFrameTs?t-this._lastFrameTs:16.7;this._lastFrameTs=t,"suspended"===this._audioCtx?.state&&(0===this._lastAudioResumeAttempt||t-this._lastAudioResumeAttempt>=1e3)&&(this._lastAudioResumeAttempt=t,this._audioCtx.resume().catch((()=>{})));const i=this._clamp01(this._readRms(this._micAnalyser,this._micBuffer)),a=this._avatarAnalyser?this._readRms(this._avatarAnalyser,this._avatarBuffer):0,n=this._clamp01(a),s=this._updateEnvelope("_micEnvelope",i,e),o=this._updateEnvelope("_avatarEnvelope",n,e),r=this._updateLeakEstimate({micSignal:s,avatarSignal:o,candidateActive:!!this._candidateSince}),c=o>(this.config.leakMinAvatar??.01)?.85*(r+(this.config.leakMargin??.012)):0,h=Math.max(0,s-o*c),l=o>5e-4?h/Math.max(o,5e-4):1/0,d=h-o,u=o<=this.config.avatarQuietFloor,p=h>=this.config.micThreshold,m=s>=this.config.absoluteMicOverride,g=t-(this._armedAt||t),y=g<(this.config.warmupMs??400),v=!u&&g<(this.config.speakingGuardMs??250);!m&&!this._candidateSince&&u&&!y&&0===this._consecHits&&h<1.2*this.config.micThreshold&&this._updateNoiseStats(h);const f=this._noiseCount>=(this.config.noiseMinSamples??90),b=this._noiseMean,_=this._getNoiseStd(),x=f?(h+1e-7)/(b+1e-7):0,k=this.config.noiseStdK??3.2,S=f&&h>=b+k*_,w=f&&x>=(this.config.minSnr??3),A=!!u||m||l>=(this.config.minSignalRatioWhileSpeaking??this.config.minSignalRatio)||d>=this.config.minSignalDelta,C=this.config.minAbsQuiet??0,R=!u||h>=C,T=u?R&&(m||(f?S||w:p)):m||p,L=!y&&!v,z=L&&T&&A,I=this.config.minConsecutive??4;if(z)this._consecHits+=1,this._lastQualifyTs=t;else{const e=this.config.hangoverMs??120,i=t-this._lastQualifyTs<=e;this._consecHits=i?this._consecHits:0}this._debugTick({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,leakApply:c,noiseMean:b,noiseStd:_,noiseSamples:this._noiseCount,snr:x,exceedsNoise:S,snrDominates:w,ratio:l,delta:d,meetsMicThreshold:p,avatarQuiet:u,absoluteOverride:m,absQuietOK:R,energyOK:T,energyQualified:T,competitionOK:A,noiseReady:f,warmup:y,speakingGuard:v,frameAllowed:L,frameQualifies:z,qualifies:z,consecutiveHits:this._consecHits,requiredHits:I,candidateDuration:this._candidateSince?t-this._candidateSince:0,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._consecHits>=I?this._candidateSince||(this._candidateSince=t,this._debugEvent("candidate-start",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d})):this._candidateSince&&!z&&t-this._lastQualifyTs>(this.config.hangoverMs??120)&&(this._debugEvent("candidate-reset",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d}),this._candidateSince=null,this._consecHits=0);const M=u?this.config.minDurationMs??200:this.config.minDurationWhileSpeakingMs??(this.config.minDurationMs??200)+60,E=this._candidateSince&&t-this._candidateSince>=M,P=t-this._lastTriggerTime>=this.config.cooldownMs;E&&P?this._emitBargeIn({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d,timestamp:t}):E&&!P&&this._debugEvent("cooldown-block",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:h,leak:r,noiseMean:b,noiseStd:_,snr:x,ratio:l,delta:d,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._rafId=requestAnimationFrame(this._monitorLoop)};_emitBargeIn({micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d}){this._lastTriggerTime=d,this._candidateSince=null,this._consecHits=0,this._lastQualifyTs=0,this._debugEvent("trigger",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d});try{this.avatarOrchestrator?.sendEvent?.("VOICE_BARGE_IN",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:h,delta:l,timestamp:d})}catch(u){}}_readRms(t,e){if(!t)return 0;try{t.getFloatTimeDomainData(e)}catch(a){return 0}let i=0;for(let n=0;n<e.length;n++){const t=e[n];i+=t*t}return Math.sqrt(i/e.length)}_teardown(){if(this._micStream&&(this._micStream.getTracks().forEach((t=>{try{t.stop()}catch(e){}})),this._micStream=null),this._micSource){try{this._micSource.disconnect()}catch(t){}this._micSource=null}if(this._micBpf){try{this._micBpf.disconnect()}catch(t){}this._micBpf=null}if(this._micAnalyser){try{this._micAnalyser.disconnect()}catch(t){}this._micAnalyser=null}if(this._audioCtx){try{this._audioCtx.close()}catch(t){}this._audioCtx=null}this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats(),this._lastFrameTs=0,this._lastAudioResumeAttempt=0}_debugTick(t){if(!this.config.debug)return;const e=performance.now?performance.now():Date.now();e-this._lastTickLog<150||(this._lastTickLog=e)}_debugEvent(t,e){this.config.debug}_updateEnvelope(t,e,i=16.7){const a="number"==typeof this[t]?this[t]:e,n=Math.min(Math.max(this.config.envelopeAttack,0),.999),s=Math.min(Math.max(this.config.envelopeRelease,0),.999),o=e>=a?n:s,r=Math.max(i/16.7,.1),c=a+(e-a)*(1-Math.pow(o,r)),h=this._clamp01(c);return this[t]=h,h}_updateLeakEstimate({micSignal:t,avatarSignal:e,candidateActive:i}){const a=this.config.leakMinAvatar??0,n=this.config.leakAdaptRate??.1,s=this.config.leakFloor??0,o=this.config.leakCeil??1,r="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();let c=this._leakEstimate??s;if(i||this._consecHits>0)return c;const h=this._noiseCount>=(this.config.noiseMinSamples??90),l=this._getNoiseStd(),d=this._noiseMean,u=h&&t>=d+(this.config.noiseStdK??3.2)*l;if(e>a&&t<.8*this.config.absoluteMicOverride&&!u){const i=t/Math.max(e,1e-5);c+=(Math.max(s,Math.min(i,o))-c)*n,this._leakEstimate=c,this._debugLeakUpdate({ratio:i,estimate:c}),this._lastAvatarBelowMin=null}else if(e<=a&&c>s){const t=this.config.leakDecayHoldMs??1e3,i=this.config.leakDecayRate??.1*n;null==this._lastAvatarBelowMin&&(this._lastAvatarBelowMin=r),e<=a?r-this._lastAvatarBelowMin>=t&&(c+=(s-c)*i):this._lastAvatarBelowMin=r,this._leakEstimate=Math.max(s,c)}return this._leakEstimate??s}_debugLeakUpdate({ratio:t,estimate:e}){this.config.debug&&this._debugEvent("leak-update",{ratio:t,estimate:e})}_resetNoiseStats(){this._noiseMean=0,this._noiseVar=0,this._noiseCount=0}_updateNoiseStats(t){const e=this._clamp01(t);if(!Number.isFinite(e))return;this._noiseCount>=500&&(this._noiseCount=Math.floor(350),this._noiseMean*=.95,this._noiseVar*=.9),this._noiseCount+=1;const i=e-this._noiseMean;this._noiseMean+=i/this._noiseCount;const a=e-this._noiseMean;this._noiseVar+=i*a}_getNoiseStd(){return this._noiseCount<2?0:Math.sqrt(Math.max(this._noiseVar/(this._noiseCount-1),0))}_clamp01(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:0}}let it=null;const at={setInstance(t){it=t},getItem:async t=>{if(!it)throw new Error("Storage instance not initialized");return it.getItem(t)},setItem:async(t,e)=>{if(!it)throw new Error("Storage instance not initialized");return it.setItem(t,e)},removeItem:async t=>{if(!it)throw new Error("Storage instance not initialized");return it.removeItem(t)}};class nt extends Error{constructor(t,{statusCode:e=null,reason:i=null}={}){super(t),this.name="LoginError",this.statusCode=e,this.reason=i}}async function st(t){try{const e=await fetch(`${t.serverBaseURL}/api/v1/chatbot/login`,{method:"POST",headers:{"Content-Type":"application/json","X-Sentifyd-Origin":t.targetApp},body:JSON.stringify({avatar_api_key:t.getAvatarAPIKey()})});if(!e.ok){const i=function(t){switch(t){case 404:return{message:"Avatar not found.",reason:"avatar-not-found",shouldStopRetrying:!0};case 401:return{message:"Unauthorized avatar login attempt.",reason:"unauthorized",shouldStopRetrying:!1};case 429:return{message:"Too many login attempts. Please retry later.",reason:"rate-limited",shouldStopRetrying:!1};default:return{message:`Login failed with status code ${t}.`,reason:"login-failed",shouldStopRetrying:!1}}}(e.status);throw i.shouldStopRetrying&&(t.retries=E.auth.maxLoginRetries),new nt(i.message,{statusCode:e.status,reason:i.reason})}const i=await e.json();await async function(t,e){try{const i=e?.data?.avatar_params;if(!i||!i.avatarId)throw new Error("Invalid avatar parameters received in login response.");const a=i.avatarId;t.id=a;const n={accessToken:e.data.access_token,refreshToken:e.data.refresh_token,avatarParameters:i};await t.updateAuthData(n),t.setConnected()}catch(i){throw new Error(`Failed to process login response: ${i.message}`)}}(t,i)}catch(e){throw e}}const ot=new class{constructor(t=1){this.max=t,this._fns=[],this._active=0}get remaining(){return this._fns.length}get active(){return this._active}take(t){this._fns.push(t),this._try()}_done(){this._active-=1,this._try()}_try(){if(this._active===this.max||0===this._fns.length)return;const t=this._fns.shift();this._active+=1,t&&t(this._done.bind(this))}}(1);class rt{constructor({serverBaseURL:t,getRefreshToken:e,updateAccessToken:i,onSuccess:a,onError:n}){this.serverBaseURL=t,this.getRefreshToken=e,this.onSuccess=a,this.onError=n,this.tokenRefreshIntervalId=null,this.updateAccessToken=i}startTokenRefreshInterval(){this.tokenRefreshIntervalId&&clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=setInterval((async()=>{try{await this.refreshAccessToken()}catch(t){}}),E.auth.tokenRefreshInterval)}stopTokenRefreshInterval(){this.tokenRefreshIntervalId&&(clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=null)}async refreshAccessToken(){return new Promise(((t,e)=>{ot.take((async i=>{try{const e=this.getRefreshToken();if(!e)throw new Error("No refresh token available");const i=await fetch(`${this.serverBaseURL}/api/v1/chatbot/token_exchange`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}});if(!i.ok){const t=`Failed to refresh JWT token (Status: ${i.status} ${i.statusText})`;throw"function"==typeof this.onError&&this.onError(new Error(t)),new Error(t)}const a=await i.json();if(!a?.data?.access_token)throw new Error("Invalid token data received during refresh.");this.updateAccessToken&&await this.updateAccessToken(a.data.access_token),"function"==typeof this.onSuccess&&this.onSuccess(a.data.access_token),t(!0)}catch(a){"function"==typeof this.onError&&this.onError(a),e(a)}finally{i()}}))}))}}class ct extends G{#t;#e;#i;constructor(t="",e="",i=""){if(ct._instance)return ct._instance;super("authentication"),ct._instance=this,this.#t=t,this.tokenEndpoint=e,this.#e=null,this.#i=null,this.avatarParameters=null,this.id=i,this.serverBaseURL=E.auth.serverBaseURL||"",this.targetApp="",this.lastFailureDetails=null,this.tokenRefresher=new rt({serverBaseURL:this.serverBaseURL,getRefreshToken:()=>this.#i,updateAccessToken:async t=>await this.updateAuthData({accessToken:t}),onSuccess:()=>{},onError:t=>{this.handleAuthenticationFailure("Error refreshing access token",t)}})}async init(t="web",e="",i="",a=""){this.id=a,this.targetApp=t,this.#t=e,this.tokenEndpoint=i;try{return await this.authenticate(),this.startTokenRefreshInterval(),!0}catch(n){return this.handleAuthenticationFailure(`Error during authentication initialization: ${n.message}`,n),!1}}async authenticate(){for(this.retries=0,this.setConnecting();this.retries<E.auth.maxLoginRetries;)try{if(this.#t?.trim())await st(this);else{if(!this.tokenEndpoint?.trim()){const t="authenticate: No API key or token endpoint provided for authentication.";throw this.handleAuthenticationFailure(t),new Error(t)}await this.requestDataFromServer()}return void this.clearFailureDetails()}catch(t){if(this.setDisconnected(),this.recordFailure({message:`authenticate: Attempt #${this.retries+1} failed`,reason:t instanceof nt?t.reason:t?.message||null,statusCode:t instanceof nt&&"number"==typeof t.statusCode?t.statusCode:null}),this.retries++,this.retries>=E.auth.maxLoginRetries){const e=`authenticate: All ${E.auth.maxLoginRetries} authentication attempts failed.`;if(this.handleAuthenticationFailure(e,t),t instanceof Error)throw t;throw new Error(`${e} Last error: ${t}`)}await T(E.auth.loginRetryDelay)}}startTokenRefreshInterval(){this.tokenRefresher.startTokenRefreshInterval()}stopTokenRefreshInterval(){this.tokenRefresher.stopTokenRefreshInterval()}isTokenCloseToExpiration(){if(!this.#e)return!0;try{const{exp:t}=h(this.#e);if(!t)return!0;if(1e3*t-Date.now()<=E.auth.closeToExpirationLimit)return!0}catch(t){return!0}return!1}async callSentifydApi(t,e="POST",i=null){if(!this.isConnected())throw new Error("Cannot call the API without active authentication");const a=`${this.serverBaseURL}${t}`,n=new Headers({"Content-Type":"application/json"}),s=this.getAccessToken();if(!s)throw new Error("Cannot call the API without an access token");n.append("Authorization",`Bearer ${s}`);const o={method:e,headers:n,body:i?JSON.stringify(i):void 0};try{let t=await fetch(a,o);if(401===t.status)try{await this.authenticate();const e={...o,headers:{...o.headers,Authorization:`Bearer ${this.getAccessToken()}`}};if(t=await fetch(a,e),401===t.status)throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error(`API call failed: ${t.statusText} (Status: ${t.status})`)}catch(r){throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error("API call failed")}if(!t.ok)throw new Error(`API call failed: ${t.statusText} (Status: ${t.status})`);return await t.json()}catch(r){throw r}}async isAuthRequired(){const t=this.#a();return!(t&&t.accessToken&&t.refreshToken&&t.avatarParameters&&!this.isTokenCloseToExpiration())}async logout(){this.id&&await async function(t){if(t)try{await at.removeItem(`authData_${t}`)}catch(e){}}(this.id),this.stopTokenRefreshInterval(),this.#e=null,this.#i=null,this.avatarParameters=null,this.clearFailureDetails(),this.setDisconnected()}async#n(){if(!this.id)return!1;const t=await async function(t){if(!t)return null;try{const e=await at.getItem(`authData_${t}`);return e?JSON.parse(e):null}catch(e){return null}}(this.id);if(!t)return!1;try{return this.#e=t.accessToken,this.#i=t.refreshToken,this.avatarParameters=t.avatarParameters,await this.isAuthRequired()?(this.setDisconnected(),!1):(this.setConnected(),await this.updateAvatarParametersFromServer(),!0)}catch(e){return this.setDisconnected(),!1}}#a(){return this.id&&this.#e&&this.#i&&this.avatarParameters?{accessToken:this.#e,refreshToken:this.#i,avatarParameters:this.avatarParameters}:null}getAccessToken(){return this.#e||null}getRefreshToken(){return this.#i||null}getAvatarAPIKey(){return this.#t}async updateAccessToken(t){await this.updateAuthData({accessToken:t})}getAvatarParameters(){return this.avatarParameters||null}async updateAuthData({accessToken:t,refreshToken:e,avatarParameters:i}){const a=this.#a()||{};t&&(this.#e=t,a.accessToken=t),e&&(this.#i=e,a.refreshToken=e),i&&(this.avatarParameters=i,a.avatarParameters=i);try{await async function(t,e){if(t)try{await at.setItem(`authData_${t}`,JSON.stringify(e))}catch(i){}}(this.id,a),this.clearFailureDetails()}catch(n){}}async requestDataFromServer(){if(!this.tokenEndpoint?.trim())throw new Error("requestDataFromServer: Token URL is not specified.");try{const t=await fetch(this.tokenEndpoint,{method:"GET"});if(!t.ok)throw new Error(`requestDataFromServer: Failed to request tokens (Status: ${t.status} ${t.statusText})`);const e=await t.json();if(!this.#s(e))throw new Error("requestDataFromServer: Invalid token response received from server.");await this.updateAuthData({accessToken:e.tokens.accessToken,refreshToken:e.tokens.refreshToken,avatarParameters:e.avatarParameters}),this.setConnected()}catch(t){throw this.setDisconnected(),t}}#s(t){return t?.tokens?.accessToken&&t?.tokens?.refreshToken&&t?.avatarParameters}async updateAvatarParametersFromServer(){try{const t=await this.callSentifydApi("/api/v1/chatbot/get-avatar-params","POST");if(!t||!t.data||!t.data.avatar_params)return;this.avatarParameters=t.data.avatar_params,this.updateAuthData({avatarParameters:this.avatarParameters})}catch(t){}}handleAuthenticationFailure(t,e=null){this.recordFailure({message:t,reason:e instanceof nt?e.reason:e instanceof Error?e.message:null,statusCode:e instanceof nt&&"number"==typeof e.statusCode?e.statusCode:null}),this.setFailed()}recordFailure({message:t,reason:e=null,statusCode:i=null}={}){this.lastFailureDetails={message:t||"Unknown authentication error",reason:e??(t||"Unknown authentication error"),statusCode:i,timestamp:Date.now()}}clearFailureDetails(){this.lastFailureDetails=null}getLastFailureDetails(){return this.lastFailureDetails?{...this.lastFailureDetails}:null}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.stopTokenRefreshInterval(),this.isFailed()?this.setReconnecting():this.setConnecting();try{await this.authenticate(),this.isConnected()?this.startTokenRefreshInterval():this.setFailed()}catch(t){this.handleAuthenticationFailure("Authentication reconnect failed",t)}}}static resetInstance(){ct._instance=null}}class ht{constructor(t,e=l){this.avatarId=t,this.conversationData={id:void 0,transcript:[],currentTurnId:0},this.lastDetectedLanguage=null,this.uuidGenerator=e,this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0}get conversationId(){return this.conversationData.id}set conversationId(t){this.conversationData.id=t}get transcript(){return this.conversationData.transcript}set transcript(t){this.conversationData.transcript=t}get currentTurnId(){return this.conversationData.currentTurnId}set currentTurnId(t){this.conversationData.currentTurnId=t}incrementTurnId(){return this.conversationData.currentTurnId++,this.conversationData.currentTurnId}async getConversationData(){if(!this.avatarId)return null;const t=await at.getItem(`conversationData_${this.avatarId}`),e={id:void 0,transcript:[],currentTurnId:0};return this.conversationData=t?{...e,...JSON.parse(t)}:e,this.conversationData}async saveConversationData(){this.avatarId&&await at.setItem(`conversationData_${this.avatarId}`,JSON.stringify(this.conversationData))}async notifyConversationInit(){await this.getConversationData(),this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId())}async notifyConversationStart(t=!1){if(t)this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0,await this.clearOngoingConversation(),await this.generateNewConversationId(),this.incrementTurnId();else{await this.getConversationData();const t=!!this.conversationId,e=Array.isArray(this.transcript)&&this.transcript.length>0;this.lastStartWasResumeAttempt=t&&e,this.transcriptLengthBeforeResume=e?this.transcript.length:0,this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId()),this.incrementTurnId()}}async notifyConversationEnd(){this.lastStartWasResumeAttempt=!1,await this.clearOngoingConversation()}async clearOngoingConversation(){this.conversationData={id:void 0,transcript:[],currentTurnId:0};try{await at.removeItem(`conversationData_${this.avatarId}`)}catch(t){await this.saveConversationData()}}async discardConversationHistory(){const t=this.conversationId,e=this.currentTurnId;this.conversationData={id:t,transcript:[],currentTurnId:e},await this.saveConversationData()}async generateNewConversationId(){const t=this.uuidGenerator();this.conversationId=t,await this.saveConversationData()}async appendMessage(t,e,i){if(!this.conversationId)return null;const a={speaker:i,messageText:L(t),time:e};return this.transcript.push(a),await this.saveConversationData(),a}async handleConversationSuccessfulStart(t){const e=t?.isInProgress,i=t?.conversationId,a=this.conversationId,n=!!this.lastStartWasResumeAttempt;let s=!1;if(!1===e&&(s=!0),i&&a&&i!==a&&(this.conversationId=i,s=!0),n&&s){const t=this.transcript.slice(this.transcriptLengthBeforeResume);this.conversationData.transcript=t,await this.saveConversationData()}return{serverStartedNew:s,resumeAttempt:n,resumeFailed:s&&n}}}class lt{constructor(){if(lt._instance)return lt._instance;this._avatarId=null,this._avatarName="",this._avatarItem=null,this._trainingId=null,this._language="",this._autodetectLanguages=[],this._voice="",this._lipsyncType="words",this._wordsPerMinute=150,this._userData={username:"",phoneNumber:"",email:"",isTermsAccepted:!1},this.conversation=null,lt._instance=this,Object.seal(this)}static getInstance(){return lt._instance||(lt._instance=new lt),lt._instance}static hasInstance(){return null!==lt._instance&&void 0!==lt._instance}static resetInstance(){if(lt._instance)try{return lt._instance.destroy(),lt._instance=null,!0}catch(t){return!1}return!0}async init(t,e){const{avatarId:i,avatarName:a,trainingId:n,language:s,autodetectLanguages:o,voice:r,wordsPerMinute:c}=t;if(![i,a,e,s,r].every((t=>null!=t&&""!==t))||!Array.isArray(o))return!1;this._trainingId=null===n||""===n?null:n,this._avatarId=i,this._avatarName=a,this._avatarItem=e,this._language=s,this._autodetectLanguages=o,this._voice=r,this._lipsyncType=e?.lipsyncType||"words",this._wordsPerMinute=c||150;try{return this.conversation=new ht(this._avatarId),!0}catch(h){return!1}}get isUserDataDefined(){return this._userData.username&&!0===this._userData.isTermsAccepted}get avatarId(){return this._avatarId}set avatarId(t){this._avatarId=t,this.conversation&&(this.conversation.avatarId=t)}get avatarName(){return this._avatarName}set avatarName(t){"string"==typeof t&&""!==t.trim()&&(this._avatarName=t)}get avatarItem(){return this._avatarItem}set avatarItem(t){t&&"object"==typeof t&&(this._avatarItem=t)}get trainingId(){return this._trainingId}set trainingId(t){(null==t||"string"==typeof t&&""!==t.trim())&&(this._trainingId=t)}get language(){return this._language}set language(t){"string"==typeof t&&""!==t.trim()&&(this._language=t)}get autodetectLanguages(){return this._autodetectLanguages}set autodetectLanguages(t){Array.isArray(t)&&(this._autodetectLanguages=t)}get voice(){return this._voice}set voice(t){"string"==typeof t&&""!==t.trim()&&(this._voice=t)}get lipsyncType(){return this._lipsyncType}set lipsyncType(t){["words","visemes","blendshapes"].includes(t)&&(this._lipsyncType=t)}get wordsPerMinute(){return this._wordsPerMinute}set wordsPerMinute(t){"number"!=typeof t||t<=0||(this._wordsPerMinute=t)}get username(){return this._userData.username}set username(t){"string"==typeof t&&""!==t.trim()&&(this._userData.username=t)}get phoneNumber(){return this._userData.phoneNumber}set phoneNumber(t){"string"==typeof t&&""!==t.trim()&&(this._userData.phoneNumber=t)}get email(){return this._userData.email}set email(t){"string"==typeof t&&""!==t.trim()&&(this._userData.email=t)}get isTermsAccepted(){return this._userData.isTermsAccepted}set isTermsAccepted(t){"boolean"==typeof t&&(this._userData.isTermsAccepted=t)}destroy(){try{this.conversation&&"function"==typeof this.conversation.destroy&&this.conversation.destroy()}catch(t){}}}function dt(t){try{t?.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t?.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}}lt._instance=null;const ut=d({id:"avatarOrchestrator",context:({input:t})=>({bus:t?.bus??null,talkingAvatar:t?.talkingAvatar??null,chatSocket:t?.chatSocket??null,voiceBot:t?.voiceBot??null,conversation:t?.conversation??null,eventPayload:null,isPageVisible:!0,currentPage:"LoaderPage",pendingStart:null,userSilenced:!1,initFailed:!1,firstConnectionCompleted:!1}),type:"parallel",states:{lifecycle:{initial:"init",states:{init:{initial:"initializing",states:{initializing:{id:"initializing",on:{READY:{target:"complete",actions:["onLeaveInitializing"]},FAIL:{target:"failed",actions:u({initFailed:!0})}}},failed:{id:"failed",on:{RETRY:{target:"initializing"},CONNECT:{target:"initializing"}}},complete:{always:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}}}},checkingResume:{id:"checkingResume",invoke:{id:"checkResumeOnStart",src:"checkResumeActor",input:({context:t})=>({conversation:t.conversation,bus:t.bus}),onDone:[{target:"conversation.autoResuming",guard:({event:t})=>!!t.output?.resumable},{target:"conversation.stopped"}],onError:{target:"conversation.stopped"}}},conversation:{initial:"stopped",on:{CONVERSATION_TIMEOUT:{target:".timedOut"}},states:{stopped:{id:"stopped",on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},CONVERSATION_TIMEOUT:{target:"#avatarOrchestrator.lifecycle.conversation.timedOut"},DISCONNECT:{actions:[]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},timedOut:{id:"timedOut",entry:[({context:t,event:e})=>{try{const i=e?.payload?.conversationId??t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_TimedOut",{conversationId:i})}catch(i){}}],on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},autoResuming:{id:"autoResuming",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"autoResumeService",src:"startConversationService",input:({context:t})=>({isNew:!1,skipFallback:!0,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"inProgress.idle",actions:"onConversationStartSuccess"},{target:"inProgress.thinking",actions:"onConversationStartSuccess"}],onError:{target:"resumeExpired",actions:["onAutoResumeFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"inProgress.pendingAudioStart",actions:["onStreamStart"]},IDLE:"inProgress.idle"}},resumeExpired:{id:"resumeExpired",entry:[({context:t})=>{try{const e=t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_ResumeExpired",{conversationId:e})}catch(e){}}],on:{START_NEW_CONVERSATION:{target:"inProgress.startingConversation",actions:u({eventPayload:{fresh:!0}})},DISMISS:{target:"stopped",actions:[({context:t})=>{try{t.conversation?.clearOngoingConversation?.()}catch(e){}}]},CLEAR_CONVERSATION:{target:"clearingConversation"},END_CONVERSATION:{target:"endingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},paused:{id:"paused",entry:["onConversationPaused"],tags:["conversation_paused","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},RECONNECT:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],RESTORED_CONNECTION:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},initializingConversation:{id:"initializingConversation",invoke:{id:"initConversationActor",src:"initConversationActor",input:({context:t})=>({conversation:t.conversation,chatSocket:t.chatSocket,bus:t.bus}),onDone:{target:"stopped",actions:"onConversationInitSuccess"},onError:{target:"stopped",actions:[u({initFailed:!0}),"onConversationInitFailed"]}},on:{FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},inProgress:{id:"inProgress",tags:["conversation_in_progress"],on:{STOP:{target:"stopped",actions:["onStop"]},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},DISCONNECT:[{target:"paused",guard:"hasActiveConversation"},{target:"stopped"}],AUDIO_START:{target:"#speaking",actions:["onAudioStarted"]},AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}},initial:"idle",states:{idle:{id:"idle",entry:["onIdle"],on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},LISTEN:"listening",THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})},SEND_TEXT_MESSAGE:{target:"processingTextMessage"},MIC_BUTTON:[{guard:"isRequestBlocked",actions:["onMicButtonBlocked"]},{target:"listening",actions:["onMicButtonStartListening"]}],AUDIO_END:{actions:["onAudioEnd"]}}},listening:{id:"listening",tags:["listening"],entry:["onListenEntry"],invoke:{id:"listenActor",src:"listenActor",input:({context:t})=>({voiceBot:t.voiceBot,bus:t.bus}),onError:{target:"idle",actions:["onListenFailed"]}},on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:["onIdle",u({eventPayload:({event:t})=>t.payload})]},SPEECH_RECOGNITION_COMPLETE:{target:"processingSpeechRecognition"},SEND_TEXT_MESSAGE:{target:"processingTextMessage",actions:[({context:t})=>{if(t.voiceBot){t.voiceBot.stopListening();try{t.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t.bus.emit("event_command_UI_ClearCaptions")}catch(e){}}}]},MIC_BUTTON:{target:"idle",actions:["setUserSilencedTrue","onMicButtonStopListening"]},IDLE:"idle",AUDIO_END:{actions:["onAudioEnd"]}}},processingSpeechRecognition:{id:"processingSpeechRecognition",invoke:{id:"speechRecognitionActor",src:"speechRecognitionActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSpeechRecognitionFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},processingTextMessage:{id:"processingTextMessage",invoke:{id:"sendTextMessageActor",src:"sendTextMessageActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSendTextMessageFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},thinking:{id:"thinking",tags:["thinking","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}}},startingConversation:{id:"startingConversation",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"startConversationService",src:"startConversationService",input:({context:t})=>({isNew:t.eventPayload?.fresh||!1,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"idle",actions:"onConversationStartSuccess"},{target:"thinking",actions:"onConversationStartSuccess"}],onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped",actions:[u({initFailed:!0}),"onConversationStartFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle"}},pendingAudioStart:{id:"pendingAudioStart",tags:["thinking","inputs_blocked"],after:{speechStartTimeout:{guard:"isPendingAudioStart",target:"#speaking",actions:["onAudioStartedFallback"]}},on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},speaking:{id:"speaking",tags:["speaking"],on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},STREAM_END:{actions:["onStreamEnd"],internal:!0},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},interruptingForRestart:{id:"interruptingForRestart",entry:["onEnsureCleanupComplete"],invoke:{src:"cleanupInterruptionActor",input:({context:t})=>({talkingAvatar:t.talkingAvatar,chatSocket:t.chatSocket,voiceBot:t.voiceBot}),onDone:{target:"startingConversation"},onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}},tags:["inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]}}}}},endingConversation:{id:"endingConversation",tags:["inputs_blocked"],invoke:{id:"endConversationActor",src:"endConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar,voiceBot:t.voiceBot,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedEndConversation"})}catch(e){}}]}}},clearingConversation:{id:"clearingConversation",tags:["inputs_blocked"],invoke:{id:"clearConversationActor",src:"clearConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,talkingAvatar:t.talkingAvatar,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedClearConversation"})}catch(e){}}]}}}}}}},connection:{initial:"connected",states:{connected:{id:"connected",on:{DISCONNECT:"disconnected"}},disconnected:{id:"disconnected",on:{RECONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]},CONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]}}}}}},on:{INJECT_MODULES:{actions:[u((({context:t,event:e})=>({talkingAvatar:e.payload?.talkingAvatar??t.talkingAvatar,chatSocket:e.payload?.chatSocket??t.chatSocket,voiceBot:e.payload?.voiceBot??t.voiceBot,conversation:e.payload?.conversation??t.conversation}))),({context:t,self:e})=>{try{const i=e.getSnapshot?.();(i?.matches?.("lifecycle.conversation.stopped")||i?.matches?.("lifecycle.conversation.timedOut"))&&t.conversation&&e.send({type:"AVATAR_INITIALIZED"})}catch(i){}}]},PAGE_CHANGED:{actions:["onPageChanged","setCurrentPage"]},DEFER_START:{actions:["onDeferStart"]},VISIBILITY_CHANGED:{actions:["onVisibilityChanged"]},UI_CHATBOT_MODE:{actions:["onUiChatbotMode"]},CONVERSATION_ERROR:{actions:["onConversationError"]},TTS_ERROR:{actions:["onTtsError"]},INTERRUPT:{actions:[({context:t})=>{try{t.talkingAvatar?.interruptSpeaking?.()}catch{}try{t.chatSocket?.interruptCurrentTurn?.()}catch{}try{t.voiceBot?.stopListening?.()}catch{}try{t.bus?.emit?.("event_command_UI_ClearCaptions")}catch{}}]}}},{actions:{onPageChanged:({context:t,event:e,self:i})=>{try{const n=e?.payload?.newPage;if(!n)return;const s=i.getSnapshot?.(),o=!!s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart"),r=!!s?.hasTag?.("listening")||s?.matches?.("lifecycle.conversation.inProgress.listening");if("AvatarPage"!==n&&(o||r)&&(o?i.send({type:"INTERRUPT"}):r&&i.send({type:"IDLE"})),"AvatarPage"===n)try{const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&t.isPageVisible&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}catch(a){}}catch(n){}},setCurrentPage:u((({event:t})=>{const e=t?.payload?.newPage;return e?{currentPage:e}:{}})),onDeferStart:u((({context:t,event:e})=>{if(!t.isPageVisible){const i=e.payload?.fresh??!1;return null!==t.pendingStart&&t.pendingStart,{pendingStart:i}}return null!==t.pendingStart?{pendingStart:null}:{}})),onVisibilityChanged:u((({context:t,event:e,self:i})=>{const a=e&&(e.payload?.isVisible??e.isVisible),n=void 0===a?!!t.isPageVisible:!!a,s=n&&!t.isPageVisible;if(!n&&t.isPageVisible){if(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),t.talkingAvatar){t.talkingAvatar.interruptSpeaking?.();try{t.talkingAvatar.suspendRendering?.("visibility")}catch(o){}}i.send({type:"IDLE"})}else{if(s&&null!==t.pendingStart){const e=t.pendingStart;return i.send({type:"START_CONVERSATION",payload:{fresh:e}}),{isPageVisible:n,pendingStart:null}}s&&t.voiceBot&&i.getSnapshot().matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})}try{if(n&&"AvatarPage"===t.currentPage){const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}}catch(o){}return{isPageVisible:n}})),onListenEntry:({context:t})=>{t.voiceBot&&dt(t)},onListenFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onIdle:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening().success)},onStop:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening())},onAudioStarted:({context:t,event:e})=>{const i=e?.payload?.audioStartTime??("undefined"!=typeof performance?performance.now():Date.now());try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:i})}catch(a){}},onAudioStartedFallback:({context:t})=>{const e="undefined"!=typeof performance?performance.now():Date.now();try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:e})}catch(i){}},onStreamStart:({context:t,event:e})=>{const{audioStream:i,lipsyncStream:a,turnId:n}=e.payload||{};t.voiceBot&&void 0!==n&&(t.voiceBot._currentTurnId=n,t.voiceBot._expectedTurnId=n),t.talkingAvatar&&i&&a&&t.talkingAvatar.startStreaming(i,a,n)},onInterruptSpeaking:({context:t,self:e})=>{if(t.voiceBot){const i=Date.now();if(i-t.voiceBot._lastInterruptionTime<t.voiceBot.INTERRUPTION_DEBOUNCE)return;const a=-1!==t.voiceBot._expectedTurnId,n=t.voiceBot._isHandlingAudioEnd,s=e.getSnapshot(),o=s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart");a&&o&&!n&&(t.voiceBot._expectedTurnId=-1,t.voiceBot._lastInterruptionTime=i),dt(t),t.voiceBot.stopListening().success}t.talkingAvatar&&t.talkingAvatar.interruptSpeaking(),t.chatSocket&&t.chatSocket.interruptCurrentTurn()},onEnsureCleanupComplete:({context:t,self:e})=>{},onSpeechRecognitionFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onSendTextMessageFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"})}catch(i){}},onUiChatbotMode:({context:t,event:e,self:i})=>{const a=e.payload;if(!a||void 0===a.isShown&&!a.chatbotMode)return;const n=a.chatbotMode;if(t.chatSocket&&(void 0!==n&&(t.chatSocket.chatbotMode=n),void 0!==a.isShown&&(t.chatSocket.isChatbotShown=a.isShown)),"CHAT"===n){const e=i.getSnapshot();if(e.matches("lifecycle.conversation.inProgress.speaking")||e.matches("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(dt(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("chat")}catch(s){}}else if("AVATAR"===n)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),n=e.matches?.("lifecycle.conversation.inProgress.idle"),s=!!t.isPageVisible;a&&n&&s&&i.send({type:"LISTEN"})}catch(s){}if(!1===a.isShown)try{const e=i.getSnapshot();if(e.matches?.("lifecycle.conversation.inProgress.speaking")||e.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking?.()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(dt(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches?.("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(dt(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("ui-hidden")}catch(s){}}catch(s){}else if(!0===a.isShown)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),s=e.matches?.("lifecycle.conversation.inProgress.idle"),o=!!t.isPageVisible;"AVATAR"===(void 0!==n?n:t.chatSocket?.chatbotMode)&&a&&s&&o&&i.send({type:"LISTEN"})}catch(s){}try{const e=void 0!==n?n:t.chatSocket?.chatbotMode,i=void 0!==a.isShown?a.isShown:!1!==t.chatSocket?.isChatbotShown;if("AVATAR"===e&&i&&t.isPageVisible&&"AvatarPage"===t.currentPage)t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.();else if(t.talkingAvatar?.isRenderingActive?.()&&("CHAT"===e||!i||!t.isPageVisible||"AvatarPage"!==t.currentPage))try{t.talkingAvatar?.suspendRendering?.("conditions-change")}catch(s){}}catch(s){}},onLeaveDisconnected:({self:t})=>t.send({type:"RESTORED_CONNECTION"}),onLeaveInitializing:({self:t})=>t.send({type:"AVATAR_INITIALIZED"}),onStartingConversation:({context:t,event:e})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening(),t.voiceBot._expectedTurnId=-1),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()},onConversationStartSuccess:({context:t,event:e})=>{},onConversationStartFailed:({context:t,event:e})=>{},onAutoResumeFailed:({context:t,event:e})=>{},onConversationInitFailed:({context:t,event:e})=>{},onConversationInitSuccess:({context:t,event:e})=>{},handleAiMessage:({context:t,event:e,self:i})=>{const{message:a,time:n,structuredResponse:s}=e.payload||{};if("string"==typeof a&&""!==a.trim())try{t.bus.emit("event_command_UI_UpdateCurrentMessage",{speaker:"assistant",messageText:L(a)})}catch(r){}const o=s?.avatar_mood??e.payload?.structuredResponse?.avatar_mood;if(o)try{t.bus.emit("event_command_Avatar_SetAvatarMood",{mood:o})}catch(r){}t.conversation&&a&&Promise.resolve().then((async()=>{try{const i=n||(new Date).toLocaleTimeString(),s=await t.conversation.appendMessage(a,i,"assistant");try{t.bus.emit("event_status_Conversation_MessageAppended",s)}catch(e){}}catch(r){}})),"AVATAR"===t.chatSocket?.chatbotMode||setTimeout((()=>{try{const t=i.getSnapshot?.();(t?.matches?.("lifecycle.conversation.inProgress.thinking")||t?.matches?.("lifecycle.conversation.inProgress.startingConversation")||t?.matches?.("lifecycle.conversation.autoResuming"))&&i?.send?.({type:"IDLE"})}catch(t){}}),0)},onAudioEnd:({context:t,event:e})=>{const{turnId:i}=e.payload||{};if(dt(t),t.voiceBot){if(-1===t.voiceBot._expectedTurnId||i!==t.voiceBot._expectedTurnId)return;t.voiceBot._expectedTurnId=-1,t.voiceBot._isHandlingAudioEnd=!0}t.chatSocket?.pendingDelayedActions?.length>0&&(P(t.chatSocket.pendingDelayedActions,t.bus),t.chatSocket.pendingDelayedActions=null),t.voiceBot&&setTimeout((()=>{t.voiceBot._isHandlingAudioEnd=!1}),50)},onStreamEnd:({context:t})=>{try{t.talkingAvatar?.finalizeTurn?.()}catch(e){}if(t.chatSocket?.pendingDelayedActions?.length>0){try{P(t.chatSocket.pendingDelayedActions,t.bus)}catch(e){}t.chatSocket.pendingDelayedActions=null}},onMicButtonBlocked:({context:t})=>{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertWaitForAIResponse"})},onMicButtonStartListening:u((()=>({userSilenced:!1}))),setUserSilencedTrue:u((()=>({userSilenced:!0}))),onMicButtonStopListening:({context:t})=>{},onMicButtonInterruptSpeaking:u((()=>({userSilenced:!1}))),emitVoiceBargeInEvent:({context:t,event:e})=>{const i=e?.payload||{};try{t.bus?.emit?.("event_status_Speech_BargeInTriggered",{micLevel:i.micLevel,avatarLevel:i.avatarLevel,ratio:i.ratio,delta:i.delta,timestamp:i.timestamp})}catch(a){}},onVoiceBargeIn:u((()=>({userSilenced:!1}))),onAssistantMessage:({context:t,event:e})=>{try{t.bus.emit("event_command_UI_AutoScrollChat",{message:e?.payload?.message||e?.message})}catch(i){}},onConversationError:({context:t,event:e,self:i})=>{const{error:a,chatbotMode:n}=e.payload||{};if(!a)return;if((908===a.code||404===a.code||408===a.code)&&void 0!==a.conversationId)return void i.send({type:"CONVERSATION_TIMEOUT",payload:{conversationId:a.conversationId}});const s=a.message?{errorMessage:a.message}:{messageKey:"alertSomeErrorOccurred"};t.bus.emit("event_command_Alerts_ShowDismissableAlert",s);const o=i.getSnapshot();o.matches("lifecycle.conversation.inProgress.thinking")&&i.send({type:"IDLE"}),"AVATAR"===n&&o.matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})},onTtsError:({context:t,self:e})=>{t.chatSocket?.cleanupActiveStreams();const i=e.getSnapshot();i.matches("lifecycle.conversation.inProgress.speaking")||i.matches("lifecycle.conversation.inProgress.pendingAudioStart")?(t.talkingAvatar?.interruptSpeaking&&t.talkingAvatar.interruptSpeaking(),e.send({type:"IDLE"})):e.send({type:"IDLE"})},onConversationPaused:({context:t})=>{t.voiceBot&&(dt(t),t.voiceBot.stopListening()),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()}},guards:{isRequestBlocked:({self:t})=>{try{const e=t.getSnapshot?.();return!!e?.hasTag?.("thinking")}catch(e){return!1}},isAvatarMode:({context:t})=>{try{return"AVATAR"===t?.chatSocket?.chatbotMode}catch(e){return!1}},hasActiveConversation:({context:t})=>{if(!t.conversation)return!1;try{const e=!!t.conversation.conversationId,i=(t.conversation.conversationData?.currentTurnId||0)>0,a=Array.isArray(t.conversation.conversationData?.transcript)&&t.conversation.conversationData.transcript.length>0;return e&&(i||a)}catch(e){return!1}},isPendingAudioStart:({self:t})=>{try{return t.getSnapshot?.().matches?.("lifecycle.conversation.inProgress.pendingAudioStart")}catch(e){return!1}}},actors:{startConversationService:p((async({input:t})=>{const{isNew:e,skipFallback:i,bus:a,conversation:n,chatSocket:s,talkingAvatar:o}=t||{};if(!n||!s)throw new Error("Conversation or ChatSocket module not available");if(await Promise.resolve(),o?.conversationStreamActive)try{await(o.stopConversationStream?.())}catch(l){}e&&n.conversationId&&await n.notifyConversationEnd(),await n.notifyConversationStart(e),o&&await o.startConversationStream();const r=!e;let c;try{c=await s.sendStartConversationEvent(r)}catch(d){const t=d?.message?.includes("404")||d?.message?.includes("408");if(r&&t&&!i){try{await n.clearOngoingConversation()}catch(l){}await n.notifyConversationStart(!0),c=await s.sendStartConversationEvent(!1);try{a?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:n.conversationId})}catch(l){}return c}throw d}const h=await(n.handleConversationSuccessfulStart?.(c))||{};if(h.resumeFailed)try{a?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:n.conversationId})}catch(l){}else if(h.resumeAttempt&&!h.serverStartedNew)try{a?.emit?.("event_status_Conversation_ResumedSuccessfully",{conversationId:n.conversationId})}catch(l){}return c})),initConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i}=t||{};if(!e)throw new Error("Conversation module not available");return await e.notifyConversationInit(),i&&await i.sendInitConversationEvent(),{initialized:!0}})),listenActor:p((async({input:t})=>{const{voiceBot:e}=t||{};if(!e)return{started:!1};const i=await e.startListening();if(!i.success)throw new Error(i.error||"Failed to start listening");return{started:!0}})),speechRecognitionActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.messageText)throw new Error("Invalid speech payload");const s=await a.appendMessage(i.messageText,z(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(r){}const o=await e.sendMessage(i,"AVATAR");if(!o.success)throw n?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(o.error||"Failed to process speech input");return{sent:!0}})),sendTextMessageActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.message)throw new Error("Invalid text payload");const s=await a.appendMessage(i.message,z(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(h){}const o={messageText:i.message},r=i.chatbotMode||"CHAT",c=await e.sendMessage(o,r);if(!c.success)throw n?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(c.error||"Failed to send text message");return{sent:!0}})),endConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i,talkingAvatar:a,voiceBot:n,payload:s}=t||{};if(!e)return!0;const o=e.conversationId,{satisfactionScore:r=0}=s||{};if(await e.notifyConversationEnd(),i&&o)try{i.sendEndConversationEvent(o,r)}catch(c){}try{a?.interruptSpeaking?.()}catch(c){}try{await(a?.stopConversationStream?.())}catch(c){}try{a?.liveCaptions?.clearCaptions?.(),n?.stopListening?.()}catch(c){}return!0})),clearConversationActor:p((async({input:t})=>{const{conversation:e,talkingAvatar:i,payload:a}=t||{};if(!e)return!0;const{conversationId:n}=a||{};if(n===e.conversationId){await e.clearOngoingConversation();try{await(i?.stopConversationStream?.())}catch(s){}}return!0})),checkResumeActor:p((async({input:t})=>{const{conversation:e,bus:i}=t||{};if(!e)return{resumable:!1};try{const t=await(e.getConversationData?.());if(t?.id&&Array.isArray(t.transcript)&&t.transcript.length>0)return{resumable:!0}}catch(a){throw a}return{resumable:!1}})),cleanupInterruptionActor:p((async({input:t})=>{const{talkingAvatar:e,chatSocket:i,voiceBot:a}=t||{};try{try{e?.liveCaptions?.clearCaptions?.()}catch(n){}if(a)try{a.stopListening?.()}catch(n){}try{e?.interruptSpeaking?.()}catch(n){}try{i?.interruptCurrentTurn?.()}catch(n){}return await new Promise((t=>setTimeout(t,10))),!0}catch(s){throw s}}))},delays:{thinkingTimeout:E?.chatbot?.thinkingTimeout,speechStartTimeout:Math.min(Math.max(E?.chatbot?.speechStartTimeout??8e3,2e3),6e4)}});class pt{constructor(t){if(!t)throw new Error("Cannot initialize AvatarOrchestrator: missing bus instance");this.bus=t,this.actor=null,this._pendingEvents=[],this._deferredModules=null,this.diagnostics=null}start(t={}){if(this._deferredModules&&(t={...t,...this._deferredModules},this._deferredModules=null),this.actor)t&&Object.keys(t).length>0&&this.injectModules(t);else if(this.actor=m(ut,{input:{bus:this.bus,...t}}).start(),this.actor.subscribe((t=>{this.handleStateTransition(t)})),this._pendingEvents.length>0){for(const t of this._pendingEvents)this.actor.send(t);this._pendingEvents.length=0}}handleStateTransition(t){t&&this.diagnostics&&t?.changed&&(this.diagnostics.logStateTransition(t.history?.value,t.value),t.matches?.("lifecycle.conversation.stopped")&&this.diagnostics.displayDiagnosticsInConsole())}sendEvent(t,e=null){const i={type:t,payload:e};this.actor?this.actor.send(i):this._pendingEvents.push(i)}is(t){return!!this.actor&&this.actor.getSnapshot().matches(t)}getCurrentState(){return this.actor?.getSnapshot().value}getSnapshot(){return this.actor?this.actor.getSnapshot():null}destroy(){this.actor?.stop(),this.actor=null,this.diagnostics=null,this._pendingEvents=[]}interruptSpeaking(){this.sendEvent("INTERRUPT")}transitionToListening(){this.sendEvent("LISTEN")}transitionToIdle(){this.sendEvent("IDLE")}injectModules(t={}){this.actor?this.actor.send({type:"INJECT_MODULES",payload:t}):this._deferredModules={...this._deferredModules||{},...t}}subscribeProjected(t){if(!this.actor)return()=>{};let e={};const i=this.actor.subscribe((i=>{const a={lifecycle:{initInitializing:i.matches?.("lifecycle.init.initializing")||!1,initFailed:i.matches?.("lifecycle.init.failed")||!1,convoStopped:i.matches?.("lifecycle.conversation.stopped")||!1,convoAutoResuming:i.matches?.("lifecycle.conversation.autoResuming")||!1,convoResumeExpired:i.matches?.("lifecycle.conversation.resumeExpired")||!1,convoInProgress:i.matches?.("lifecycle.conversation.inProgress")||!1,convoStarting:i.matches?.("lifecycle.conversation.inProgress.startingConversation")||!1,convoInitializing:i.matches?.("lifecycle.conversation.initializingConversation")||!1,conversationSubstate:i.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")?"pendingAudioStart":i.matches?.("lifecycle.conversation.inProgress.speaking")?"speaking":i.matches?.("lifecycle.conversation.inProgress.listening")?"listening":i.matches?.("lifecycle.conversation.inProgress.thinking")?"thinking":i.matches?.("lifecycle.conversation.inProgress.startingConversation")?"startingConversation":i.matches?.("lifecycle.conversation.inProgress.idle")?"idle":""},connection:{connected:i.matches?.("connection.connected")||!1,disconnected:i.matches?.("connection.disconnected")||!1},flags:{userSilenced:i.context?.userSilenced||!1,isPageVisible:!!i.context?.isPageVisible,pendingStart:"boolean"==typeof i.context?.pendingStart?i.context.pendingStart:null}};!function(t,e){if(t===e)return!0;if(!t||!e)return!1;const i=t.lifecycle,a=e.lifecycle;if(!i||!a)return!1;if(i.initInitializing!==a.initInitializing||i.initFailed!==a.initFailed||i.convoStopped!==a.convoStopped||i.convoResumable!==a.convoResumable||i.convoInProgress!==a.convoInProgress||i.convoStarting!==a.convoStarting||i.convoInitializing!==a.convoInitializing||i.conversationSubstate!==a.conversationSubstate)return!1;const n=t.connection,s=e.connection;if(!n||!s)return!1;if(n.connected!==s.connected||n.disconnected!==s.disconnected)return!1;const o=t.flags,r=e.flags;return!(!o||!r)&&o.userSilenced===r.userSilenced&&o.isPageVisible===r.isPageVisible&&o.pendingStart===r.pendingStart}(a,e)&&(e=a,t(a,i))}));return()=>i.unsubscribe()}}class mt{constructor(t,e){if(!t||!e)throw new Error("Cannot initialize connectionManager due to missing bus or avatarOrchestrator");this.connectionModules={},this._allConnectionsReady=!1,this._wasAllReady=!1,this.isReconnecting=!1,this.bus=t,this.avatarOrchestrator=e,this._reconnectTimer=null,this._retryDelay=E?.connection?.reconnectInitialDelay,this._maxDelay=E?.connection?.reconnectMaxDelay,this._factor=E?.connection?.reconnectFactor,this._reconnectHandler=async()=>{try{this._resetBackoff(),await this.reconnectFailedModules(!0)}catch(t){}},this.bus.on("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler)}get allConnectionsReady(){return this._allConnectionsReady}set allConnectionsReady(t){this._allConnectionsReady=t}registerNewConnectionModule(t,e=null){try{const i=new G(t);e&&(i.reconnect=e),i.subscribe((()=>this.updateAvatarState())),this.connectionModules[t]=i}catch(i){}}registerConnectionModule(t){try{if(!t||!t.name||"function"!=typeof t.subscribe)throw new Error("Invalid module: must have 'name' property and 'subscribe' method");t.subscribe((()=>this.updateAvatarState())),this.connectionModules[t.name]=t}catch(e){}}setReconnectFunction(t,e){try{const i=this.connectionModules[t];if(!i)return;i.reconnect=e}catch(i){}}waitUntilReady(t=15e3){return new Promise(((e,i)=>{if(this._allConnectionsReady)return e(!0);let a,n;const s=()=>{a&&clearTimeout(a),n&&this.bus.off("connectionStateChanged",n)};a=setTimeout((()=>{s(),i(new Error("Connection timeout"))}),t),n=()=>{this._allConnectionsReady&&(s(),e(!0))},this.bus.on("connectionStateChanged",n)}))}updateAvatarState(){if(!this.avatarOrchestrator)return;const t=Object.values(this.connectionModules).every((t=>t.isConnected()));if(Object.values(this.connectionModules).some((t=>t.isFailed())),this.allConnectionsReady=t,this.bus.emit("connectionStateChanged"),t){if(this._clearReconnectTimer(),!this._wasAllReady)try{const t=this.avatarOrchestrator.getSnapshot?.();t?.matches?.("connection.disconnected"),this.avatarOrchestrator.sendEvent("RECONNECT"),(t?.matches?.("lifecycle.init.failed")||t?.matches?.("lifecycle.init.initializing"))&&this.avatarOrchestrator.sendEvent("CONNECT")}catch(e){}this._wasAllReady=!0}else{if(this._scheduleAutoReconnect(),this._wasAllReady)try{this.avatarOrchestrator.sendEvent("DISCONNECT")}catch(e){}this._wasAllReady=!1}}async reconnectFailedModules(t=!1){if(this.isReconnecting)return;this.isReconnecting=!0;const e=Object.values(this.connectionModules).filter((t=>t.isFailed()||t.isDisconnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(e),this.isReconnecting=!1,this.updateAvatarState(),t||this._stepBackoff()}async reconnectDisconnectedModules(){if(this.isReconnecting)return;this.isReconnecting=!0;const t=Object.values(this.connectionModules).filter((t=>!t.isConnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(t),this.isReconnecting=!1,this.updateAvatarState()}getConnectionReport(){let t=`System is ${this.allConnectionsReady?"Ready":"Not Ready"}\n\n`;for(const e of Object.values(this.connectionModules))t+=`${e.name}: ${e.isConnected()?"connected":"disconnected"}, \n`;return t}_scheduleAutoReconnect(){this._reconnectTimer||(this._reconnectTimer=setTimeout((async()=>{this._reconnectTimer=null,await this.reconnectFailedModules()}),this._retryDelay))}_clearReconnectTimer(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._resetBackoff()}_resetBackoff(){this._retryDelay=E?.connection?.reconnectInitialDelay}_stepBackoff(){this._retryDelay=Math.min(Math.ceil(this._retryDelay*this._factor),this._maxDelay)}destroy(){try{this._reconnectHandler&&(this.bus?.off("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler),this._reconnectHandler=null),this._clearReconnectTimer()}catch(t){}}}let gt,yt,vt;const ft=[0,0,0,0],bt=new g.Vector3,_t=new g.Vector3,xt=new g.Vector3,kt=new g.Vector3;new g.Plane,new g.Ray,new g.Euler;const St=new g.Quaternion,wt=new g.Quaternion,At=new g.Matrix4,Ct=new g.Matrix4;new g.Vector3;const Rt=new g.Vector3(0,0,1),Tt=new g.Vector3(1,0,0),Lt=new g.Vector3(0,1,0),zt=new g.Vector3(0,0,1);class It{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map((t=>t.name))}getValue(t,e){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const i=this.dict[t];let a;if("type"===e)a=i.type;else if("stiffness"===e)a=i.k.every((t=>t===i.k[0]))?i.k[0]:[...i.k];else if("damping"===e)a=i.c.every((t=>t===i.c[0]))?i.c[0]:[...i.c];else if("external"===e)a=i.ext<1?i.ext:null;else if("limits"===e)a=i.limits?.map((t=>null===t?null:[...t]));else if("deltaLocal"===e)a=i.dl?[...i.dl]:null;else if("excludes"===e)a=i.excludes?[...i.excludes.map((t=>{const e={bone:t.bone.name.slice(),radius:t.radius};return t.deltaLocal&&(e.deltaLocal=[...t.deltaLocal]),e}))]:null;else if("deltaWorld"===e)a=i.dw?[...i.dw]:null;else if("pivot"===e)a=i.pivot;else{if("helper"!==e)throw new Error("Unsupported property '"+e+"'.");a=i.helper}return a}setValue(t,e,i){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const a=this.dict[t];if("type"===e){if(!i)throw new Error("Parameter 'type' not set.");if("string"!=typeof i)throw new Error("Type must be a string.");switch(i){case"point":a.isPoint=!0,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!1;break;case"link":a.isPoint=!1,a.isX=!0,a.isY=!1,a.isZ=!0,a.isT=!1;break;case"mix1":a.isPoint=!1,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!1;break;case"mix2":a.isPoint=!1,a.isX=!0,a.isY=!1,a.isZ=!0,a.isT=!0;break;case"full":a.isPoint=!1,a.isX=!0,a.isY=!0,a.isZ=!0,a.isT=!0;break;default:throw new Error("Unknown type'"+i+"'.")}a.type=i.slice()}else if("stiffness"===e){if(!i)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(i)&&i>=0)a.k=Array(4).fill(i);else{if(!Array.isArray(i)||4!==i.length||!i.every((t=>t>=0)))throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.");a.k=[...i]}}else if("damping"===e){if(!i)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(i)&&i>=0)a.c=Array(4).fill(i);else{if(!Array.isArray(i)||4!==i.length||!i.every((t=>t>=0)))throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.");a.c=[...i]}}else if("external"===e)if(null==i)a.ext=1;else{if(!(!Number.isNaN(i)&&i>=0&&i<=1))throw new Error("External (if set) must be a number between [0,1].");a.ext=i}else if("limits"===e)if(null==i)a.limits=null;else{if(!Array.isArray(i)||4!==i.length)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!i.every((t=>null===t||Array.isArray(t)&&2===t.length&&(null===t[0]||!Number.isNaN(t[0]))&&(null===t[1]||!Number.isNaN(t)))))throw new Error("Limit values must be null or numbers.");a.limits=[i[0]?[...i[0]]:null,i[1]?[...i[1]]:null,i[2]?[...i[2]]:null,i[3]?[...i[3]]:null]}else if("excludes"===e){if(null==i)a.excludes=null;else{if(!Array.isArray(i))throw new Error("Excludes (if set) must null, or an array.");a.excludes=[],i.forEach(((t,e)=>{if(!t.bone)throw new Error("Bone not specified in #"+e+" exclude.");if("string"!=typeof t.bone||0===t.bone.length)throw new Error("Bone name must be a non-empty string in #"+e+" exclude.");const i=this.armature.getObjectByName(t.bone);if(!i)throw new Error("Bone '"+t.bone+"' not found in #"+e+" exclude.");if(Number.isNaN(t.radius)&&t.radius>=0)throw new Error("Radius must be a non-negative number in #"+e+" exclude.");const n={bone:i,radius:t.radius,radiusSq:t.radius*t.radius,deltaLocal:null};if(t.deltaLocal){if(!Array.isArray(t.deltaLocal)||3!==t.deltaLocal.length||t.deltaLocal.some((t=>Number.isNaN(t))))throw new Error("deltaLocal must be an array of three numbers in #"+e+" exclude.");n.deltaLocal=[...t.deltaLocal]}a.excludes.push(n)}))}this.showHelpers()}else if("helper"===e){if(null==i)a.helper=null;else{if(!1!==i&&!0!==i)throw new Error("Helper, if set, must be false or true.");a.helper=i}this.showHelpers()}else if("pivot"===e)if(null==i)a.pivot=null;else{if(!1!==i&&!0!==i)throw new Error("Pivot, if set, must be false or true.");if(!0===i&&0===a.type)throw new Error("Point type bone can't be a pivot.");a.pivot=i}else if("deltaLocal"===e)if(null==i)a.dl=null;else{if(!Array.isArray(i)||3!==i.length)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!i.every((t=>!Number.isNaN(t))))throw new Error("deltaLocal values must be numbers.");a.dl=[...i]}else{if("deltaWorld"!==e)throw new Error("Unsupported property "+e);if(null==i)a.dw=null;else{if(!Array.isArray(i)||3!==i.length)throw new Error("deltaWorld, is set, must be an array of three values.");if(!i.every((t=>!Number.isNaN(t))))throw new Error("deltaWorld values must be numbers.");a.dw=[...i]}}}getConfig(){return this.data.map((t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach((i=>{gt=this.getValue(t.name,i),gt&&(e[i]=gt)})),e}))}sortBones(){if(null===this.scene)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse((i=>{e.has(i)||(e.set(i,t),t++)})),this.data.sort(((t,i)=>e.get(t.bone)-e.get(i.bone))),this.data.forEach((t=>{gt=this.dict[t.boneParent.name],gt&&(gt.children||(gt.children=[]),gt.children.push(t))})),this.objectsUpdate=[];const i=new WeakSet,a=t=>t.parent?.isBone?[t,...a(t.parent)]:[t],n=t=>{a(t).forEach((t=>{i.has(t)||(this.objectsUpdate.push(t),i.add(t))}))};this.data.forEach((t=>{n(t.bone),t.excludes&&t.excludes.forEach((t=>{n(t.bone)}))})),this.objectsUpdate.sort(((t,i)=>e.get(t)-e.get(i)))}setup(t,e,i){this.dispose();const a=(t,e)=>{if(!t)throw this.dispose(),new Error(e)};a(t?.isScene,"First parameter must be Scene."),this.scene=t,a(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,a(Array.isArray(i),"Third parameter must be an array of bone configs."),this.config=i,this.config.forEach(((t,e)=>{const i="Config item #"+e+": ";a(t.bone,i+"Bone not specified.");const n=t.bone;a("string"==typeof n&&n.length>0,i+"Bone name must be a non-empty string.");const s=this.armature.getObjectByName(n);a(s,i+"Bone '"+n+"' not found."),a(s.parent?.isBone,i+"Bone must have a parent bone."),a(this.data.every((t=>t.bone!==s)),i+"Bone '"+n+"' already exists."),s.updateMatrixWorld(!0);const o={name:n,bone:s,boneParent:s.parent,vBasis:s.position.clone(),vWorld:s.parent.getWorldPosition(bt).clone(),qBasis:s.parent.quaternion.clone(),l:s.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};o.boneParent.matrixWorld.decompose(bt,St,xt),bt.copy(Rt).applyQuaternion(St).setY(0).normalize(),St.premultiply(wt.setFromUnitVectors(Rt,bt).invert()).normalize(),o.qWorldInverseYaw=St.clone().normalize(),this.data.push(o),this.dict[n]=o;try{this.setValue(n,"type",t.type),this.setValue(n,"stiffness",t.stiffness),this.setValue(n,"damping",t.damping),this.setValue(n,"external",t.external),this.setValue(n,"limits",t.limits),this.setValue(n,"excludes",t.excludes),this.setValue(n,"deltaLocal",t.deltaLocal),this.setValue(n,"deltaWorld",t.deltaWorld),this.setValue(n,"pivot",t.pivot),this.setValue(n,"helper",t.helper)}catch(r){a(!1,i+r)}})),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,i,a,n,s;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,a=this.objectsUpdate.length;e<a;e++)s=this.objectsUpdate[e],s.updateMatrix(),null===s.parent?s.matrixWorld.copy(s.matrix):s.matrixWorld.multiplyMatrices(s.parent.matrixWorld,s.matrix),s.matrixWorldNeedsUpdate=!1;for(e=0,a=this.data.length;e<a;e++){if(s=this.data[e],bt.copy(s.vWorld),At.copy(s.boneParent.matrixWorld),Ct.copy(At).invert(),s.vWorld.setFromMatrixPosition(At),bt.applyMatrix4(Ct),bt.length()>.5&&bt.setLength(.5),bt.applyQuaternion(s.bone.quaternion),ft[0]=bt.x,ft[1]=bt.y,ft[2]=-bt.z,ft[3]=bt.length()/3,s.children)for(i=0,n=s.children.length;i<n;i++)gt=s.children[i],ft[0]-=gt.v[0]*t/3,ft[1]-=gt.v[1]*t/3,ft[2]+=gt.v[2]*t/3,ft[3]-=gt.v[3]*t/3;if(gt=this.opt.sensitivityFactor,ft[0]*=s.ext*gt,ft[1]*=s.ext*gt,ft[2]*=s.ext*gt,ft[3]*=s.ext*gt,s.isX&&(gt=ft[0]/t,s.ea[0]=(gt-s.ev[0])/t,s.ev[0]=gt,s.a[0]=-s.k[0]*s.p[0]-s.c[0]*s.v[0]-s.ea[0],s.p[0]+=s.v[0]*t+s.a[0]*t*t/2+ft[0],gt=s.v[0]+s.a[0]*t/2,gt=-s.k[0]*s.p[0]-s.c[0]*gt-s.ea[0],s.v[0]=s.v[0]+(gt+s.a[0])*t/2),s.isY&&(gt=ft[1]/t,s.ea[1]=(gt-s.ev[1])/t,s.ev[1]=gt,s.a[1]=-s.k[1]*s.p[1]-s.c[1]*s.v[1]-s.ea[1],s.p[1]+=s.v[1]*t+s.a[1]*t*t/2+ft[1],gt=s.v[1]+s.a[1]*t/2,gt=-s.k[1]*s.p[1]-s.c[1]*gt-s.ea[1],s.v[1]=s.v[1]+(gt+s.a[1])*t/2),s.isZ&&(gt=ft[2]/t,s.ea[2]=(gt-s.ev[2])/t,s.ev[2]=gt,s.a[2]=-s.k[2]*s.p[2]-s.c[2]*s.v[2]-s.ea[2],s.p[2]+=s.v[2]*t+s.a[2]*t*t/2+ft[2],gt=s.v[2]+s.a[2]*t/2,gt=-s.k[2]*s.p[2]-s.c[2]*gt-s.ea[2],s.v[2]=s.v[2]+(gt+s.a[2])*t/2),s.isT&&(gt=ft[3]/t,s.ea[3]=(gt-s.ev[3])/t,s.ev[3]=gt,s.a[3]=-s.k[3]*s.p[3]-s.c[3]*s.v[3]-s.ea[3],s.p[3]+=s.v[3]*t+s.a[3]*t*t/2+ft[3],gt=s.v[3]+s.a[3]*t/2,gt=-s.k[3]*s.p[3]-s.c[3]*gt-s.ea[3],s.v[3]=s.v[3]+(gt+s.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(s.v[0]*=1e-4,s.p[0]*=1e-4,s.v[1]*=1e-4,s.p[1]*=1e-4,s.v[2]*=1e-4,s.p[2]*=1e-4,s.v[3]*=1e-4,s.p[3]*=1e-4),ft[0]=s.p[0],ft[1]=s.p[1],ft[2]=s.p[2],ft[3]=s.p[3],gt=this.opt.movementFactor,ft[0]*=gt,ft[1]*=gt,ft[2]*=gt,ft[3]*=gt,s.dl&&(gt=s.dl,ft[0]+=gt[0],ft[1]+=gt[1],ft[2]+=gt[2]),s.dw&&(gt=s.dw,bt.set(s.vBasis.x+ft[0],s.vBasis.y+ft[1],s.vBasis.z+ft[2]),bt.applyMatrix4(At),bt.x+=gt[0],bt.y+=gt[1],bt.z+=gt[2],bt.applyMatrix4(Ct),ft[0]+=bt.x-s.vBasis.x,ft[1]+=bt.y-s.vBasis.y,ft[2]+=bt.z-s.vBasis.z),s.limits&&this.opt.isLimits&&(gt=s.limits,gt[0]&&(null!==gt[0][0]&&ft[0]<gt[0][0]&&(ft[0]=gt[0][0]),null!==gt[0][1]&&ft[0]>gt[0][1]&&(ft[0]=gt[0][1])),gt[1]&&(null!==gt[1][0]&&ft[1]<gt[1][0]&&(ft[1]=gt[1][0]),null!==gt[1][1]&&ft[1]>gt[1][1]&&(ft[1]=gt[1][1])),gt[2]&&(null!==gt[2][0]&&ft[2]<gt[2][0]&&(ft[2]=gt[2][0]),null!==gt[2][1]&&ft[2]>gt[2][1]&&(ft[2]=gt[2][1])),gt[3]&&(null!==gt[3][0]&&ft[3]<gt[3][0]&&(ft[3]=gt[3][0]),null!==gt[3][1]&&ft[3]>gt[3][1]&&(ft[3]=gt[3][1]))),s.isPoint)s.bone.position.set(s.vBasis.x+ft[0],s.vBasis.y+ft[1],s.vBasis.z-ft[2]);else if(s.boneParent.quaternion.copy(s.qBasis),s.pivot&&this.opt.isPivots&&(s.boneParent.updateWorldMatrix(!1,!1),s.boneParent.matrixWorld.decompose(bt,St,xt),bt.copy(Rt).applyQuaternion(St).setY(0).normalize(),St.premultiply(wt.setFromUnitVectors(Rt,bt).invert()).normalize(),s.boneParent.quaternion.multiply(St.invert()),s.boneParent.quaternion.multiply(s.qWorldInverseYaw)),s.isZ&&(gt=Math.atan(ft[0]/s.l),St.setFromAxisAngle(zt,-gt),s.boneParent.quaternion.multiply(St)),s.isY&&(gt=s.l/3,gt*=Math.tanh(ft[1]/gt),s.bone.position.setLength(s.l+gt)),s.isX&&(gt=Math.atan(ft[2]/s.l),St.setFromAxisAngle(Tt,-gt),s.boneParent.quaternion.multiply(St)),s.isT&&(gt=1.5*Math.tanh(1.5*ft[3]),St.setFromAxisAngle(Lt,-gt),s.boneParent.quaternion.multiply(St)),s.boneParent.updateWorldMatrix(!1,!0),s.excludes&&this.opt.isExcludes)for(i=0,n=s.excludes.length;i<n;i++)gt=s.excludes[i],xt.set(0,0,0),gt.deltaLocal&&(xt.x+=gt.deltaLocal[0],xt.y+=gt.deltaLocal[1],xt.z+=gt.deltaLocal[2]),xt.applyMatrix4(gt.bone.matrixWorld),Ct.copy(s.boneParent.matrixWorld).invert(),xt.applyMatrix4(Ct),bt.copy(s.bone.position),bt.distanceToSquared(xt)>=gt.radiusSq||(vt=bt.length(),yt=xt.length(),yt>gt.radius+vt||yt<Math.abs(gt.radius-vt)||(yt=(yt*yt+vt*vt-gt.radiusSq)/(2*yt),xt.normalize(),kt.copy(xt).multiplyScalar(yt),yt=Math.sqrt(vt*vt-yt*yt),bt.subVectors(bt,kt).projectOnPlane(xt).normalize().multiplyScalar(yt),_t.subVectors(s.vBasis,kt).projectOnPlane(xt).normalize(),vt=_t.dot(bt),vt<0&&(vt=Math.sqrt(yt*yt-vt*vt),_t.multiplyScalar(vt),bt.add(_t)),bt.add(kt).normalize(),xt.copy(s.bone.position).normalize(),St.setFromUnitVectors(xt,bt),s.boneParent.quaternion.premultiply(St),s.boneParent.updateWorldMatrix(!1,!0)))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=void 0===t?this.helpers.isShowAll:!0===t,gt=this.helpers,this.data.forEach((t=>{(this.helpers.isShowAll||!0===t.helper)&&(gt.points.bones.push(t.bone),gt.points.pivots.push(t.pivot),0!==t.type&&gt.lines.bones.push(t.bone),t.excludes&&t.excludes.forEach((t=>{let e=!1;for(let i=0;i<gt.excludes.bones.length;i++)if(gt.excludes.bones[i]===t.bone&&gt.excludes.radii[i]===t.radius&&(null!==gt.excludes.deltaLocals[i]||null===t.deltaLocal)&&!(null!==gt.excludes.deltaLocals[i]&&null===t.deltaLocal||null!==gt.excludes.deltaLocals[i]&&gt.excludes.deltaLocals[i].some(((e,i)=>e!==t.deltaLocal[i])))){e=!0;break}e||(gt.excludes.bones.push(t.bone),gt.excludes.radii.push(t.radius),gt.excludes.deltaLocals.push(t.deltaLocal?[...t.deltaLocal]:null),gt.excludes.objects.push(null))})))})),gt=this.helpers.excludes,this.opt.isExcludes&&gt.bones.length&&gt.bones.forEach(((t,e)=>{const i=new g.SphereGeometry(gt.radii[e],6,6),a=new g.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});gt.objects[e]=new g.Mesh(i,a),gt.objects[e].renderOrder=997,t.add(gt.objects[e]),gt.deltaLocals[e]&&gt.objects[e].position.set(gt.deltaLocals[e][0],gt.deltaLocals[e][1],gt.deltaLocals[e][2])})),gt=this.helpers.points,gt.bones.length){this.helpers.isActive=!0;const t=new g.BufferGeometry,e=gt.bones.map((t=>[0,0,0])).flat();t.setAttribute("position",new g.Float32BufferAttribute(e,3));const i=new g.Color(this.opt.helperBoneColor1),a=new g.Color(this.opt.helperBoneColor2),n=gt.pivots.map((t=>t&&this.opt.isPivots?[a.r,a.g,a.b]:[i.r,i.g,i.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(n,3));const s=new g.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});gt.object=new g.Points(t,s),gt.object.renderOrder=998,gt.object.matrix=this.armature.matrixWorld,gt.object.matrixAutoUpdate=!1,this.scene.add(gt.object)}if(gt=this.helpers.lines,gt.bones.length){const t=new g.BufferGeometry,e=gt.bones.map((t=>[0,0,0,0,0,0])).flat();t.setAttribute("position",new g.Float32BufferAttribute(e,3));const i=new g.Color(this.opt.helperLinkColor1),a=new g.Color(this.opt.helperLinkColor2),n=gt.bones.map((t=>[i.r,i.g,i.b,a.r,a.g,a.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(n,3));const s=new g.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});gt.object=new g.LineSegments(t,s),gt.object.renderOrder=999,gt.object.matrix=this.armature.matrixWorld,gt.object.matrixAutoUpdate=!1,this.scene.add(gt.object)}}updateHelpers(){if(gt=this.helpers.points,gt.bones.length){Ct.copy(this.armature.matrixWorld).invert();const t=gt.object.geometry.getAttribute("position");for(let e=0,i=gt.bones.length;e<i;e++)At.multiplyMatrices(Ct,gt.bones[e].matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(e,bt.x,bt.y,bt.z);t.needsUpdate=!0,gt.object.updateMatrixWorld()}if(gt=this.helpers.lines,gt.bones.length){Ct.copy(this.armature.matrixWorld).invert();const t=gt.object.geometry.getAttribute("position");for(let e=0,i=0,a=gt.bones.length;e<a;e++,i+=2)At.multiplyMatrices(Ct,gt.bones[e].matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(i,bt.x,bt.y,bt.z),At.multiplyMatrices(Ct,gt.bones[e].parent.matrixWorld),bt.setFromMatrixPosition(At),t.setXYZ(i+1,bt.x,bt.y,bt.z);t.needsUpdate=!0,gt.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach((t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)})),gt=this.helpers.excludes,gt.objects.forEach(((t,e)=>{t&&(gt.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())})),gt.bones=[],gt.deltaLocals=[],gt.radii=[],gt.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const e=this.data[t];e.bone.position.copy(e.vBasis),e.boneParent.quaternion.copy(e.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}let Mt=null;const Et=new g.Quaternion,Pt=new g.Euler,Dt=new g.Vector3,Ht=new g.Vector3,Ot=new g.Box3;new g.Matrix4,new g.Matrix4,new g.Vector3,new g.Vector3(0,0,1);const Ft=new g.Vector3(1,0,0);new g.Vector3(0,1,0),new g.Vector3(0,0,1);class Bt{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:0,mixerGainSpeech:null,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:2,lightDirectColor:8947882,lightDirectIntensity:30,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.2,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.5,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new x,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach((t=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach((e=>{this.poseDelta.props[t+e+".quaternion"]={x:0,y:0,z:0}})),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((e=>{this.poseDelta.props[t+e+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[t+e+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[t+e+"3.quaternion"]={x:0,y:0,z:0}}))}));const i=new Set;Object.values(this.poseTemplates).forEach((t=>{Object.keys(this.propsToThreeObjects(t.props)).forEach((t=>i.add(t)))})),Object.keys(this.poseDelta.props).forEach((t=>{i.add(t)})),this.posePropNames=[...i],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:.1},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:.1},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,(t=>{t.alt[0].delay[0]=t.alt[1].delay[0]=2e3})),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"šŸ˜":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"šŸ™‚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"šŸ™ƒ":{link:"šŸ™‚"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"šŸ˜‡":{link:"😊"},"šŸ˜€":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜„":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜†":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"šŸ˜":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"šŸ˜‹":{link:"šŸ˜"},"šŸ˜›":{link:"šŸ˜"},"šŸ˜›":{link:"šŸ˜"},"😜":{link:"šŸ˜"},"🤪":{link:"šŸ˜"},"šŸ˜‚":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"šŸ˜‚"},"šŸ˜…":{link:"šŸ˜‚"},"šŸ˜‰":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🄺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"šŸ˜ž":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"šŸ˜”":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"ā˜¹ļø":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🄰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"šŸ˜":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"šŸ˜"},"😔":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"šŸ˜’":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"šŸ™„":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"šŸ¤”":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"šŸ‘€":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😓":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"āœ‹":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"šŸ‘‹":{link:"āœ‹"},"šŸ‘":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"šŸ‘Ž":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"šŸ‘Œ":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"šŸ¤·ā€ā™‚ļø":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"šŸ¤·ā€ā™€ļø":{link:"šŸ¤·ā€ā™‚ļø"},"🤷":{link:"šŸ¤·ā€ā™‚ļø"},"šŸ™":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:t=>Math.max(t,(this.mtAvatar.eyesLookDown?.value||0+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:t=>Math.max(t,(this.mtAvatar.eyesLookDown?.value||0+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach((t=>this.lipsyncGetProcessor(t))),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath,this.b64Lookup="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let n=0;n<64;n++)this.b64Lookup["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(n)]=n;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let t=new Audio;if(t.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else{if(!t.canPlayType("audio/mp3"))throw new Error("There was no support for either OGG or MP3 audio.");this.ttsAudioEncoding="MP3"}}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new g.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=g.SRGBColorSpace,this.renderer.toneMapping=g.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new g.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new g.Scene,this.lightAmbient=new g.AmbientLight(new g.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new g.DirectionalLight(new g.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new g.SpotLight(new g.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const t=new g.PMREMGenerator(this.renderer);t.compileEquirectangularShader(),this.scene.environment=t.fromScene(new _).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new y(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new g.SkinnedMesh;const a=[];Object.entries({LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"}).forEach(((t,e)=>{const i=new g.Bone;i.name=t[0],t[1]?this.ikMesh.getObjectByName(t[1]).add(i):this.ikMesh.add(i),a.push(i)})),this.ikMesh.bind(new g.Skeleton(a)),this.dynamicbones=new It,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&"closed"!==this.audioCtx.state&&this.audioCtx.close(),this.audioCtx=t?new AudioContext({sampleRate:t}):new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){}this.streamWorkletNode=null}}valueFn(t){return"function"==typeof t?t():t}deepCopy(t,e=null){const i=JSON.parse(JSON.stringify(t));return e&&"function"==typeof e&&e(i),i}b64ToArrayBuffer(t){let e=3*t.length/4;"="===t[t.length-1]&&(e--,"="===t[t.length-2]&&e--);const i=new ArrayBuffer(e),a=new Uint8Array(i);let n,s,o,r,c,h=0;for(n=0;n<t.length;n+=4)s=this.b64Lookup[t.charCodeAt(n)],o=this.b64Lookup[t.charCodeAt(n+1)],r=this.b64Lookup[t.charCodeAt(n+2)],c=this.b64Lookup[t.charCodeAt(n+3)],a[h++]=s<<2|o>>4,a[h++]=(15&o)<<4|r>>2,a[h++]=(3&r)<<6|63&c;return i}concatArrayBuffers(t){if(1===t.length)return t[0];let e=0;for(let s=0;s<t.length;s++)e+=t[s].byteLength;let i=new ArrayBuffer(e),a=new Uint8Array(i),n=0;for(let s=0;s<t.length;s++)a.set(new Uint8Array(t[s]),n),n+=t[s].byteLength;return i}pcmToAudioBuffer(t){const e=new Int16Array(t),i=new Float32Array(e.length);for(let n=0;n<e.length;n++)i[n]=e[n]>=32768?-(65536-e[n])/32768:e[n]/32767;const a=this.audioCtx.createBuffer(1,i.length,this.opt.pcmSampleRate);return a.copyToChannel(i,0,0),a}propsToThreeObjects(t){const e={};for(let[i,a]of Object.entries(t)){const t=i.split(".");let n=Array.isArray(a.x)?this.gaussianRandom(...a.x):a.x,s=Array.isArray(a.y)?this.gaussianRandom(...a.y):a.y,o=Array.isArray(a.z)?this.gaussianRandom(...a.z):a.z;"position"===t[1]||"scale"===t[1]?e[i]=new g.Vector3(n,s,o):"rotation"===t[1]?(i=t[0]+".quaternion",e[i]=(new g.Quaternion).setFromEuler(new g.Euler(n,s,o,"XYZ")).normalize()):"quaternion"===t[1]&&(e[i]=new g.Quaternion(n,s,o,a.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach((e=>{t.material[e]&&null!==t.material[e]&&"function"==typeof t.material[e].dispose&&t.material[e].dispose()})),t.material.dispose())}addMixedMorphTarget(t,e,i,a=!1){t.forEach((t=>{if(!a&&t.morphTargetDictionary.hasOwnProperty(e))return;const n=t.geometry;let s=null,o=null;for(const[e,a]of Object.entries(i))if(t.morphTargetDictionary.hasOwnProperty(e)){const i=t.morphTargetDictionary[e],r=n.morphAttributes.position[i],c=n.morphAttributes.normal?.[i];s||(s=new g.Float32BufferAttribute(3*r.count,3),c&&(o=new g.Float32BufferAttribute(3*r.count,3)));for(let t=0;t<r.count;t++){const e=s.getX(t)+r.getX(t)*a,i=s.getY(t)+r.getY(t)*a,n=s.getZ(t)+r.getZ(t)*a;s.setXYZ(t,e,i,n)}if(c)for(let t=0;t<r.count;t++){const e=o.getX(t)+c.getX(t)*a,i=o.getY(t)+c.getY(t)*a,n=o.getZ(t)+c.getZ(t)*a;o.setXYZ(t,e,i,n)}}if(s){n.morphAttributes.position.push(s),o&&n.morphAttributes.normal.push(o);const i=n.morphAttributes.position.length-1;t.morphTargetInfluences[i]=0,t.morphTargetDictionary[e]=i}}))}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const i=new v;if(this.dracoEnabled){const t=new f;t.setDecoderPath(this.dracoDecoderPath),i.setDRACOLoader(t)}let a=await i.loadAsync(t.url,e);const n=[this.opt.modelRoot];if(this.posePropNames.forEach((t=>n.push(t.split(".")[0]))),n.forEach((t=>{if(!a.scene.getObjectByName(t))throw new Error("Avatar object "+t+" not found")})),this.stop(),this.avatar=t,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=a.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=a.animations,this.userData=a.userData,this.morphs=[],this.armature.traverse((t=>{t.morphTargetInfluences&&t.morphTargetInfluences.length&&t.morphTargetDictionary&&this.morphs.push(t),t.frustumCulled=!1})),0===this.morphs.length)throw new Error("Blend shapes not found");const s=new Set(this.mtCustoms);this.morphs.forEach((t=>{Object.keys(t.morphTargetDictionary).forEach((t=>s.add(t)))})),this.mtExtras.forEach((t=>{s.has(t.key)||(this.addMixedMorphTarget(this.morphs,t.key,t.mix),s.add(t.key))}));const o={};if(s.forEach((t=>{o[t]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(t)?this.mtMinExceptions[t]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(t)?this.mtMaxExceptions[t]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(t)?this.mtAccExceptions[t]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(t)?this.mtMaxVExceptions[t]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(t)?this.mtLimits[t]:null,onchange:this.mtOnchange.hasOwnProperty(t)?this.mtOnchange[t]:null,baseline:this.avatar.baseline?.hasOwnProperty(t)?this.avatar.baseline[t]:this.mtBaselineExceptions.hasOwnProperty(t)?this.mtBaselineExceptions[t]:this.mtBaselineDefault,ms:[],is:[]},o[t].value=o[t].baseline,o[t].applied=o[t].baseline;const e=this.mtAvatar[t];e&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach((i=>{o[t][i]=e[i]})),this.morphs.forEach((e=>{const i=e.morphTargetDictionary[t];void 0!==i&&(o[t].ms.push(e.morphTargetInfluences),o[t].is.push(i),e.morphTargetInfluences[i]=o[t].applied)}))})),this.mtAvatar=o,this.poseAvatar={props:{}},this.posePropNames.forEach((t=>{const e=t.split("."),i=this.armature.getObjectByName(e[0]);this.poseAvatar.props[t]=i[e[1]],this.poseBase.props.hasOwnProperty(t)?this.poseAvatar.props[t].copy(this.poseBase.props[t]):this.poseBase.props[t]=this.poseAvatar.props[t].clone(),this.poseDelta.props.hasOwnProperty(t)&&!this.poseTarget.props.hasOwnProperty(t)&&(this.poseTarget.props[t]=this.poseAvatar.props[t].clone()),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=2e3})),this.ikMesh.traverse((t=>{t.isBone&&t.position.copy(this.armature.getObjectByName(t.name).position)})),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(a.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(c){}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const r=new g.Vector3;this.objectLeftEye.getWorldPosition(r),this.avatarHeight=r.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if("full"!==(t=t||this.viewName)&&"upper"!==t&&"head"!==t&&"mid"!==t)return;if(!this.armature)return void(this.opt.cameraView=t);if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const i=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,a=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,n=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,s=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,o=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,r=this.camera.fov*(Math.PI/180);let c=-i*Math.tan(r/2),h=(1-a)*Math.tan(r/2),l=n;switch(this.viewName){case"head":l+=2,h=h*l+4*this.avatarHeight/5;break;case"upper":l+=4.5,h=h*l+2*this.avatarHeight/3;break;case"mid":l+=8,h=h*l+this.avatarHeight/3;break;default:l+=12,h*=l}c*=l,this.controlsEnd=new g.Vector3(c,h,0),this.cameraEnd=new g.Vector3(c,h,l).applyEuler(new g.Euler(s,o,0)),null===this.cameraClock&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||((t=t||{}).hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new g.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=0!==t.lightAmbientIntensity),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new g.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=0!==t.lightDirectIntensity),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new g.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=0!==t.lightSpotIntensity),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new g.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer.render(this.scene,this.camera)}onResize(){this.isAvatarOnly||(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,i]of Object.entries(this.poseTarget.props)){const a=this.poseAvatar.props[e];if(a){let n=(t-i.t)/i.d;n>1||!this.poseBase.props.hasOwnProperty(e)?a.copy(i):a.isQuaternion?a.copy(this.poseBase.props[e].slerp(i,this.easing(n))):a.isVector3&&a.copy(this.poseBase.props[e].lerp(i,this.easing(n)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(0===e.x&&0===e.y&&0===e.z)continue;Pt.set(e.x,e.y,e.z);const i=this.poseAvatar.props[t];i.isQuaternion?(Et.setFromEuler(Pt),i.multiply(Et)):i.isVector3&&i.add(Pt)}}updateMorphTargets(t){for(let[e,i]of Object.entries(this.mtAvatar)){if(!i.needsUpdate)continue;let a=null,n=null;if(null!==i.fixed){if(a=i.fixed,i.system=null,i.systemd=null,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.value===a){i.needsUpdate=!1;continue}}else null!==i.realtime?(i.ref=null,i.base=null,n=i.realtime):null!==i.system?(a=i.system,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,null!==i.systemd?0===i.systemd?(a=null,i.system=null,i.systemd=null):(i.systemd-=t,i.systemd<0&&(i.systemd=0),i.value===a&&(a=null)):i.value===a&&(a=null,i.system=null)):null!==i.newvalue?(i.ref=null,i.base=null,n=i.newvalue,i.newvalue=null):null!==i.base?(a=i.base,i.ref=null,i.value===a&&(a=null,i.base=null,i.needsUpdate=!1)):(i.ref=null,null!==i.baseline&&i.value!==i.baseline?(a=i.baseline,i.base=i.baseline):i.needsUpdate=!1);if(null!==a){let e=a-i.value;e>=0?e<.005?(n=a,i.v=0):(i.v<i.maxv&&(i.v+=i.acc*t),n=i.v>=0?i.value+e*(1-Math.exp(-i.v*t)):i.value+i.v*t*(1-Math.exp(i.v*t))):e>-.005?(n=a,i.v=0):(i.v>-i.maxv&&(i.v-=i.acc*t),n=i.v>=0?i.value+i.v*t*(1-Math.exp(-i.v*t)):i.value+e*(1-Math.exp(i.v*t)))}if(null!==i.limit){if(null!==n&&n!==i.value&&(i.value=n,null!==i.onchange&&i.onchange(n)),n=i.limit(i.value),n===i.applied)continue}else{if(null===n||n===i.value)continue;i.value=n,null!==i.onchange&&i.onchange(n)}switch(i.applied=n,i.applied<i.min&&(i.applied=i.min),i.applied>i.max&&(i.applied=i.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=i.applied/2,this.poseDelta.props["Spine.quaternion"].x=i.applied/8,this.poseDelta.props["Hips.quaternion"].x=i.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=i.applied/2,this.poseDelta.props["Spine.quaternion"].y=i.applied/2,this.poseDelta.props["Hips.quaternion"].y=i.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=i.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=i.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=i.applied/12,this.poseDelta.props["Spine.quaternion"].z=i.applied/12,this.poseDelta.props["Hips.quaternion"].z=i.applied/24;break;case"handFistLeft":case"handFistRight":const t=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(((e,a)=>{0===a?(this.poseDelta.props[t+e+"1.quaternion"].x=0,this.poseDelta.props[t+e+"2.quaternion"].z=("Left"===t?-1:1)*i.applied,this.poseDelta.props[t+e+"3.quaternion"].z=("Left"===t?-1:1)*i.applied):(this.poseDelta.props[t+e+"1.quaternion"].x=i.applied,this.poseDelta.props[t+e+"2.quaternion"].x=1.5*i.applied,this.poseDelta.props[t+e+"3.quaternion"].x=1.5*i.applied)}));break;case"chestInhale":const a=i.applied/20,n={x:a,y:a/2,z:3*a},s={x:1/(1+a)-1,y:1/(1+a/2)-1,z:1/(1+3*a)-1};this.poseDelta.props["Spine1.scale"]=n,this.poseDelta.props["Neck.scale"]=s,this.poseDelta.props["LeftArm.scale"]=s,this.poseDelta.props["RightArm.scale"]=s;break;default:for(let e=0,o=i.ms.length;e<o;e++)i.ms[e][i.is[e]]=i.applied}}}getPoseString(t,e=1e3){let i="{";return Object.entries(t).forEach(((t,a)=>{const n=t[0].split(".");if("position"===n[1]||"rotation"===n[1]||"quaternion"===n[1]){const s="quaternion"===n[1]?n[0]+".rotation":t[0],o=t[1].isQuaternion?(new g.Euler).setFromQuaternion(t[1]):t[1];i+=(a?", ":"")+"'"+s+"':{",i+="x:"+Math.round(o.x*e)/e,i+=", y:"+Math.round(o.y*e)/e,i+=", z:"+Math.round(o.z*e)/e,i+="}"}})),i+="}",i}getPoseTemplateProp(t){const e=t.split(".");let i=e[0]+"."+("rotation"===e[1]?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(i))return this.gesture[i].clone();{let t,a=e[0]+"."+("quaternion"===e[1]?"rotation":e[1]);if(this.poseWeightOnLeft||(a.startsWith("Left")?(a="Right"+a.substring(4),i="Right"+i.substring(4)):a.startsWith("Right")&&(a="Left"+a.substring(5),i="Left"+i.substring(5))),this.poseTarget.template.props.hasOwnProperty(i)){const e={};e[i]=this.poseTarget.template.props[i],t=this.propsToThreeObjects(e)[i]}else if(this.poseTarget.template.props.hasOwnProperty(a)){const e={};e[a]=this.poseTarget.template.props[a],t=this.propsToThreeObjects(e)[i]}return t&&!this.poseWeightOnLeft&&t.isQuaternion&&(t.x*=-1,t.w*=-1),t}}mirrorPose(t){const e={};for(let[i,a]of Object.entries(t))a.isQuaternion&&(i.startsWith("Left")?i="Right"+i.substring(4):i.startsWith("Right")&&(i="Left"+i.substring(5)),a.x*=-1,a.w*=-1),e[i]=a.clone(),e[i].t=a.t,e[i].d=a.d;return e}poseFactory(t,e=2e3){const i={template:t,props:this.propsToThreeObjects(t.props)};for(const[a,n]of Object.entries(i.props)){if(this.opt.modelMovementFactor<1&&t.standing&&("Hips.quaternion"===a||"Spine.quaternion"===a||"Spine1.quaternion"===a||"Spine2.quaternion"===a||"Neck.quaternion"===a||"LeftUpLeg.quaternion"===a||"LeftLeg.quaternion"===a||"RightUpLeg.quaternion"===a||"RightLeg.quaternion"===a)){const t=this.poseStraight[a],e=n.angleTo(t);n.rotateTowards(t,(1-this.opt.modelMovementFactor)*e)}n.t=this.animClock,n.d=e}return i}setPoseFromTemplate(t,e=2e3){const i=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),a=t&&t===this.poseCurrentTemplate,n=this.poseWeightOnLeft;let s=i?1e3:e;if(i?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout((()=>{this.setPoseFromTemplate(t,e)}),s)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,s),this.poseWeightOnLeft=!0,(!a&&!n||a&&n)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[o,r]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(o)&&(this.poseTarget.props[o].copy(r),this.poseTarget.props[o].t=r.t,this.poseTarget.props[o].d=r.d);Object.keys(this.poseDelta.props).forEach((t=>{this.poseTarget.props.hasOwnProperty(t)||(this.poseTarget.props[t]=this.poseBase.props[t].clone(),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=s)}))}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,i=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:i,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let t=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?t=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(t=this.avatar.baseline[e]),this.setBaselineValue(e,t)}this.mood.anims.forEach((t=>{let e=this.animQueue.findIndex((e=>e.template.name===t.name));-1!==e&&this.animQueue.splice(e,1),this.animQueue.push(this.animFactory(t,-1))}))}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if("eyesRotateY"===t){const t=this.getBaselineValue("eyeLookOutLeft");if(void 0===t)return;const e=this.getBaselineValue("eyeLookInLeft");if(void 0===e)return;if(void 0===this.getBaselineValue("eyeLookOutRight"))return;if(void 0===this.getBaselineValue("eyeLookInRight"))return;return t-e}if("eyesRotateX"===t){const t=this.getBaselineValue("eyesLookDown");if(void 0===t)return;const e=this.getBaselineValue("eyesLookUp");if(void 0===e)return;return t-e}return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){"eyesRotateY"===t?(this.setBaselineValue("eyeLookOutLeft",null===e?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",null===e?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",null===e?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",null===e?null:e>0?e:0)):"eyesRotateX"===t?(this.setBaselineValue("eyesLookDown",null===e?null:e>0?e:0),this.setBaselineValue("eyesLookUp",null===e?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if("eyesRotateY"===t){const t=this.getFixedValue("eyeLookOutLeft");if(null===t)return null;const e=this.getFixedValue("eyeLookInLeft");return null===e||null===this.getFixedValue("eyeLookOutRight")||null===this.getFixedValue("eyeLookInRight")?null:t-e}if("eyesRotateX"===t){const t=this.getFixedValue("eyesLookDown");if(null===t)return null;const e=this.getFixedValue("eyesLookUp");return null===e?null:t-e}return this.mtAvatar[t]?.fixed}setFixedValue(t,e,i=null){"eyesRotateY"===t?(this.setFixedValue("eyeLookOutLeft",null===e?null:e>0?e:0,i),this.setFixedValue("eyeLookInLeft",null===e?null:e>0?0:-e,i),this.setFixedValue("eyeLookOutRight",null===e?null:e>0?0:-e,i),this.setFixedValue("eyeLookInRight",null===e?null:e>0?e:0,i)):"eyesRotateX"===t?(this.setFixedValue("eyesLookDown",null===e?null:e>0?e:0,i),this.setFixedValue("eyesLookUp",null===e?null:e>0?0:-e,i)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,i=1,a=1,n=!1){const s={template:t,ts:[0],vs:{}};let o=t;for(;;)if(o.hasOwnProperty(this.stateName))o=o[this.stateName];else if(o.hasOwnProperty(this.moodName))o=o[this.moodName];else if(o.hasOwnProperty(this.poseName))o=o[this.poseName];else if(o.hasOwnProperty(this.viewName))o=o[this.viewName];else if(this.avatar.body&&o.hasOwnProperty(this.avatar.body))o=o[this.avatar.body];else{if(!o.hasOwnProperty("alt"))break;{let t=o.alt[0];if(o.alt.length>1){const e=Math.random();let i=0;for(let a=0;a<o.alt.length;a++){let n=this.valueFn(o.alt[a].p);if(i+=void 0===n?(1-i)/(o.alt.length-1-a):n,e<i){t=o.alt[a];break}}}o=t}}let r=this.valueFn(o.delay)||0;if(Array.isArray(r)&&(r=this.gaussianRandom(...r)),o.hasOwnProperty("dt"))o.dt.forEach(((t,e)=>{let i=this.valueFn(t);Array.isArray(i)&&(i=this.gaussianRandom(...i)),s.ts[e+1]=s.ts[e]+i}));else{let t=Object.values(o.vs).reduce(((t,e)=>e.length>t?e.length:t),0);s.ts=Array(t+1).fill(0)}s.ts=n?s.ts.map((t=>r+t*i)):s.ts.map((t=>this.animClock+r+t*i));for(let[c,h]of Object.entries(o.vs)){const t=this.getBaselineValue(c),e=h.map((e=>null===(e=this.valueFn(e))?null:"function"==typeof e?e:"string"==typeof e||e instanceof String?e.slice():Array.isArray(e)?"gesture"===c?e.slice():(void 0===t?0:t)+a*this.gaussianRandom(...e):"boolean"==typeof e?e:e instanceof Object&&e.constructor===Object?Object.assign({},e):(void 0===t?0:t)+a*e));"eyesRotateY"===c?(s.vs.eyeLookOutLeft=[null,...e.map((t=>t>0?t:0))],s.vs.eyeLookInLeft=[null,...e.map((t=>t>0?0:-t))],s.vs.eyeLookOutRight=[null,...e.map((t=>t>0?0:-t))],s.vs.eyeLookInRight=[null,...e.map((t=>t>0?t:0))]):"eyesRotateX"===c?(s.vs.eyesLookDown=[null,...e.map((t=>t>0?t:0))],s.vs.eyesLookUp=[null,...e.map((t=>t>0?0:-t))]):s.vs[c]=[null,...e]}for(let c of Object.keys(s.vs))for(;s.vs[c].length<=s.ts.length;)s.vs[c].push(s.vs[c][s.vs[c].length-1]);return t.hasOwnProperty("mood")&&(s.mood=this.valueFn(t.mood).slice()),e&&(s.loop=e),s}valueAnimationSeq(t,e,i,a,n,s=null){t=this.valueFn(t),n<i&&(n=i),n>a&&(n=a);let o=((e=this.valueFn(e))-t)/(a-i);return s&&(o*=s((n-i)/(a-i))),o*n+(t-o*i)}gaussianRandom(t,e,i=1,a=5){let n=0;for(let s=0;s<a;s++)n+=Math.random();return t+Math.pow(n/a,i)*(e-t)}sigmoidFactory(t){function e(e){return 1/(1+Math.exp(-t*e))-.5}var i=.5/e(1);return function(t){return i*e(2*Math.max(Math.min(t,1),0)-1)+.5}}convertRange(t,e,i){return(t-e[0])*(i[1]-i[0])/(e[1]-e[0])+i[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e/=this.animSlowdownRate,this.animClock+=e;let i,a,n,s,o=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),i=2,n=10;i<n;i++)this.volumeFrequencyData[i]>o&&(o=this.volumeFrequencyData[i]);this.listeningVolume=(this.listeningVolume+o)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(o=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),i=2,n=10;i<n;i++)this.volumeFrequencyData[i]>o&&(o=this.volumeFrequencyData[i]);let r=null,c=null;const h=[];for(i=0,n=this.animQueue.length;i<n;i++){const t=this.animQueue[i];if(!(this.animClock<t.ts[0])){for(a=t.ndx||0,s=t.ts.length;a<s&&!(this.animClock<t.ts[a]);a++)for(let[e,i]of Object.entries(t.vs))if(this.mtAvatar.hasOwnProperty(e)){if(null===i[a+1])continue;const n=this.mtAvatar[e];if(null===i[a]&&(i[a]=n.value),a===s-1)n.newvalue=i[a];else{n.newvalue=i[a+1];const s=t.ts[a+1]-t.ts[a];let o=1;s>1e-4&&(o=(this.animClock-t.ts[a])/s),o<1&&(n.easing&&(o=n.easing(o)),n.newvalue=(1-o)*i[a]+o*n.newvalue),n.ref&&n.ref!==t.vs&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=t.vs}if(o)switch(e){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":n.newvalue*=1+o/255-.5}n.needsUpdate=!0}else"eyeContact"===e&&null!==i[a]&&!1!==r?r=Boolean(i[a]):"headMove"===e&&null!==i[a]&&!1!==c?0===i[a]?c=!1:(Math.random()<i[a]&&(c=!0),i[a]=null):null!==i[a]&&(h.push({mt:e,val:i[a]}),i[a]=null);a===s?(t.hasOwnProperty("mood")&&this.setMood(t.mood),t.loop?(s=!this.isSpeaking||"head"!==t.template.name&&"eyes"!==t.template.name?1:4,this.animQueue[i]=this.animFactory(t.template,t.loop>0?t.loop-1:t.loop,1,1/s)):(this.animQueue.splice(i--,1),n--)):t.ndx=a-1}}for(let l=0,d=h.length;l<d;l++)switch(a=h[l].val,h[l].mt){case"speak":this.speakText(a);break;case"subtitles":this.onSubtitles&&"function"==typeof this.onSubtitles&&this.onSubtitles(a);break;case"pose":this.poseName=a,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...a);break;case"function":a&&"function"==typeof a&&a();break;case"moveto":Object.entries(a.props).forEach((t=>{t[1]?this.poseTarget.props[t[0]].copy(t[1]):this.poseTarget.props[t[0]].copy(this.getPoseTemplateProp(t[0])),this.poseTarget.props[t[0]].t=this.animClock,this.poseTarget.props[t[0]].d=t[1]&&t[1].d?t[1].d:t.duration||2e3}));break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},a.x?new g.Vector3(a.x,a.y,a.z):null,!0,a.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},a.x?new g.Vector3(a.x,a.y,a.z):null,!0,a.d)}if((r||c)&&(Pt.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),Pt.x=Math.max(-.9,Math.min(.9,2*Pt.x-.5)),Pt.y=Math.max(-.9,Math.min(.9,-2.5*Pt.y)),r?(Object.assign(this.mtAvatar.eyesLookDown,{system:Pt.x<0?-Pt.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:Pt.x<0?0:Pt.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:Pt.y<0?-Pt.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:Pt.y<0?0:Pt.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:Pt.y<0?0:Pt.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:Pt.y<0?-Pt.y:0,needsUpdate:!0}),c&&(i=-this.mtAvatar.bodyRotateY.value,a=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[i,i,0],headRotateX:[a,a,0],headRotateZ:[-i/4,-i/4,0]}})))):(i=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,a=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,i,i,0],headRotateX:[null,a,a,0],headRotateZ:[null,-i/4,-i/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),("full"!==this.viewName||this.isAvatarOnly)&&(i=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],a=this.mtAvatar[i],a.needsUpdate||Object.assign(a,{base:(this.mood.baseline[i]||0)+(1+o/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),(this.isSpeaking||this.isListening)&&r?o>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=o):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),i=this.volumeHeadTarget-this.volumeHeadCurrent,a=Math.abs(i),a>1e-4&&(s=a*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/a)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(i)*Math.min(a,s)),Math.abs(this.volumeHeadCurrent)>1e-4&&(Et.setFromAxisAngle(Ft,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(Et)),Ot.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(Dt),Dt.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(Ht),Ht.sub(this.armature.position),this.objectHips.position.y-=Ot.min.y/2,this.objectHips.position.x-=(Dt.x+Ht.x)/4,this.objectHips.position.z-=(Dt.z+Ht.z)/2,this.dynamicbones.update(e),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(null!==this.cameraClock&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let t=(new g.Spherical).setFromVector3(this.cameraStart),i=(new g.Spherical).setFromVector3(this.cameraEnd);t.phi+=this.easing(this.cameraClock/1e3)*(i.phi-t.phi),t.theta+=this.easing(this.cameraClock/1e3)*(i.theta-t.theta),t.radius+=this.easing(this.cameraClock/1e3)*(i.radius-t.radius),t.makeSafe(),this.camera.position.setFromSpherical(t),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(t.setFromVector3(this.controlsStart),i.setFromVector3(this.controlsEnd),t.phi+=this.easing(this.cameraClock/1e3)*(i.phi-t.phi),t.theta+=this.easing(this.cameraClock/1e3)*(i.theta-t.theta),t.radius+=this.easing(this.cameraClock/1e3)*(i.radius-t.radius),t.makeSafe(),this.controls.target.setFromSpherical(t)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach((t=>{this.morphs.forEach((e=>{const i=e.morphTargetDictionary["viseme_"+t];void 0!==i&&(e.morphTargetInfluences[i]=0)}))}))}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const a="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const e=Object.assign({"./lipsync-de.mjs":()=>import("./lipsync-de-C2V1AwVF.js"),"./lipsync-en.mjs":()=>import("./lipsync-en-qcS35m6x.js"),"./lipsync-fi.mjs":()=>import("./lipsync-fi-OWUVeE-b.js"),"./lipsync-fr.mjs":()=>import("./lipsync-fr-wVng3ZAI.js"),"./lipsync-lt.mjs":()=>import("./lipsync-lt-CYf-0Xtf.js")}),i=`./lipsync-${t.toLowerCase()}.mjs`;if(e[i])return void e[i]().then((e=>{e&&e[a]&&(this.lipsync[t]=new e[a])}))}catch(i){}const n=e+"lipsync-"+t.toLowerCase()+".mjs";import(n).then((e=>{this.lipsync[t]=new e[a]}))}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,i=null,a=null){const n=/[!\.\?\n\p{Extended_Pictographic}]/gu,s=/[ ]/gu,o=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/gu,r=/[\p{Extended_Pictographic}]/gu,c=(e=e||{}).lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let h="",l="",d=0,u=[],p=[];const m=Array.from(this.segmenter.segment(t),(t=>t.segment));for(let g=0;g<m.length;g++){const t=g===m.length-1,y=m[g].match(o);let v=m[g].match(n);const f=m[g].match(r),b=m[g].match(s);if(v&&!t&&!f&&m[g+1].match(n)&&(v=!1),i&&(h+=m[g]),y&&(a&&!a.every((t=>g<t[0]||g>t[1]))||(l+=m[g])),(b||v||t)&&(l.length&&(l=this.lipsyncPreProcessText(l,c),l.length&&u.push({mark:d,word:l})),h.length&&(p.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[h]}}),h=""),l.length)){const t=this.lipsyncWordsToVisemes(l,c);if(t&&t.visemes&&t.visemes.length){const e=t.times[t.visemes.length-1]+t.durations[t.visemes.length-1];for(let i=0;i<t.visemes.length;i++)p.push({mark:d,template:{name:"viseme"},ts:[(t.times[i]-.6)/e,(t.times[i]+.5)/e,(t.times[i]+t.durations[i]+.5)/e],vs:{["viseme_"+t.visemes[i]]:[null,"PP"===t.visemes[i]||"FF"===t.visemes[i]?.9:.6,0]}})}l="",d++}if(v||t){if(u.length||t&&p.length){const t={anim:p};i&&(t.onSubtitles=i),u.length&&!e.avatarMute&&(t.text=u,e.avatarMood&&(t.mood=e.avatarMood),e.ttsLang&&(t.lang=e.ttsLang),e.ttsVoice&&(t.voice=e.ttsVoice),e.ttsRate&&(t.rate=e.ttsRate),e.ttsVoice&&(t.pitch=e.ttsPitch),e.ttsVolume&&(t.volume=e.ttsVolume)),this.speechQueue.push(t),u=[],l="",d=0,p=[]}if(f){let t=this.animEmojis[m[g]];t&&t.link&&(t=this.animEmojis[t.link]),t&&this.speechQueue.push({emoji:t})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let e=await fetch(t),i=await e.arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(i),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch(t){}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let e=await fetch(t),i=await e.arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(i)}else{const t=this.audioCtx.sampleRate,e=this.audioCtx.createBuffer(2,t,t);e.getChannelData(0)[0]=1,e.getChannelData(1)[0]=1,this.audioReverbNode.buffer=e}}setMixerGain(t,e=null,i=0){null!==t&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+i)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),null!==e&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+i)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,i=null){const a=(e=e||{}).lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,n={};if(t.words){let e=[];for(let n=0;n<t.words.length;n++){const s=t.words[n],o=t.wtimes[n];let r=t.wdurations[n];if(s.length&&(i&&e.push({template:{name:"subtitles"},ts:[o],vs:{subtitles:[" "+s]}}),!t.visemes)){const t=this.lipsyncPreProcessText(s,a),i=this.lipsyncWordsToVisemes(t,a);if(i&&i.visemes&&i.visemes.length){const t=i.times[i.visemes.length-1]+i.durations[i.visemes.length-1],a=Math.min(r,Math.max(0,r-150*i.visemes.length));let n=.6+this.convertRange(a,[0,r],[0,.4]);if(r=Math.min(r,200*i.visemes.length),t>0)for(let s=0;s<i.visemes.length;s++){const a=o+i.times[s]/t*r,c=i.durations[s]/t*r;e.push({template:{name:"viseme"},ts:[a-Math.min(60,2*c/3),a+Math.min(25,c/2),a+c+Math.min(60,c/2)],vs:{["viseme_"+i.visemes[s]]:[null,"PP"===i.visemes[s]||"FF"===i.visemes[s]?.9:n,0]}})}}}}if(t.visemes)for(let i=0;i<t.visemes.length;i++){const a=t.visemes[i],n=t.vtimes[i],s=t.vdurations[i];e.push({template:{name:"viseme"},ts:[n-2*s/3,n+s/2,n+s+s/2],vs:{["viseme_"+a]:[null,"PP"===a||"FF"===a?.9:.6,0]}})}if(t.markers)for(let i=0;i<t.markers.length;i++){const a=t.markers[i],n=t.mtimes[i];e.push({template:{name:"markers"},ts:[n],vs:{function:[a]}})}e.length&&(n.anim=e)}if(t.audio&&(n.audio=t.audio),t.anim?.name){let e=this.animFactory(t.anim,!1,1,1,!0);n.anim?n.anim.push(e):n.anim=[e]}i&&(n.onSubtitles=i),Object.keys(n).length&&(this.speechQueue.push(n),this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(this.armature&&(!this.isAudioPlaying||t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const t=this.audioPlaylist.shift();if("suspended"===this.audioCtx.state||"interrupted"===this.audioCtx.state){const t=this.audioCtx.resume(),i=new Promise(((t,e)=>setTimeout((()=>e("p2")),1e3)));try{await Promise.race([t,i])}catch(e){return void this.playAudio(!0)}}let i;if(Array.isArray(t.audio)){let e=this.concatArrayBuffers(t.audio);i=this.pcmToAudioBuffer(e)}else i=t.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=i,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",(()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)}),{once:!0});let a=0;t.anim&&(a=Math.abs(Math.min(0,...t.anim.map((t=>Math.min(...t.ts))))),t.anim.forEach((t=>{for(let e=0;e<t.ts.length;e++)t.ts[e]=this.animClock+t.ts[e]+a;this.animQueue.push(t)}))),this.audioSpeechSource.start(a/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async startSpeaking(t=!1){if(this.armature&&(!this.isSpeaking||t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let t=this.speechQueue.shift();if(t.emoji){this.lookAtCamera(500);let e=t.emoji.dt.reduce(((t,e)=>t+e),0);this.animQueue.push(this.animFactory(t.emoji)),setTimeout(this.startSpeaking.bind(this),e,!0)}else if(t.break)setTimeout(this.startSpeaking.bind(this),t.break,!0);else if(t.audio)this.lookAtCamera(500),this.speakWithHands(),this.audioPlaylist.push({anim:t.anim,audio:t.audio}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio();else if(t.text){this.lookAtCamera(500);try{let e="<speak>";t.text.forEach(((t,i)=>{i>0&&(e+=" <mark name='"+t.mark+"'/>"),e+=t.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')})),e+="</speak>";const i={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&"function"==typeof this.opt.jwtGet&&(i.headers.Authorization="Bearer "+await this.opt.jwtGet());const a=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),i),n=await a.json();if(200===a.status&&n&&n.audioContent){const e=this.b64ToArrayBuffer(n.audioContent),i=await this.audioCtx.decodeAudioData(e);this.speakWithHands();const a=[0];let s=0;t.text.forEach(((t,e)=>{if(e>0){let e=a[a.length-1];n.timepoints[s]&&(e=1e3*n.timepoints[s].timeSeconds,n.timepoints[s].markName===""+t.mark&&s++),a.push(e)}}));const o=[{mark:0,time:0}];a.forEach(((t,e)=>{if(e>0){let i=t-a[e-1];o[e-1].duration=i,o.push({mark:e,time:t})}}));let r=1e3*i.duration;r>this.opt.ttsTrimEnd&&(r-=this.opt.ttsTrimEnd),o[o.length-1].duration=r-o[o.length-1].time,t.anim.forEach((t=>{const e=o[t.mark];if(e)for(let i=0;i<t.ts.length;i++)t.ts[i]=e.time+t.ts[i]*e.duration+this.opt.ttsTrimStart})),this.audioPlaylist.push({anim:t.anim,audio:i}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}catch(e){this.startSpeaking(!0)}}else t.anim?(this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),t.anim.forEach(((t,e)=>{for(let i=0;i<t.ts.length;i++)t.ts[i]=this.animClock+10*e;this.animQueue.push(t)})),setTimeout(this.startSpeaking.bind(this),10*t.anim.length,!0)):t.marker?("function"==typeof t.marker&&t.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch(t){}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch(t){}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,i=null,a=null,n=null){if(this.stopSpeaking(),this.isStreaming=!0,void 0!==t.waitForAudioChunks&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=i,this.onMetrics=n,void 0!==t.sampleRate){const e=t.sampleRate;"number"==typeof e&&e>=8e3&&e<=96e3&&e!==this.audioCtx.sampleRate&&this.initAudioGraph(e)}if(void 0!==t.gain&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||0===this.streamWorkletNode.numberOfOutputs||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch(s){}if(!this.workletLoaded)try{const t=function(){if(Mt)return Mt;const t=new Blob(['class PlaybackWorklet extends AudioWorkletProcessor {\r\n static FSM = {\r\n IDLE: 0,\r\n PLAYING: 1,\r\n };\r\n\r\n constructor(options) {\r\n super();\r\n this.port.onmessage = this.handleMessage.bind(this);\r\n\r\n this._sampleRate = options?.processorOptions?.sampleRate || sampleRate;\r\n this._scale = 1 / 32768; // PCM16 -> float\r\n\r\n // Silence detection threshold (1 second) as a fallback safety net\r\n const silenceDurationSeconds = 1.0;\r\n this._silenceThresholdBlocks = Math.ceil((this._sampleRate * silenceDurationSeconds) / 128);\r\n\r\n // Metrics configuration via options\r\n const metricsCfg = options?.processorOptions?.metrics || {};\r\n this._metricsEnabled = metricsCfg.enabled !== false;\r\n const intervalHz = (typeof metricsCfg.intervalHz === "number" && metricsCfg.intervalHz > 0)\r\n ? metricsCfg.intervalHz : 2;\r\n // Metrics state (low-overhead)\r\n this._framesProcessed = 0;\r\n this._underrunBlocks = 0;\r\n this._maxQueueSamples = 0;\r\n this._lastMetricsSentAtFrame = 0;\r\n // Convert to frames between reports\r\n this._metricsIntervalFrames = Math.max(128, Math.round(this._sampleRate / intervalHz));\r\n\r\n this.reset();\r\n }\r\n\r\n /**\r\n * Resets the worklet to its initial IDLE state.\r\n */\r\n reset() {\r\n this._bufferQueue = [];\r\n this._currentChunk = null;\r\n this._currentChunkOffset = 0;\r\n this._state = PlaybackWorklet.FSM.IDLE;\r\n\r\n this._noMoreDataReceived = false;\r\n this._silenceFramesCount = 0;\r\n this._hasSentEnded = false;\r\n // Reset max queue tracker only when going idle\r\n this._maxQueueSamples = 0;\r\n }\r\n\r\n handleMessage(event) {\r\n const { type, data } = event.data;\r\n\r\n // INTERRUPT: The main thread wants to stop immediately.\r\n if (type === "stop") {\r\n this.reset();\r\n // Send final metrics showing cleared state\r\n if (this._metricsEnabled) {\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: PlaybackWorklet.FSM.IDLE,\r\n queuedSamples: 0,\r\n queuedMs: 0,\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n }\r\n return;\r\n }\r\n\r\n // Main thread has signaled that no more audio chunks will be sent for this utterance.\r\n if (type === "no-more-data") {\r\n this._noMoreDataReceived = true;\r\n return;\r\n }\r\n\r\n // Update metrics configuration at runtime\r\n if (type === "config-metrics" && data && typeof data === "object") {\r\n if ("enabled" in data) this._metricsEnabled = !!data.enabled;\r\n if (typeof data.intervalHz === "number" && data.intervalHz > 0) {\r\n const intervalHz = data.intervalHz;\r\n this._metricsIntervalFrames = Math.max(128, Math.round(this._sampleRate / intervalHz));\r\n }\r\n // Reset pacing so the next report aligns with new interval\r\n this._lastMetricsSentAtFrame = this._framesProcessed;\r\n return;\r\n }\r\n\r\n // New audio data has arrived.\r\n if (type === "audioData" && data instanceof ArrayBuffer) {\r\n this._noMoreDataReceived = false;\r\n // If we were idle, this new data kicks off the playback.\r\n if (this._state === PlaybackWorklet.FSM.IDLE) {\r\n this._state = PlaybackWorklet.FSM.PLAYING;\r\n this.port.postMessage({ type: "playback-started" });\r\n }\r\n\r\n // We only queue data if we are in the PLAYING state. This prevents\r\n // data from a previous, interrupted stream from lingering.\r\n if (this._state === PlaybackWorklet.FSM.PLAYING) {\r\n // Store as Int16Array view to avoid constructing it in process()\r\n this._bufferQueue.push(new Int16Array(data));\r\n this._silenceFramesCount = 0; // Reset silence counter on new data\r\n }\r\n }\r\n }\r\n\r\n process(inputs, outputs, parameters) {\r\n const outputChannel = outputs[0]?.[0];\r\n if (!outputChannel) {\r\n return true; // Keep alive even if output is temporarily disconnected\r\n }\r\n\r\n // If we are not playing, just output silence and wait.\r\n if (this._state !== PlaybackWorklet.FSM.PLAYING) {\r\n outputChannel.fill(0);\r\n return true; // Always return true to keep the processor alive\r\n }\r\n\r\n // Core PLAYING Logic\r\n const blockSize = outputChannel.length;\r\n let samplesCopied = 0;\r\n\r\n while (samplesCopied < blockSize) {\r\n if (!this._currentChunk || this._currentChunkOffset >= this._currentChunk.length) {\r\n if (this._bufferQueue.length > 0) {\r\n this._currentChunk = this._bufferQueue.shift();\r\n this._currentChunkOffset = 0;\r\n } else {\r\n // Buffer is empty. Check for end conditions.\r\n const isTimedOut = this._silenceFramesCount > this._silenceThresholdBlocks;\r\n\r\n if (this._noMoreDataReceived || isTimedOut) {\r\n // END OF PLAYBACK: Either explicitly signaled or timed out.\r\n if (!this._hasSentEnded) {\r\n this.port.postMessage({ type: "playback-ended" });\r\n this._hasSentEnded = true;\r\n }\r\n // Send final metrics showing cleared state\r\n if (this._metricsEnabled) {\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: PlaybackWorklet.FSM.IDLE,\r\n queuedSamples: 0,\r\n queuedMs: 0,\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n }\r\n this.reset(); // Reset to IDLE state for reuse\r\n break; // Exit while loop\r\n } else {\r\n // BUFFER UNDERRUN (LAG): Play silence and wait for more data.\r\n this._silenceFramesCount++;\r\n if (this._metricsEnabled) this._underrunBlocks++;\r\n break; // Exit while loop\r\n }\r\n }\r\n }\r\n\r\n // If we have a chunk (could be a new one from the logic above), process it.\r\n if (this._currentChunk) {\r\n const samplesToCopy = Math.min(\r\n blockSize - samplesCopied,\r\n this._currentChunk.length - this._currentChunkOffset\r\n );\r\n // Directly write to outputChannel to avoid extra copy\r\n const src = this._currentChunk;\r\n const baseSrc = this._currentChunkOffset;\r\n const baseDst = samplesCopied;\r\n const scale = this._scale;\r\n for (let i = 0; i < samplesToCopy; i++) {\r\n outputChannel[baseDst + i] = src[baseSrc + i] * scale;\r\n }\r\n\r\n this._currentChunkOffset += samplesToCopy;\r\n samplesCopied += samplesToCopy;\r\n }\r\n }\r\n\r\n // Zero-fill the remainder, if any, once per block\r\n if (samplesCopied < blockSize) {\r\n outputChannel.fill(0, samplesCopied);\r\n }\r\n\r\n // Update metrics (optional)\r\n if (this._metricsEnabled) {\r\n this._framesProcessed += blockSize;\r\n\r\n // Track queue depth in samples (approximate)\r\n let queuedSamples = 0;\r\n if (this._currentChunk) queuedSamples += Math.max(0, this._currentChunk.length - this._currentChunkOffset);\r\n for (let i = 0; i < this._bufferQueue.length; i++) queuedSamples += this._bufferQueue[i].length;\r\n if (queuedSamples > this._maxQueueSamples) this._maxQueueSamples = queuedSamples;\r\n\r\n // Periodically send metrics to main thread\r\n if (this._framesProcessed - this._lastMetricsSentAtFrame >= this._metricsIntervalFrames) {\r\n this._lastMetricsSentAtFrame = this._framesProcessed;\r\n try {\r\n this.port.postMessage({\r\n type: "metrics",\r\n data: {\r\n state: this._state,\r\n queuedSamples,\r\n queuedMs: Math.round((queuedSamples / this._sampleRate) * 1000),\r\n maxQueuedMs: Math.round((this._maxQueueSamples / this._sampleRate) * 1000),\r\n underrunBlocks: this._underrunBlocks,\r\n framesProcessed: this._framesProcessed\r\n }\r\n });\r\n } catch (_) { }\r\n // Don\'t reset max tracker - keep session peak until idle\r\n }\r\n }\r\n\r\n // ALWAYS return true to keep the processor alive for reuse.\r\n return true;\r\n }\r\n}\r\n\r\nregisterProcessor("playback-worklet", PlaybackWorklet);\r\n'],{type:"application/javascript"});return Mt=URL.createObjectURL(t),Mt}(),e=this.audioCtx.audioWorklet.addModule(t),i=new Promise(((t,e)=>setTimeout((()=>e(new Error("Worklet loading timed out"))),5e3)));await Promise.race([e,i]),this.workletLoaded=!0}catch(o){throw new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=t=>{if("playback-started"===t.data.type&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(s){}if("playback-ended"===t.data.type&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch(s){}if(this.onMetrics&&"metrics"===t.data.type)try{this.onMetrics(t.data)}catch(s){}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch(s){}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=a||null,"suspended"===this.audioCtx.state||"interrupted"===this.audioCtx.state){const t=this.audioCtx.resume(),e=new Promise(((t,e)=>setTimeout((()=>e("p2")),1e3)));try{await Promise.race([t,e])}catch(s){return}}}streamNotifyEnd(){this.isStreaming&&this.streamWorkletNode&&this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch(e){}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch(e){}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch(t){}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter((t=>"viseme"!==t.template.name&&"subtitles"!==t.template.name&&"blendshapes"!==t.template.name)),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&"visemes"==this.streamLipsyncType)for(let i=0;i<t.visemes.length;i++){const a=t.visemes[i],n=e+t.vtimes[i],s=t.vdurations[i],o={template:{name:"viseme"},ts:[n-2*s/3,n+s/2,n+s+s/2],vs:{["viseme_"+a]:[null,"PP"===a||"FF"===a?.9:.6,0]}};this.animQueue.push(o)}if(t.words&&(this.onSubtitles||"words"==this.streamLipsyncType))for(let i=0;i<t.words.length;i++){const a=t.words[i],n=t.wtimes[i];let s=t.wdurations[i];if(a.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+n],vs:{subtitles:[" "+a]}}),"words"==this.streamLipsyncType)){const t=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,i=this.lipsyncPreProcessText(a,t),o=this.lipsyncWordsToVisemes(i,t);if(o&&o.visemes&&o.visemes.length){const t=o.times[o.visemes.length-1]+o.durations[o.visemes.length-1],i=Math.min(s,Math.max(0,s-150*o.visemes.length));let a=.6+this.convertRange(i,[0,s],[0,.4]);if(s=Math.min(s,200*o.visemes.length),t>0)for(let r=0;r<o.visemes.length;r++){const i=e+n+o.times[r]/t*s,c=o.durations[r]/t*s;this.animQueue.push({template:{name:"viseme"},ts:[i-Math.min(60,2*c/3),i+Math.min(25,c/2),i+c+Math.min(60,c/2)],vs:{["viseme_"+o.visemes[r]]:[null,"PP"===o.visemes[r]||"FF"===o.visemes[r]?.9:a,0]}})}}}}if(t.anims&&"blendshapes"==this.streamLipsyncType)for(let i=0;i<t.anims.length;i++){let a=t.anims[i];a.delay+=e;let n=this.animFactory(a,!1,1,1,!0);this.animQueue.push(n)}}}streamAudio(t){if(this.isStreaming&&this.streamWorkletNode){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",void 0!==t.audio){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const i=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=i,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const i=new Int16Array(t.audio.length);for(let e=0;e<t.audio.length;e++){let a=Math.max(-1,Math.min(1,t.audio[e]));i[e]=a<0?32768*a:32767*a}e.data=i.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime)return this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),void this.streamLipsyncQueue.push(t);this.streamWaitForAudioChunks||this.streamAudioStartTime||(this.streamAudioStartTime=this.animClock),this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,i=(Math.random()-.5)/4,a=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==a&&this.animQueue.splice(a,1);const n={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[i],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*i],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(n))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new g.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),Dt.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),Ht.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(Dt,Ht).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera)return void this.lookAhead(t)}else if(this.opt.avatarIgnoreCamera)return void this.lookAhead(t);return void this.lookAt(null,null,t)}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),Dt.setFromMatrixPosition(this.objectLeftEye.matrixWorld),Ht.setFromMatrixPosition(this.objectRightEye.matrixWorld),Dt.add(Ht).divideScalar(2),Et.copy(this.armature.quaternion),Et.multiply(this.poseTarget.props["Hips.quaternion"]),Et.multiply(this.poseTarget.props["Spine.quaternion"]),Et.multiply(this.poseTarget.props["Spine1.quaternion"]),Et.multiply(this.poseTarget.props["Spine2.quaternion"]),Et.multiply(this.poseTarget.props["Neck.quaternion"]),Et.multiply(this.poseTarget.props["Head.quaternion"]);const i=(new g.Vector3).subVectors(e,Dt).normalize(),a=Math.atan2(i.x,i.z),n=Math.asin(-i.y);Pt.set(n,a,0,"YXZ");const s=(new g.Quaternion).setFromEuler(Pt),o=(new g.Quaternion).copy(s).multiply(Et.clone().invert());Pt.setFromQuaternion(o,"YXZ");let r=Pt.x/(40/24)+.2,c=Pt.y/(9/4),h=Math.min(.6,Math.max(-.3,r)),l=Math.min(.8,Math.max(-.8,c)),d=(Math.random()-.5)/4,u=(Math.random()-.5)/4;if(t){let e=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==e&&this.animQueue.splice(e,1);const i={name:"lookat",dt:[750,t],vs:{bodyRotateX:[h+d],bodyRotateY:[l+u],eyesRotateX:[-3*d+.1],eyesRotateY:[-5*u],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(i))}}lookAt(t,e,i){if(!this.camera)return;const a=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const n=(new g.Vector3).setFromMatrixPosition(this.objectLeftEye.matrixWorld),s=(new g.Vector3).setFromMatrixPosition(this.objectRightEye.matrixWorld),o=(new g.Vector3).addVectors(n,s).divideScalar(2);o.project(this.camera);let r=(o.x+1)/2*a.width+a.left,c=-(o.y-1)/2*a.height+a.top;null===t&&(t=r),null===e&&(e=c),Et.copy(this.armature.quaternion),Et.multiply(this.poseTarget.props["Hips.quaternion"]),Et.multiply(this.poseTarget.props["Spine.quaternion"]),Et.multiply(this.poseTarget.props["Spine1.quaternion"]),Et.multiply(this.poseTarget.props["Spine2.quaternion"]),Et.multiply(this.poseTarget.props["Neck.quaternion"]),Et.multiply(this.poseTarget.props["Head.quaternion"]),Pt.setFromQuaternion(Et);let h=Pt.x/(40/24),l=Pt.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),u=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),p=Math.max(window.innerWidth-r,r),m=Math.max(window.innerHeight-c,c),y=this.convertRange(e,[c-m,c+m],[-.3,.6])-h+d,v=this.convertRange(t,[r-p,r+p],[-.8,.8])-l+u;y=Math.min(.6,Math.max(-.3,y)),v=Math.min(.8,Math.max(-.8,v));let f=(Math.random()-.5)/4,b=(Math.random()-.5)/4;if(i){let t=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==t&&this.animQueue.splice(t,1);const e={name:"lookat",dt:[750,i],vs:{bodyRotateX:[y+f],bodyRotateY:[v+b],eyesRotateX:[-3*f+.1],eyesRotateY:[-5*b],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(e))}}touchAt(t,e){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect(),a=new g.Vector2((t-i.left)/i.width*2-1,-(e-i.top)/i.height*2+1),n=new g.Raycaster;n.setFromCamera(a,this.camera);const s=n.intersectObject(this.armature);if(s.length>0){const t=s[0].point,e=new g.Vector3,i=new g.Vector3;this.objectLeftArm.getWorldPosition(e),this.objectRightArm.getWorldPosition(i),e.distanceToSquared(t)<i.distanceToSquared(t)?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},t,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},t,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach((t=>{let e=t+".quaternion";this.poseTarget.props[e].copy(this.getPoseTemplateProp(e)),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3}));return s.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new g.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new g.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const i=[],a=[];i.push(100+Math.round(500*Math.random())),a.push({duration:1e3,props:{"LeftHand.quaternion":(new g.Quaternion).setFromEuler(new g.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":(new g.Quaternion).setFromEuler(new g.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach((t=>{a[0].props[t+".quaternion"]=this.ikMesh.getObjectByName(t).quaternion.clone()})),i.push(1e3+Math.round(500*Math.random())),a.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach((t=>{a[1].props[t+".quaternion"]=null}));const n=this.animFactory({name:"talkinghands",delay:t,dt:i,vs:{moveto:a}});this.animQueue.push(n)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&!1===this.isRunning&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},i=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=i&&"function"==typeof i?i:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,i=10,a=0,n=.01){if(!this.armature)return;let s=this.animClips.find((e=>e.url===t+"-"+a));if(s){let t=this.animQueue.find((t=>"pose"===t.template.name));t&&(t.ts[0]=1/0),Object.entries(s.pose.props).forEach((t=>{this.poseBase.props[t[0]]=t[1].clone(),this.poseTarget.props[t[0]]=t[1].clone(),this.poseTarget.props[t[0]].t=0,this.poseTarget.props[t[0]].d=1e3})),this.mixer=new g.AnimationMixer(this.armature),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const e=Math.ceil(i/s.clip.duration),a=this.mixer.clipAction(s.clip);a.setLoop(g.LoopRepeat,e),a.clampWhenFinished=!0,a.fadeIn(.5).play()}else{const s=new b;let o=await s.loadAsync(t,e);if(o&&o.animations&&o.animations[a]){let s=o.animations[a];const r={};s.tracks.forEach((t=>{t.name=t.name.replaceAll("mixamorig","");const e=t.name.split(".");if("position"===e[1]){for(let e=0;e<t.values.length;e++)t.values[e]=t.values[e]*n;r[t.name]=new g.Vector3(t.values[0],t.values[1],t.values[2])}else"quaternion"===e[1]?r[t.name]=new g.Quaternion(t.values[0],t.values[1],t.values[2],t.values[3]):"rotation"===e[1]&&(r[e[0]+".quaternion"]=(new g.Quaternion).setFromEuler(new g.Euler(t.values[0],t.values[1],t.values[2],"XYZ")).normalize())}));const c={props:r};r["Hips.position"]&&(r["Hips.position"].y<.5?c.lying=!0:c.standing=!0),this.animClips.push({url:t+"-"+a,clip:s,pose:c}),this.playAnimation(t,e,i,a,n)}}}stopAnimation(){if(this.mixer=null,this.gesture)for(let[e,i]of Object.entries(this.gesture))i.t=this.animClock,i.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(i),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find((t=>"pose"===t.template.name));t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,i=5,a=0,n=.01){if(!this.armature)return;let s=this.poseTemplates[t];if(!s){const e=this.animPoses.find((e=>e.url===t+"-"+a));e&&(s=e.pose)}if(s){this.poseName=t,this.mixer=null;let e=this.animQueue.find((t=>"pose"===t.template.name));e&&(e.ts[0]=this.animClock+1e3*i+2e3),this.setPoseFromTemplate(s)}else{const s=new b;let o=await s.loadAsync(t,e);if(o&&o.animations&&o.animations[a]){let s=o.animations[a];const r={};s.tracks.forEach((t=>{t.name=t.name.replaceAll("mixamorig","");const e=t.name.split(".");"position"===e[1]?r[t.name]=new g.Vector3(t.values[0]*n,t.values[1]*n,t.values[2]*n):"quaternion"===e[1]?r[t.name]=new g.Quaternion(t.values[0],t.values[1],t.values[2],t.values[3]):"rotation"===e[1]&&(r[e[0]+".quaternion"]=(new g.Quaternion).setFromEuler(new g.Euler(t.values[0],t.values[1],t.values[2],"XYZ")).normalize())}));const c={props:r};r["Hips.position"]&&(r["Hips.position"].y<.5?c.lying=!0:c.standing=!0),this.animPoses.push({url:t+"-"+a,pose:c}),this.playPose(t,e,i,a,n)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,i=!1,a=1e3){if(!this.armature)return;let n=this.gestureTemplates[t];if(n){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let s=this.animQueue.findIndex((t=>"talkinghands"===t.template.name));-1!==s&&(this.animQueue[s].ts=this.animQueue[s].ts.map((t=>0))),this.gesture=this.propsToThreeObjects(n),i&&(this.gesture=this.mirrorPose(this.gesture)),"namaste"===t&&"M"===this.avatar.body&&(this.gesture["RightArm.quaternion"].rotateTowards(new g.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new g.Quaternion(0,1,0,0),-.25));for(let[t,e]of Object.entries(this.gesture))e.t=this.animClock,e.d=a,this.poseTarget.props.hasOwnProperty(t)&&(this.poseTarget.props[t].copy(e),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=a);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,a),1e3*e))}let s=this.animEmojis[t];if(s&&(s&&s.link&&(s=this.animEmojis[s.link]),s)){this.lookAtCamera(500);const t=this.animFactory(s);if(t.gesture=!0,e&&Number.isFinite(e)){const i=t.ts[0],a=t.ts[t.ts.length-1]-i;if(1e3*e-a>0){const n=[];for(let e=1;e<t.ts.length;e++)n.push(t.ts[e]-t.ts[e-1]);const o=s.template?.rescale||n.map((t=>t/a)),r=1e3*e-a;t.ts=t.ts.map(((t,e,a)=>0===e?i:a[e-1]+n[e-1]+o[e-1]*r))}else{const n=1e3*e/a;t.ts=t.ts.map((t=>i+n*(t-i)))}}this.animQueue.push(t)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const e=Object.entries(this.gesture);this.gesture=null;for(const[i,a]of e)this.poseTarget.props.hasOwnProperty(i)&&(this.poseTarget.props[i].copy(this.getPoseTemplateProp(i)),this.poseTarget.props[i].t=this.animClock,this.poseTarget.props[i].d=t)}let e=this.animQueue.findIndex((t=>t.gesture));-1!==e&&this.animQueue.splice(e,1)}ikSolve(t,e=null,i=!1,a=null){const n=new g.Vector3,s=new g.Vector3,o=new g.Vector3,r=new g.Vector3,c=new g.Quaternion,h=new g.Vector3,l=new g.Vector3,d=new g.Vector3,u=this.ikMesh.getObjectByName(t.root);u.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),u.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&i&&e.applyQuaternion(this.armature.quaternion).add(u.position);const p=this.ikMesh.getObjectByName(t.effector),m=t.links;m.forEach((t=>{t.bone=this.ikMesh.getObjectByName(t.link),t.bone.quaternion.copy(this.getPoseTemplateProp(t.link+".quaternion"))})),u.updateMatrixWorld(!0);const y=t.iterations||10;if(e)for(let v=0;v<y;v++){let t=!1;for(let i=0,a=m.length;i<a;i++){const a=m[i].bone;a.matrixWorld.decompose(r,c,h),c.invert(),s.setFromMatrixPosition(p.matrixWorld),o.subVectors(s,r),o.applyQuaternion(c),o.normalize(),n.subVectors(e,r),n.applyQuaternion(c),n.normalize();let u=n.dot(o);u>1?u=1:u<-1&&(u=-1),u=Math.acos(u),u<1e-5||(void 0!==m[i].minAngle&&u<m[i].minAngle&&(u=m[i].minAngle),void 0!==m[i].maxAngle&&u>m[i].maxAngle&&(u=m[i].maxAngle),l.crossVectors(o,n),l.normalize(),Et.setFromAxisAngle(l,u),a.quaternion.multiply(Et),a.rotation.setFromVector3(d.setFromEuler(a.rotation).clamp(new g.Vector3(void 0!==m[i].minx?m[i].minx:-1/0,void 0!==m[i].miny?m[i].miny:-1/0,void 0!==m[i].minz?m[i].minz:-1/0),new g.Vector3(void 0!==m[i].maxx?m[i].maxx:1/0,void 0!==m[i].maxy?m[i].maxy:1/0,void 0!==m[i].maxz?m[i].maxz:1/0))),a.updateMatrixWorld(!0),t=!0)}if(!t)break}a&&m.forEach((t=>{this.poseTarget.props[t.link+".quaternion"].copy(t.bone.quaternion),this.poseTarget.props[t.link+".quaternion"].t=this.animClock,this.poseTarget.props[t.link+".quaternion"].d=a}))}dispose(){this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect()),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const Nt={dance:["dance\\M_Dances_007.fbx","dance\\M_Dances_008.fbx","dance\\M_Dances_009.fbx","dance\\M_Dances_011.fbx","dance\\F_Dances_001.fbx","dance\\F_Dances_004.fbx","dance\\F_Dances_005.fbx","dance\\F_Dances_006.fbx","dance\\F_Dances_007.fbx","dance\\M_Dances_001.fbx","dance\\M_Dances_002.fbx","dance\\M_Dances_003.fbx","dance\\M_Dances_004.fbx","dance\\M_Dances_005.fbx","dance\\M_Dances_006.fbx"],expression:["expression\\M_Standing_Expressions_016.fbx","expression\\M_Standing_Expressions_017.fbx","expression\\M_Standing_Expressions_018.fbx","expression\\M_Talking_Variations_001.fbx","expression\\M_Talking_Variations_002.fbx","expression\\M_Talking_Variations_003.fbx","expression\\M_Talking_Variations_004.fbx","expression\\M_Talking_Variations_005.fbx","expression\\M_Talking_Variations_006.fbx","expression\\M_Talking_Variations_007.fbx","expression\\M_Talking_Variations_008.fbx","expression\\M_Talking_Variations_009.fbx","expression\\M_Talking_Variations_010.fbx","expression\\F_Talking_Variations_001.fbx","expression\\F_Talking_Variations_002.fbx","expression\\F_Talking_Variations_003.fbx","expression\\F_Talking_Variations_004.fbx","expression\\F_Talking_Variations_005.fbx","expression\\F_Talking_Variations_006.fbx","expression\\M_Standing_Expressions_001.fbx","expression\\M_Standing_Expressions_002.fbx","expression\\M_Standing_Expressions_004.fbx","expression\\M_Standing_Expressions_005.fbx","expression\\M_Standing_Expressions_006.fbx","expression\\M_Standing_Expressions_007.fbx","expression\\M_Standing_Expressions_008.fbx","expression\\M_Standing_Expressions_009.fbx","expression\\M_Standing_Expressions_010.fbx","expression\\M_Standing_Expressions_011.fbx","expression\\M_Standing_Expressions_012.fbx","expression\\M_Standing_Expressions_013.fbx","expression\\M_Standing_Expressions_014.fbx","expression\\M_Standing_Expressions_015.fbx"],locomotion:["locomotion\\M_CrouchedWalk_Backwards_002.fbx","locomotion\\M_Falling_Idle_002.fbx","locomotion\\M_Jog_001.fbx","locomotion\\M_Jog_003.fbx","locomotion\\M_Jog_Backwards_001.fbx","locomotion\\M_Jog_Jump_001.fbx","locomotion\\M_Jog_Jump_002.fbx","locomotion\\M_Jog_Strafe_Left_001.fbx","locomotion\\M_Jog_Strafe_Right_001.fbx","locomotion\\M_Run_001.fbx","locomotion\\M_Run_Backwards_002.fbx","locomotion\\M_Run_Jump_001.fbx","locomotion\\M_Run_Jump_002.fbx","locomotion\\M_Run_Strafe_Left_002.fbx","locomotion\\M_Run_Strafe_Right_002.fbx","locomotion\\M_Walk_001.fbx","locomotion\\M_Walk_002.fbx","locomotion\\M_Walk_Backwards_001.fbx","locomotion\\M_Walk_Jump_001.fbx","locomotion\\M_Walk_Jump_002.fbx","locomotion\\M_Walk_Jump_003.fbx","locomotion\\M_Walk_Strafe_Left_002.fbx","locomotion\\M_Walk_Strafe_Right_002.fbx","locomotion\\F_Crouch_Strafe_Left.fbx","locomotion\\F_Crouch_Strafe_Right.fbx","locomotion\\F_Crouch_Walk_001.fbx","locomotion\\F_CrouchedWalk_Backwards_001.fbx","locomotion\\F_Falling_Idle_000.fbx","locomotion\\F_Falling_Idle_001.fbx","locomotion\\F_Jog_001.fbx","locomotion\\F_Jog_Backwards_001.fbx","locomotion\\F_Jog_Jump_Small_001.fbx","locomotion\\F_Jog_Strafe_Left_002.fbx","locomotion\\F_Jog_Strafe_Right_002.fbx","locomotion\\F_Run_001.fbx","locomotion\\F_Run_Backwards_001.fbx","locomotion\\F_Run_Jump_001.fbx","locomotion\\F_Run_Strafe_Left_001.fbx","locomotion\\F_Run_Strafe_Right_001.fbx","locomotion\\F_Walk_002.fbx","locomotion\\F_Walk_003.fbx","locomotion\\F_Walk_Backwards_001.fbx","locomotion\\F_Walk_Jump_001.fbx","locomotion\\F_Walk_Jump_002.fbx","locomotion\\F_Walk_Strafe_Left_001.fbx","locomotion\\F_Walk_Strafe_Right_001.fbx","locomotion\\M_Crouch_Strafe_Left_002.fbx","locomotion\\M_Crouch_Strafe_Right_002.fbx","locomotion\\M_Crouch_Walk_003.fbx"],idle:["idle\\M_Standing_Idle_Variations_001.fbx","idle\\M_Standing_Idle_Variations_002.fbx","idle\\M_Standing_Idle_Variations_003.fbx","idle\\M_Standing_Idle_Variations_004.fbx","idle\\M_Standing_Idle_Variations_005.fbx","idle\\M_Standing_Idle_Variations_006.fbx","idle\\M_Standing_Idle_Variations_007.fbx","idle\\M_Standing_Idle_Variations_008.fbx","idle\\M_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_Variations_010.fbx","idle\\F_Standing_Idle_001.fbx","idle\\F_Standing_Idle_Variations_001.fbx","idle\\F_Standing_Idle_Variations_002.fbx","idle\\F_Standing_Idle_Variations_003.fbx","idle\\F_Standing_Idle_Variations_004.fbx","idle\\F_Standing_Idle_Variations_005.fbx","idle\\F_Standing_Idle_Variations_006.fbx","idle\\F_Standing_Idle_Variations_007.fbx","idle\\F_Standing_Idle_Variations_008.fbx","idle\\F_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_001.fbx","idle\\M_Standing_Idle_002.fbx"]};function Ut(t){return t&&0!==t.length?t[Math.floor(Math.random()*t.length)]:null}function Vt(t,e,...i){return t.filter((t=>!!t.includes(`${e}_`)&&i.every((e=>t.includes(e)))))}const $t={maxChars:E.captions.maxCharactersPerCaption,minChars:E.captions.minCharactersPerCaption,softChars:Math.floor(.75*E.captions.maxCharactersPerCaption),pauseBreakMs:350,preferBreakAfter:/[.!?…]|—|–|;/,softBreakAfter:/,|:/};class jt{constructor(){this.currentCaptions=[],this.currentCaptionIndex=0,this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this._playAttemptActive=!1}isBoundaryTypeValid(t){return"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType}handleWordBoundaryEvent(t){if(!this.isBoundaryTypeValid(t))return;const e=t.text,i=t.audioOffset,a=t.duration;let n=this.currentCaptions[this.currentCaptions.length-1],s=null;if(n&&Number.isFinite(n._lastEndOffsetMs)&&(s=i-n._lastEndOffsetMs),!n||function(t,e,i){const a=t.text,n=a.length,s=$t.preferBreakAfter.test(a.slice(-1)),o=$t.softBreakAfter.test(a.slice(-1));return!!t.isDisplayed||null!=i&&i>=$t.pauseBreakMs&&n>=$t.minChars||(r=n)+(r?1:0)+e.length>$t.maxChars||!!(s&&n>=$t.minChars)||!!(n>=$t.softChars&&o);var r}(n,e,s)){const t={text:e,audioOffset:i,duration:a,isDisplayed:!1,_lastEndOffsetMs:i+a,get renderText(){return(t=this.text)?` ${t.trim()} `:" ";var t}};this.currentCaptions.push(t)}else n.text=(r=e,((o=n.text).length>0&&!/\s$/.test(o)&&!/^[\s.,!?;:…)]/.test(r)?o+" "+r:o+r).replace(/\s{2,}/g," ")),n.duration+=a,n._lastEndOffsetMs=i+a;var o,r;if(/^[\s.,!?;:…()\[\]{}'"—–-]$/.test(e)){const t=this.currentCaptions[this.currentCaptions.length-1];t&&(t.text=t.text.replace(/\s+([.,!?;:…)\]}])/g,"$1").replace(/([([{])\s+/g,"$1").replace(/\s{2,}/g," ").trim())}}playCaptions(t,e){this._playAttemptActive=!0;const i=async()=>{this._playAttemptActive&&(this.currentCaptions.length>0&&!this.currentCaptions[0].isDisplayed?(this._playAttemptActive=!1,this.startCaptionDisplay(t,e)):(await this.wait(100),i()))};i()}startCaptionDisplay(t,e){this.currentCaptionIndex=0,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null;const i=()=>{if(this.currentCaptionIndex>=this.currentCaptions.length)return void(this.settleTimeoutId=setTimeout((()=>{this.settleTimeoutId=null,this.currentCaptionIndex>=this.currentCaptions.length?t(!1):i()}),100));const a=this.currentCaptions[this.currentCaptionIndex];if(!a)return void t(!1);const n=Math.max(0,a.audioOffset-(performance.now()-e));this.displayTimeoutId=setTimeout((()=>{this.displayTimeoutId=null,this.currentCaptions[this.currentCaptionIndex]?(a.isDisplayed=!0,t(!0,a.text),this.durationTimeoutId=setTimeout((()=>{this.durationTimeoutId=null,this.currentCaptionIndex++,i()}),a.duration)):t(!1)}),n)};i()}clearCaptions(){this._playAttemptActive=!1,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this.currentCaptions=[],this.currentCaptionIndex=0}wait(t){return new Promise((e=>setTimeout(e,t)))}destroy(){this.clearCaptions()}}const qt=["eyeBlinkLeft","eyeLookDownLeft","eyeLookInLeft","eyeLookOutLeft","eyeLookUpLeft","eyeSquintLeft","eyeWideLeft","eyeBlinkRight","eyeLookDownRight","eyeLookInRight","eyeLookOutRight","eyeLookUpRight","eyeSquintRight","eyeWideRight","jawForward","jawLeft","jawRight","jawOpen","mouthClose","mouthFunnel","mouthPucker","mouthLeft","mouthRight","mouthSmileLeft","mouthSmileRight","mouthFrownLeft","mouthFrownRight","mouthDimpleLeft","mouthDimpleRight","mouthStretchLeft","mouthStretchRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthPressLeft","mouthPressRight","mouthLowerDownLeft","mouthLowerDownRight","mouthUpperUpLeft","mouthUpperUpRight","browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","noseSneerLeft","noseSneerRight","tongueOut","headRotateZ"],Wt=["sil","aa","aa","O","E","RR","I","U","O","O","O","I","kk","RR","nn","SS","CH","TH","FF","DD","kk","PP"];class Gt extends G{constructor(t,e){super("talkingAvatar"),this.bus=t,this.avatarOrchestrator=e,this.talkingAvatar=null,this.isFullBody=!0,this.bodyGender="M",this.resetSpeakData(),this.prevViseme=null,this.frameDuration=1e3/E.constants.FRAME_RATE,this.currentTurnId=null,this.isStoppingSpeaking=!1,this._endedTurns=new Set,this.conversationStreamActive=!1,this._pendingEndReason=null,this._audioStartSent=!1,this._busHandlers=[],this.liveCaptions=new jt}resetSpeakData(){this.speak={audio:[],visemes:[],vtimes:[],vdurations:[],words:[],wtimes:[],wdurations:[],markers:[],mtimes:[],anim:{}},this.azureBlendShapes={frames:[],sbuffer:[],orderBuffer:{}},this.prevViseme=null}finalizeTurn(){this.handlePendingVisemes(),this.talkingAvatar.streamNotifyEnd(),this.resetSpeakData()}async init(t,e){try{this.talkingAvatar=new Bt(e,{ttsEndpoint:"/gtts/",cameraZoomEnable:!1,cameraPanEnable:!1,cameraRotateEnable:!1,cameraView:"full",avatarMood:"happy"});const i="male"===t.gender?"M":"F";this.bodyGender=i,await this.talkingAvatar.showAvatar({url:t.url,body:i}),this.addEventListeners(),this.setConnected(),this.lipsyncType=t.lipsyncType}catch(i){throw this.setFailed(),new Error("Error initializing TalkingAvatar: "+i)}}isRenderingActive(){return!!this.talkingAvatar?.isRunning}async suspendRendering(t="hidden"){if(this.isRenderingActive()){try{this.talkingAvatar?.streamInterrupt?.()}catch(e){}try{this.audioReader?.cancel()}catch(e){}try{this.lipsyncReader?.cancel()}catch(e){}if(this.conversationStreamActive)try{await this.stopConversationStream()}catch(e){}try{this.talkingAvatar?.stop?.()}catch(e){}try{this.liveCaptions?.clearCaptions?.()}catch(e){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}try{const e=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:e,reason:t})}catch(e){}}}async resumeRendering(){if(!this.isRenderingActive()){try{this.talkingAvatar?.start?.()}catch(t){}try{const t=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:t,reason:"resume"})}catch(t){}}}resumeAudioContext(){try{const t=this.talkingAvatar?.audioCtx;if(!t)return;"suspended"!==t.state&&"interrupted"!==t.state||t.resume().then((()=>{})).catch((t=>{}))}catch(t){}}getSpeechAnalyzerNode(){return this.talkingAvatar?.audioAnalyzerNode??null}startStreamPump(t){try{this.audioReader=t.readable.getReader()}catch(i){return}const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.audioReader.read();if(a)return;if(this.currentTurnId!==e){try{this.audioReader.cancel()}catch(t){}return}this._notifyAudioStart(e),this.handleSpeechSynthesizingChunk({audio:i})}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}startLipsyncPump(t){this.lipsyncReader=t.readable.getReader();const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.lipsyncReader.read();if(a)break;if(this.currentTurnId!==e){try{this.lipsyncReader.cancel()}catch(t){}break}switch(i.type){case"viseme":this.handleAddVisemeToStreaming(i);break;case"word":this.handleReceivedWordBoundaryEvent(i);break;case"blend":this.handleAddBlendShapestoStreaming(i)}}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}handleAudioEndOnce(t,e){const i=t??"__null__";this._endedTurns.has(i)||(this._endedTurns.add(i),this.avatarOrchestrator.sendEvent("AUDIO_END",{turnId:t,reason:e}))}async startConversationStream(){if(this.isRenderingActive()&&!this.conversationStreamActive)try{await this.talkingAvatar.streamStart({lipsyncType:this.lipsyncType,sampleRate:24e3},(({turnId:t,audioStartTime:e}={})=>{const i=t??this.currentTurnId;this._notifyAudioStart(i,e)}),(()=>{const t=this._pendingEndReason||"completed";this._pendingEndReason=null,this.handleAudioEndOnce(this.currentTurnId,t),this.currentTurnId&&(this.currentTurnId=null)})),this.conversationStreamActive=!0}catch(t){throw this.conversationStreamActive=!1,t}}async stopConversationStream(){if(this.conversationStreamActive)try{this.talkingAvatar.streamStop(),this.conversationStreamActive=!1}catch(t){this.conversationStreamActive=!1}}addEventListeners(){const t=(t,e)=>{this.bus.on(t,e),this._busHandlers.push([t,e])};t("event_command_Avatar_SetAvatarView",(t=>{this.setView(t.view)})),t("event_command_Avatar_SetAvatarMood",(t=>{this.talkingAvatar.setMood(t.mood)})),t("event_command_Avatar_PlayOrStopGesture",(t=>{"stop"!==t.gesture?this.talkingAvatar.playGesture(t.gesture,t.duration,t.mirror,t.ms):this.talkingAvatar.stopGesture()})),t("event_command_Avatar_PlayOrStopAnimation",(t=>{if("stop"===t.animation)return void this.talkingAvatar.stopAnimation();const e=function(t,e="M"){let i=[];switch(t){case"dance":i=Vt(Nt.dance,e,"Dances");break;case"expression_talking":i=Vt(Nt.expression,e,"Talking_Variations");break;case"expression_standing":i=Vt(Nt.expression,e,"Standing_Expressions");break;case"idle_standing":i=Vt(Nt.idle,e,"Standing_Idle");break;case"locomotion_walk":i=Vt(Nt.locomotion,e,"Walk_");break;case"locomotion_walk_backwards":i=Vt(Nt.locomotion,e,"Walk_Backwards");break;case"locomotion_walk_jump":i=Vt(Nt.locomotion,e,"Walk_Jump");break;case"locomotion_walk_strafe_left":i=Vt(Nt.locomotion,e,"Walk_Strafe_Left");break;case"locomotion_walk_strafe_right":i=Vt(Nt.locomotion,e,"Walk_Strafe_Right");break;case"locomotion_run":i=Vt(Nt.locomotion,e,"Run_");break;case"locomotion_run_backwards":i=Vt(Nt.locomotion,e,"Run_Backwards");break;case"locomotion_run_jump":i=Vt(Nt.locomotion,e,"Run_Jump");break;case"locomotion_run_strafe_left":i=Vt(Nt.locomotion,e,"Run_Strafe_Left");break;case"locomotion_run_strafe_right":i=Vt(Nt.locomotion,e,"Run_Strafe_Right");break;case"locomotion_jog":i=Vt(Nt.locomotion,e,"Jog_");break;case"locomotion_jog_backwards":i=Vt(Nt.locomotion,e,"Jog_Backwards");break;case"locomotion_jog_jump":i=Vt(Nt.locomotion,e,"Jog_Jump");break;case"locomotion_jog_strafe_left":i=Vt(Nt.locomotion,e,"Jog_Strafe_Left");break;case"locomotion_jog_strafe_right":i=Vt(Nt.locomotion,e,"Jog_Strafe_Right");break;case"locomotion_crouch_walk":i=Vt(Nt.locomotion,e,"Crouch_Walk");break;case"locomotion_crouch_strafe_left":i=Vt(Nt.locomotion,e,"Crouch_Strafe_Left");break;case"locomotion_crouch_strafe_right":i=Vt(Nt.locomotion,e,"Crouch_Strafe_Right");break;case"locomotion_crouchedwalk_backwards":i=Vt(Nt.locomotion,e,"CrouchedWalk_Backwards");break;case"locomotion_falling_idle":i=Vt(Nt.locomotion,e,"Falling_Idle");break;default:i=[]}return Ut(i)||Ut(Nt.locomotion.filter((t=>t.includes(`${e}_Walk_`))))||"locomotion\\M_Walk_001.fbx"}(t.animation,this.bodyGender);this.playAnimation(e,t.dur)})),t("event_command_Avatar_ControlAvatarLookAt",(t=>{"ahead"!==t.target?"point"!==t.target?"camera"!==t.target?"eye_contact"!==t.target||this.talkingAvatar.makeEyeContact(t.t):this.talkingAvatar.lookAtCamera(t.t):this.talkingAvatar.lookAt(t.x,t.y,t.t):this.talkingAvatar.lookAhead(t.t)})),t("event_command_UI_ClearCaptions",(()=>{try{this.liveCaptions?.clearCaptions?.()}catch(t){}}))}onResize(){this.talkingAvatar&&this.talkingAvatar.onResize()}handleSpeechSynthesizingChunk(t){switch(this.lipsyncType){case"blendshapes":this.talkingAvatar.streamAudio({audio:t.audio,anims:this.azureBlendShapes?.sbuffer.splice(0,this.azureBlendShapes?.sbuffer.length)});break;case"visemes":this.talkingAvatar.streamAudio({audio:t.audio,visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)});break;case"words":this.talkingAvatar.streamAudio({audio:t.audio,words:this.speak.words.splice(0,this.speak.words.length),wtimes:this.speak.wtimes.splice(0,this.speak.wtimes.length),wdurations:this.speak.wdurations.splice(0,this.speak.wdurations.length)})}}handleAddVisemeToStreaming(t){const e=Wt[t?.visemeId||0],i=t?.audioOffset||0;if(this.prevViseme){const t=this.prevViseme;let e=i-t.vtime;e<40&&(e=40),this.speak.visemes.push(t.viseme),this.speak.vtimes.push(t.vtime),this.speak.vdurations.push(e)}this.prevViseme={viseme:e,vtime:i}}handleAddBlendShapestoStreaming(t){const e=t?.BlendShapes;if(!e||0===e.length)return;const i=this._getBlendColumns(),a=e.length,n=Object.create(null);for(let o=0;o<i.length;o++){const[t,s]=i[o],r=new Float32Array(a);for(let i=0;i<a;i++){const a=e[i];r[i]=Array.isArray(a)||ArrayBuffer.isView(a)?a[t]??0:0}n[s]=r}const s=null!=t?.AudioOffset?Math.round(t.AudioOffset/1e4):(t?.FrameIndex||0)*this.frameDuration;this.azureBlendShapes.sbuffer.push({name:"blendshapes",delay:s,dt:this._getDtArray(a),vs:n})}handleReceivedWordBoundaryEvent(t){try{this.liveCaptions.handleWordBoundaryEvent(t)}catch(s){}const e=this.speak,i=t.text,a=t.audioOffset,n=t.duration;"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType&&e.words.length?e.words[e.words.length-1]+=i:"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType?(e.words.push(i),e.wtimes.push(a),e.wdurations.push(n)):"SpeechSynthesisBoundaryType.Sentence"===t.boundaryType&&a>500&&(e.markers.push((()=>{this.talkingAvatar.lookAtCamera(500)})),e.mtimes.push(a-500))}handlePendingVisemes(t=null){if("visemes"===this.lipsyncType&&this.prevViseme){const e=this.prevViseme;t||(t=100),this.speak.visemes.push(e.viseme),this.speak.vtimes.push(e.vtime),this.speak.vdurations.push(t),this.prevViseme=null}"visemes"===this.lipsyncType&&this.speak.visemes.length&&this.talkingAvatar.streamAudio({visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)}),"blendshapes"===this.lipsyncType&&this.azureBlendShapes.sbuffer.length&&this.talkingAvatar.streamAudio({anims:this.azureBlendShapes.sbuffer.splice(0,this.azureBlendShapes.sbuffer.length)})}async startStreaming(t,e,i){if(this.currentTurnId=i,this.isStoppingSpeaking=!1,this._audioStartSent=!1,!this.isRenderingActive()){try{t?.cancel?.()}catch(n){}try{e?.cancel?.()}catch(n){}return this.handleAudioEndOnce(i,"suppressed"),void(this.currentTurnId=null)}const a=i;this._endedTurns.delete(a??"__null__");try{this.startStreamPump(t),this.startLipsyncPump(e),this.conversationStreamActive||await this.startConversationStream()}catch(s){this.handleAudioEndOnce(a,"error"),this.currentTurnId===a&&(this.currentTurnId=null),this.isStoppingSpeaking=!1}}_notifyAudioStart(t,e=null){if(this._audioStartSent)return;this._audioStartSent=!0;const i=e??("undefined"!=typeof performance?performance.now():Date.now()),a=t??this.currentTurnId,n=a||0===a?{turnId:a,audioStartTime:i}:{audioStartTime:i},s=()=>{try{this.avatarOrchestrator?.sendEvent("AUDIO_START",n)}catch(t){}};"function"==typeof queueMicrotask?queueMicrotask(s):setTimeout(s,0)}interruptSpeaking(){if(!this.isStoppingSpeaking){this.isStoppingSpeaking=!0,this.conversationStreamActive&&this.talkingAvatar.streamInterrupt(),this.audioReader?.cancel(),this.lipsyncReader?.cancel(),this._pendingEndReason="interrupted";try{this.liveCaptions?.clearCaptions?.()}catch(t){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(t){}this.isStoppingSpeaking=!1}}setView(t){switch(t){case"full":this.talkingAvatar.setView("full");break;case"mid":this.talkingAvatar.setView("mid");break;case"upper":this.talkingAvatar.setView("upper");break;case"head":this.talkingAvatar.setView("head")}}playAnimation(t,e){const i=`https://sentifydfrontend.blob.core.windows.net/animationclips/${t}`;this.setView("full"),this.talkingAvatar.playAnimation(i,null,e)}reconnect(){}async destroy(){for(const[t,e]of this._busHandlers)try{this.bus.off(t,e)}catch{}this._busHandlers.length=0,this.isStoppingSpeaking=!1,this.conversationStreamActive&&await this.stopConversationStream(),this.talkingAvatar?.stop(),this.talkingAvatar=null}_getBlendColumns(){if(!this._blendCols){this._blendCols=[];for(let t=0;t<qt.length;t++){const e=qt[t];e&&this._blendCols.push([t,e])}}return this._blendCols}_getDtArray(t){this._dtCache||(this._dtCache=new Map);let e=this._dtCache.get(t);return e||(e=new Array(t).fill(this.frameDuration),this._dtCache.set(t,e)),e}}class Qt{constructor(t){if(!t)throw new Error("Cannot initialize SpeakingAvatar due to missing bus instance");this.voiceBot=null,this.chatSocket=null,this.bus=t,this.avatarOrchestrator=new pt(t),this.avatarOrchestrator.start(),this.connectionManager=this.createConnectionManager(this.bus,this.avatarOrchestrator),this.sessionData=lt.getInstance(),this.auth=new ct,this.connectionManager.registerConnectionModule(this.auth),this.voiceBargeInDetector=null}createConnectionManager(t,e){if(!t||!e)throw new Error("Missing dependencies for ConnectionManager creation.");return new mt(t,e)}async init(t){if(!t?.avatarContainer||!t.avatarAPIKey&&!t.tokenEndpoint||!t.avatarId||!t.targetApp)return!1;try{await this.initializeAuthentication(t);const{avatarParameters:e,avatarItem:i}=await this.setupAvatarData();return!(!e||!i||(this.avatarModule=new Gt(this.bus,this.avatarOrchestrator),await this.sessionData.init(e,i),await Promise.all([this.initializeChatSocket(),this.initializeVoiceBot(),this.initializeAvatarScene(i,t.avatarContainer)]),this.avatarOrchestrator.injectModules({talkingAvatar:this.avatarModule,chatSocket:this.chatSocket,voiceBot:this.voiceBot,conversation:this.sessionData.conversation}),await this.initializeVoiceBargeInDetector(),await this.connectionManager.waitUntilReady(),this.avatarOrchestrator.sendEvent("READY","SpeakingAAvatar.init"),0))}catch(e){return!1}}async initializeAuthentication(t){if(!(await this.auth.init(t.targetApp,t.avatarAPIKey||"",t.tokenEndpoint||"",t.avatarId)))throw new Error("Authentication initialization failed.")}async setupAvatarData(){const t=await this.auth.getAvatarParameters();if(!t)throw new Error("Failed to retrieve avatar parameters from authentication");return{avatarParameters:t,avatarItem:this.constructAvatarItem(t)}}constructAvatarItem(t){let e=t.avatarUrl;"ReadyPlayerMe"===t.avatarSource&&(e+="?morphTargets=ARKit,Oculus+Visemes,mouthOpen,mouthSmile,eyesClosed,eyesLookUp,eyesLookDown&textureSizeLimit=1024&textureFormat=png");let i=t.lipsyncType||"visemes";return{id:t.avatarSourceId,type:E?.avatar?.type,url:e,source:t.avatarSource,bodyType:t.bodyType,gender:t.gender,lipsyncType:i}}async initializeChatSocket(){try{X.resetInstance?.()}catch{}this.chatSocket=X.getInstance(this.bus,this.auth,this.sessionData,this.avatarOrchestrator),this.connectionManager.registerConnectionModule(this.chatSocket),await this.chatSocket.init()}async initializeVoiceBot(){this.voiceBot=await J.build(this.bus,this.avatarOrchestrator,this.auth,this.sessionData),this.connectionManager.registerConnectionModule(this.voiceBot.speechService)}async initializeVoiceBargeInDetector(){if(!this.voiceBargeInDetector&&!1!==E?.speech?.bargeIn?.enabled)try{this.voiceBargeInDetector=new et({talkingAvatar:this.avatarModule,avatarOrchestrator:this.avatarOrchestrator,config:E?.speech?.bargeIn}),await this.voiceBargeInDetector.init()}catch(t){this.voiceBargeInDetector=null}}async setBargeInEnabled(t){if(E?.speech?.bargeIn&&(E.speech.bargeIn.enabled=t),t)this.voiceBargeInDetector||this.avatarModule&&this.avatarOrchestrator&&await this.initializeVoiceBargeInDetector();else if(this.voiceBargeInDetector){try{this.voiceBargeInDetector.destroy()}catch(e){}this.voiceBargeInDetector=null}}async initializeAvatarScene(t,e){try{if(!this.avatarModule)throw new Error("Avatar module not initialized.");this.connectionManager.registerConnectionModule(this.avatarModule),await this.avatarModule.init(t,e)}catch(i){throw i}}destroy(){try{X.resetInstance?.()}catch{}this.voiceBot?.destroy?.(),this.voiceBargeInDetector?.destroy?.(),this.voiceBargeInDetector=null,this.avatarModule?.destroy?.(),this.connectionManager?.destroy?.(),this.sessionData?.destroy?.(),this.auth?.destroy?.(),this.avatarOrchestrator?.destroy?.()}}class Yt extends EventTarget{constructor(){super(),this._listeners=new Map,this._disposers=new Set,this._isDisposed=!1,this._globalListeners=new Set}on(t,e){if(this._isDisposed)return()=>{};if("*"===t)return this.onAll(e);const i=t=>{try{const i=t.detail;e(i)}catch(i){}};this._listeners.has(t)||this._listeners.set(t,new Map),this._listeners.get(t).set(e,i),this.addEventListener(t,i);const a=()=>{this._isDisposed||(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e),this._disposers.delete(a))};return this._disposers.add(a),a}off(t,e){if("*"===t)return this.offAll(e);const i=this._listeners.get(t)?.get(e);i&&(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e))}emit(t,e=void 0){if(this._isDisposed)return;const i=new CustomEvent(t,{detail:e,bubbles:!1,cancelable:!1});this.dispatchEvent(i),this._globalListeners.forEach((i=>{try{i(t,e)}catch(a){}}))}onAll(t){if(this._isDisposed)return()=>{};this._globalListeners.add(t);const e=()=>{this._isDisposed||(this._globalListeners.delete(t),this._disposers.delete(e))};return this._disposers.add(e),e}offAll(t){this._globalListeners.delete(t)}clear(){this._listeners.forEach(((t,e)=>{t.forEach(((t,i)=>{this.removeEventListener(e,t)}))})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear()}dispose(){this._isDisposed||(this._disposers.forEach((t=>{try{t()}catch(e){}})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear(),this._isDisposed=!0)}get disposerCount(){return this._disposers.size}get isDisposed(){return this._isDisposed}get listenerCount(){let t=this._globalListeners.size;return this._listeners.forEach((e=>{t+=e.size})),t}}const Xt="en",Zt={en:{start:"Start Conversation",connect:"Connect",endConversation:"End Conversation",restartConversation:"Restart Conversation",hideTyping:"Hide typing input",showTyping:"Show typing input",reconnecting:"Reconnecting...",waitForResponse:"Please wait for response...",typeHere:"Type here.",noMessagesYet:"No messages yet...",conversationStatus:"Conversation Status",conversationInProgress:"Conversation In Progress",conversationStopped:"Conversation Stopped",startConversation:"Start Conversation",downloadConversation:"Download Conversation",liveCaptions:"Live captions",toggleChatbot:"Toggle avatar chatbot",avatar:"Avatar",chat:"Chat",statusInitializing:"Hang tight, we're waking up the assistant!",statusReconnecting:"Connection issue, attempting to reconnect...",statusFailed:"Connection failed. Manual action may be required.",statusInvalidConfiguration:"The avatar is not configured correctly, contact the admin.",close:"Close",lastAssistantMessage:"Last assistant message",fullBodyView:"Full body view",upperBodyView:"Upper body view",previousConversationFound:"Previous conversation found - please choose an option to proceed",secureFormTitle:"Secure Form",secureFormDescription:"Enter your information.",name:"Name*",namePlaceholder:"Enter your name",phoneNumber:"Phone Number",phonePlaceholder:"Enter your phone number",email:"Email",emailPlaceholder:"Enter your email",secureFormNote:"Your information will not be shared with the LLM and will not be stored after this session. By sending you agree to share your info to get additional support.",save:"Save",send:"Send",cancel:"Cancel",conversationEndedPrompt:"Conversation ended. Please rate your satisfaction with the conversation.",submit:"Submit",skip:"Skip",consentTitle:"Consent for AI conversation",consentInfo1:"For general information only — no medical, legal, financial, or safety advice.",consentInfo2:"We use session storage and send your input to provide replies. We don’t keep your conversation or personal info after this session.",consentReadOur:"Read our",consentTermsLabel:"Terms",consentAnd:"and",consentPrivacyLabel:"Privacy Policy",consentMoreDetails:"for more details.",consentInfo4:"(Your consent applies to this session only and clears when you close the tab/window)",consentAccept:"I agree",consentDecline:"Decline",consentAcceptAria:"I agree – start chat",consentDeclineAria:"Decline",interruptSpeaking:"Interrupt speaking avatar",turnOnMic:"Turn on microphone",turnOffMic:"Turn off microphone",tapToSpeak:"Tap to speak",startConversationReminder:"Start a conversation to chat.",chatPlaceholderTitle:"Ready to chat?",chatPlaceholderDescription:"Start a conversation to continue in text mode.",enterInfoOnMobile:"Enter your information in User Information page",waitCurrentResponse:"Please wait for the current response before sending another message.",resumeConversationFailedNewStarted:"We couldn't resume your previous conversation. A new one has been started instead.",end:"End",endConversationPrompt:"Would you like to end the conversation? Ending it will permanently delete the conversation history.",restartConversationPrompt:"Are you sure you want to start a new conversation? Current conversation will be deleted.",newConversation:"New",conversationExpiredPrompt:"This conversation has expired and cannot be resumed. Would you like to download a copy and end or end only?",conversationExpiredResumePrompt:"Your previous conversation has expired and cannot be resumed. Would you like to download a copy of your conversation history?",downloadAndClear:"Download & Clear",downloadAndStartNew:"Download & Start New",startNew:"Start New",ok:"OK",download:"Download",onlyClear:"Only Clear",confirm:"Confirm",alertGenericError:"An error occurred.",alertFailedEndConversation:"Failed to end the conversation. Please try again.",alertFailedClearConversation:"Failed to clear the conversation.",alertCouldNotStartListening:"Could not start listening. Please try again.",alertSomeErrorOccurred:"Some error occurred. Please try again.",alertWaitForAIResponse:"Please wait for the AI response before starting to speak.",alertVoiceServicesUnavailable:"Unable to connect to voice services. Please try again later.",alertServiceTemporarilyUnavailable:"Service is temporarily unavailable. Please try again.",alertTooManyRequests:"Too many simultaneous requests. Please wait a moment and try again.",alertConnectionIssue:"Connection issue detected. Please check your internet connection and try again.",alertResponseTimeout:"Response timeout. Please try again.",alertServiceBusy:"Voice service is currently busy. Please try again in a few minutes.",alertMicrophoneStartFailed:"Failed to start listening. Make sure your microphone is working.",alertMicrophoneCheckSettings:"Failed to start listening. Please check your microphone settings.",alertSpeechRecognitionSetupFailed:"Speech recognition setup failed. Please refresh the page and try again.",alertMicrophoneAccessDenied:"Microphone access denied. Please allow microphone access in your browser settings and refresh the page.",alertNoMicrophoneDetected:"No microphone detected. Please connect a microphone and refresh the page.",alertMicrophoneError:"Microphone error. Please check your microphone."},fr:{start:"DĆ©marrer la conversation",connect:"Se connecter",endConversation:"Terminer la conversation",restartConversation:"RedĆ©marrer la conversation",hideTyping:"Masquer la saisie",showTyping:"Afficher la saisie",reconnecting:"Reconnexion...",waitForResponse:"Veuillez attendre la rĆ©ponse...",typeHere:"Tapez ici.",noMessagesYet:"Pas encore de messages...",conversationStatus:"Ɖtat de la conversation",conversationInProgress:"Conversation en cours",conversationStopped:"Conversation terminĆ©e",startConversation:"Commencer la conversation",downloadConversation:"TĆ©lĆ©charger la conversation",liveCaptions:"Sous-titres en direct",toggleChatbot:"Afficher/Masquer l'avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Patientez, nous rĆ©veillons l'assistant !",statusReconnecting:"ProblĆØme de connexion, tentative de reconnexion...",statusFailed:"Ɖchec de la connexion. Une action manuelle peut ĆŖtre nĆ©cessaire.",statusInvalidConfiguration:"L'avatar n'est pas configurĆ© correctement, contactez l'administrateur.",close:"Fermer",lastAssistantMessage:"Dernier message de l'assistant",fullBodyView:"Vue du corps entier",upperBodyView:"Vue du haut du corps",previousConversationFound:"Conversation prĆ©cĆ©dente trouvĆ©e - veuillez choisir une option pour continuer.",secureFormTitle:"Formulaire sĆ©curisĆ©",secureFormDescription:"Saisissez vos informations.",name:"Nom*",namePlaceholder:"Entrez votre nom",phoneNumber:"NumĆ©ro de tĆ©lĆ©phone",phonePlaceholder:"Entrez votre numĆ©ro de tĆ©lĆ©phone",email:"E-mail",emailPlaceholder:"Entrez votre e-mail",secureFormNote:"Vos informations ne seront pas partagĆ©es avec le LLM et ne seront pas conservĆ©es aprĆØs cette session. En envoyant, vous acceptez de partager vos informations pour obtenir un support supplĆ©mentaire.",save:"Enregistrer",send:"Envoyer",cancel:"Annuler",conversationEndedPrompt:"Conversation terminĆ©e. Veuillez Ć©valuer votre satisfaction.",submit:"Envoyer",skip:"Ignorer",consentTitle:"Consentement pour la conversation IA",consentInfo1:"ƀ titre informatif uniquement — aucun conseil mĆ©dical, juridique, financier ou de sĆ©curitĆ©.",consentInfo2:"Nous utilisons le stockage de session et envoyons votre saisie pour fournir des rĆ©ponses. Nous ne conservons pas votre conversation ni vos informations personnelles aprĆØs cette session.",consentReadOur:"Lisez nos",consentTermsLabel:"Conditions",consentAnd:"et",consentPrivacyLabel:"Politique de confidentialitĆ©",consentMoreDetails:"pour plus de dĆ©tails.",consentInfo4:"(Votre consentement s'applique uniquement Ć  cette session et est rĆ©initialisĆ© lorsque vous fermez l'onglet ou la fenĆŖtre)",consentAccept:"J'accepte",consentDecline:"Refuser",consentAcceptAria:"J'accepte – dĆ©marrer le chat",consentDeclineAria:"Refuser",interruptSpeaking:"Interrompre l'avatar",turnOnMic:"Activer le microphone",turnOffMic:"DĆ©sactiver le microphone",tapToSpeak:"Appuyez pour parler",startConversationReminder:"DĆ©marrez une conversation pour discuter.",chatPlaceholderTitle:"PrĆŖt Ć  discuter ?",chatPlaceholderDescription:"Lancez une conversation pour continuer en mode texte.",enterInfoOnMobile:"Saisissez vos informations dans la page Informations utilisateur",waitCurrentResponse:"Veuillez attendre la rĆ©ponse en cours avant d'envoyer un autre message.",resumeConversationFailedNewStarted:"Nous n'avons pas pu reprendre votre conversation prĆ©cĆ©dente. Une nouvelle a Ć©tĆ© dĆ©marrĆ©e Ć  la place.",end:"Terminer",endConversationPrompt:"Souhaitez-vous terminer la conversation ? Cela supprimera dĆ©finitivement l'historique de la conversation.",restartConversationPrompt:"Voulez-vous dĆ©marrer une nouvelle conversation ? La conversation actuelle sera supprimĆ©e.",newConversation:"Nouveau",conversationExpiredPrompt:"Cette conversation a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous en tĆ©lĆ©charger une copie puis la supprimer, ou simplement la supprimer ?",conversationExpiredResumePrompt:"Votre conversation prĆ©cĆ©dente a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous tĆ©lĆ©charger une copie de votre historique de conversation ?",downloadAndClear:"TĆ©lĆ©charger et effacer",downloadAndStartNew:"TĆ©lĆ©charger et dĆ©marrer",startNew:"Nouvelle conv.",onlyClear:"Effacer uniquement",confirm:"Confirmer",ok:"OK",download:"TĆ©lĆ©charger",alertGenericError:"Une erreur s'est produite.",alertFailedEndConversation:"Ɖchec de la fin de la conversation. Veuillez rĆ©essayer.",alertFailedClearConversation:"Ɖchec de l'effacement de la conversation.",alertCouldNotStartListening:"Impossible de dĆ©marrer l'Ć©coute. Veuillez rĆ©essayer.",alertSomeErrorOccurred:"Une erreur s'est produite. Veuillez rĆ©essayer.",alertWaitForAIResponse:"Veuillez attendre la rĆ©ponse de l'IA avant de commencer Ć  parler.",alertVoiceServicesUnavailable:"Impossible de se connecter aux services vocaux. Veuillez rĆ©essayer plus tard.",alertServiceTemporarilyUnavailable:"Service temporairement indisponible. Veuillez rĆ©essayer.",alertTooManyRequests:"Trop de demandes simultanĆ©es. Veuillez patienter un instant et rĆ©essayer.",alertConnectionIssue:"ProblĆØme de connexion dĆ©tectĆ©. Veuillez vĆ©rifier votre connexion internet et rĆ©essayer.",alertResponseTimeout:"DĆ©lai de rĆ©ponse dĆ©passĆ©. Veuillez rĆ©essayer.",alertServiceBusy:"Le service vocal est actuellement occupĆ©. Veuillez rĆ©essayer dans quelques minutes.",alertMicrophoneStartFailed:"Impossible de dĆ©marrer l'Ć©coute. Assurez-vous que votre microphone fonctionne.",alertMicrophoneCheckSettings:"Impossible de dĆ©marrer l'Ć©coute. Veuillez vĆ©rifier les paramĆØtres de votre microphone.",alertSpeechRecognitionSetupFailed:"Ɖchec de la configuration de la reconnaissance vocale. Veuillez actualiser la page et rĆ©essayer.",alertMicrophoneAccessDenied:"AccĆØs au microphone refusĆ©. Veuillez autoriser l'accĆØs au microphone dans les paramĆØtres de votre navigateur et actualiser la page.",alertNoMicrophoneDetected:"Aucun microphone dĆ©tectĆ©. Veuillez connecter un microphone et actualiser la page.",alertMicrophoneError:"Erreur de microphone. Veuillez vĆ©rifier votre microphone."},de:{start:"Starten Sie die Konversation",connect:"Verbinden",endConversation:"GesprƤch beenden",restartConversation:"GesprƤch neu starten",hideTyping:"Eingabefeld ausblenden",showTyping:"Eingabefeld anzeigen",reconnecting:"Verbindung wird wiederhergestellt...",waitForResponse:"Bitte auf die Antwort warten...",typeHere:"Hier eingeben.",noMessagesYet:"Noch keine Nachrichten...",conversationStatus:"GesprƤchsstatus",conversationInProgress:"GesprƤch lƤuft",conversationStopped:"GesprƤch beendet",startConversation:"GesprƤch starten",downloadConversation:"GesprƤch herunterladen",liveCaptions:"Live-Untertitel",toggleChatbot:"Avatar-Chatbot ein-/ausblenden",avatar:"Avatar",chat:"Chat",statusInitializing:"Einen Moment, der Assistent wird gestartet!",statusReconnecting:"Verbindungsproblem, versuche erneut zu verbinden...",statusFailed:"Verbindung fehlgeschlagen. Mƶglicherweise ist ein manueller Eingriff erforderlich.",statusInvalidConfiguration:"Der Avatar ist nicht korrekt konfiguriert, wenden Sie sich an den Administrator.",close:"Schließen",lastAssistantMessage:"Letzte Nachricht des Assistenten",fullBodyView:"Ganzkƶrperansicht",upperBodyView:"Oberkƶrperansicht",previousConversationFound:"Früheres GesprƤch gefunden – bitte wƤhlen Sie eine Option, um fortzufahren",secureFormTitle:"Sicheres Formular",secureFormDescription:"Geben Sie Ihre Informationen ein.",name:"Name*",namePlaceholder:"Geben Sie Ihren Namen ein",phoneNumber:"Telefonnummer",phonePlaceholder:"Geben Sie Ihre Telefonnummer ein",email:"E-Mail",emailPlaceholder:"Geben Sie Ihre E-Mail ein",secureFormNote:"Ihre Informationen werden nicht mit dem LLM geteilt und nach dieser Sitzung nicht gespeichert. Mit dem Absenden erklƤren Sie sich einverstanden, Ihre Daten zu teilen, um zusƤtzliche Unterstützung zu erhalten.",save:"Speichern",send:"Senden",cancel:"Abbrechen",conversationEndedPrompt:"GesprƤch beendet. Bitte bewerten Sie Ihre Zufriedenheit.",submit:"Senden",skip:"Überspringen",consentTitle:"Einwilligung für das KI-GesprƤch",consentInfo1:"Nur zu allgemeinen Informationszwecken – keine medizinischen, rechtlichen, finanziellen oder sicherheitsrelevanten RatschlƤge.",consentInfo2:"Wir verwenden den Sitzungspeicher und senden Ihre Eingaben, um Antworten bereitzustellen. Wir speichern Ihr GesprƤch oder persƶnliche Daten nach dieser Sitzung nicht.",consentReadOur:"Lesen Sie unsere",consentTermsLabel:"Nutzungsbedingungen",consentAnd:"und",consentPrivacyLabel:"DatenschutzerklƤrung",consentMoreDetails:"für weitere Informationen.",consentInfo4:"(Ihre Einwilligung gilt nur für diese Sitzung und wird zurückgesetzt, wenn Sie den Tab oder das Fenster schließen)",consentAccept:"Ich stimme zu",consentDecline:"Ablehnen",consentAcceptAria:"Ich stimme zu – Chat starten",consentDeclineAria:"Ablehnen",interruptSpeaking:"Sprechenden Avatar unterbrechen",turnOnMic:"Mikrofon einschalten",turnOffMic:"Mikrofon ausschalten",tapToSpeak:"Tippen zum Sprechen",startConversationReminder:"Starten Sie ein GesprƤch, um zu chatten.",chatPlaceholderTitle:"Bereit zum Chatten?",chatPlaceholderDescription:"Starten Sie ein GesprƤch, um im Textmodus fortzufahren.",enterInfoOnMobile:"Geben Sie Ihre Daten auf der Seite Benutzerinformationen ein",waitCurrentResponse:"Bitte warten Sie die aktuelle Antwort ab, bevor Sie eine weitere Nachricht senden.",resumeConversationFailedNewStarted:"Wir konnten Ihr vorheriges GesprƤch nicht fortsetzen. Stattdessen wurde ein neues gestartet.",end:"Beenden",endConversationPrompt:"Mƶchten Sie das GesprƤch beenden? Dadurch wird der GesprƤchsverlauf dauerhaft gelƶscht.",restartConversationPrompt:"Mƶchten Sie ein neues GesprƤch beginnen? Das aktuelle GesprƤch wird gelƶscht.",newConversation:"Neu",conversationExpiredPrompt:"Dieses GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie herunterladen und lƶschen oder nur lƶschen?",conversationExpiredResumePrompt:"Ihr vorheriges GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie Ihres GesprƤchsverlaufs herunterladen?",downloadAndClear:"Herunterladen & lƶschen",downloadAndStartNew:"Herunterladen & Neu starten",startNew:"Neu starten",onlyClear:"Nur lƶschen",confirm:"BestƤtigen",ok:"OK",download:"Herunterladen",alertGenericError:"Ein Fehler ist aufgetreten.",alertFailedEndConversation:"Das GesprƤch konnte nicht beendet werden. Bitte versuchen Sie es erneut.",alertFailedClearConversation:"Das GesprƤch konnte nicht gelƶscht werden.",alertCouldNotStartListening:"Zuhƶren konnte nicht gestartet werden. Bitte versuchen Sie es erneut.",alertSomeErrorOccurred:"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",alertWaitForAIResponse:"Bitte warten Sie auf die KI-Antwort, bevor Sie zu sprechen beginnen.",alertVoiceServicesUnavailable:"Verbindung zu Sprachdiensten nicht mƶglich. Bitte versuchen Sie es spƤter erneut.",alertServiceTemporarilyUnavailable:"Der Dienst ist vorübergehend nicht verfügbar. Bitte versuchen Sie es erneut.",alertTooManyRequests:"Zu viele gleichzeitige Anfragen. Bitte warten Sie einen Moment und versuchen Sie es erneut.",alertConnectionIssue:"Verbindungsproblem erkannt. Bitte überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",alertResponseTimeout:"Zeitüberschreitung bei der Antwort. Bitte versuchen Sie es erneut.",alertServiceBusy:"Der Sprachdienst ist derzeit ausgelastet. Bitte versuchen Sie es in einigen Minuten erneut.",alertMicrophoneStartFailed:"Zuhƶren konnte nicht gestartet werden. Stellen Sie sicher, dass Ihr Mikrofon funktioniert.",alertMicrophoneCheckSettings:"Zuhƶren konnte nicht gestartet werden. Bitte überprüfen Sie Ihre Mikrofoneinstellungen.",alertSpeechRecognitionSetupFailed:"Einrichtung der Spracherkennung fehlgeschlagen. Bitte aktualisieren Sie die Seite und versuchen Sie es erneut.",alertMicrophoneAccessDenied:"Mikrofonzugriff verweigert. Bitte erlauben Sie den Mikrofonzugriff in Ihren Browsereinstellungen und aktualisieren Sie die Seite.",alertNoMicrophoneDetected:"Kein Mikrofon erkannt. Bitte schließen Sie ein Mikrofon an und aktualisieren Sie die Seite.",alertMicrophoneError:"Mikrofonfehler. Bitte überprüfen Sie Ihr Mikrofon."},es:{start:"Iniciar conversación",connect:"Conectar",endConversation:"Terminar conversación",restartConversation:"Reiniciar conversación",hideTyping:"Ocultar entrada de texto",showTyping:"Mostrar entrada de texto",reconnecting:"Reconectando...",waitForResponse:"Espere la respuesta...",typeHere:"Escriba aquĆ­.",noMessagesYet:"TodavĆ­a no hay mensajes...",conversationStatus:"Estado de la conversación",conversationInProgress:"Conversación en curso",conversationStopped:"Conversación detenida",startConversation:"Iniciar conversación",downloadConversation:"Descargar conversación",liveCaptions:"SubtĆ­tulos en vivo",toggleChatbot:"Mostrar/ocultar avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Espere, estamos iniciando el asistente",statusReconnecting:"Problema de conexión, intentando reconectar...",statusFailed:"La conexión falló. Puede ser necesaria una acción manual.",statusInvalidConfiguration:"El avatar no estĆ” configurado correctamente, contacte al administrador.",close:"Cerrar",lastAssistantMessage:"Último mensaje del asistente",fullBodyView:"Vista de cuerpo completo",upperBodyView:"Vista de torso",previousConversationFound:"Se encontró una conversación anterior; elija una opción para continuar",secureFormTitle:"Formulario seguro",secureFormDescription:"Ingrese su información.",name:"Nombre*",namePlaceholder:"Ingrese su nombre",phoneNumber:"NĆŗmero de telĆ©fono",phonePlaceholder:"Ingrese su nĆŗmero de telĆ©fono",email:"Correo electrónico",emailPlaceholder:"Ingrese su correo electrónico",secureFormNote:"Su información no se compartirĆ” con el LLM ni se almacenarĆ” despuĆ©s de esta sesión. Al enviar, acepta compartir su información para obtener soporte adicional.",save:"Guardar",send:"Enviar",cancel:"Cancelar",conversationEndedPrompt:"Conversación finalizada. Califique su satisfacción.",submit:"Enviar",skip:"Omitir",consentTitle:"Consentimiento para conversación con IA",consentInfo1:"Solo con fines informativos — sin consejos mĆ©dicos, legales, financieros ni de seguridad.",consentInfo2:"Usamos almacenamiento de sesión y enviamos su entrada para responder. No guardamos su conversación ni datos personales tras esta sesión.",consentReadOur:"Lea nuestros",consentTermsLabel:"TĆ©rminos",consentAnd:"y",consentPrivacyLabel:"PolĆ­tica de privacidad",consentMoreDetails:"para mĆ”s detalles.",consentInfo4:"(Su consentimiento se aplica solo a esta sesión y se borra al cerrar la pestaƱa o ventana)",consentAccept:"Acepto",consentDecline:"Rechazar",consentAcceptAria:"Acepto – iniciar chat",consentDeclineAria:"Rechazar",interruptSpeaking:"Interrumpir avatar que habla",turnOnMic:"Activar micrófono",turnOffMic:"Desactivar micrófono",tapToSpeak:"Toca para hablar",startConversationReminder:"Inicie una conversación para chatear.",chatPlaceholderTitle:"ĀæListo para chatear?",chatPlaceholderDescription:"Inicia una conversación para continuar en modo texto.",enterInfoOnMobile:"Ingrese su información en la pĆ”gina de usuario",waitCurrentResponse:"Espere la respuesta actual antes de enviar otro mensaje.",resumeConversationFailedNewStarted:"No pudimos reanudar su conversación anterior. En su lugar, se ha iniciado una nueva.",end:"Terminar",endConversationPrompt:"ĀæDesea terminar la conversación? Esto eliminarĆ” el historial permanentemente.",restartConversationPrompt:"ĀæSeguro que quiere iniciar una nueva conversación? La conversación actual se eliminarĆ”.",newConversation:"Nueva",conversationExpiredPrompt:"Esta conversación ha expirado y no se puede reanudar. ĀæDesea descargar una copia y borrar o solo borrar?",conversationExpiredResumePrompt:"Su conversación anterior ha expirado y no se puede reanudar. ĀæDesea descargar una copia de su historial de conversación?",downloadAndClear:"Descargar y borrar",downloadAndStartNew:"Descargar e iniciar",startNew:"Iniciar nueva",onlyClear:"Solo borrar",confirm:"Confirmar",ok:"OK",download:"Descargar",alertGenericError:"Se produjo un error.",alertFailedEndConversation:"No se pudo terminar la conversación. Por favor, intĆ©ntelo de nuevo.",alertFailedClearConversation:"No se pudo borrar la conversación.",alertCouldNotStartListening:"No se pudo iniciar la escucha. Por favor, intĆ©ntelo de nuevo.",alertSomeErrorOccurred:"Se produjo un error. Por favor, intĆ©ntelo de nuevo.",alertWaitForAIResponse:"Por favor, espere la respuesta de la IA antes de comenzar a hablar.",alertVoiceServicesUnavailable:"No se puede conectar a los servicios de voz. Por favor, intĆ©ntelo mĆ”s tarde.",alertServiceTemporarilyUnavailable:"El servicio no estĆ” disponible temporalmente. Por favor, intĆ©ntelo de nuevo.",alertTooManyRequests:"Demasiadas solicitudes simultĆ”neas. Por favor, espere un momento e intĆ©ntelo de nuevo.",alertConnectionIssue:"Problema de conexión detectado. Por favor, verifique su conexión a internet e intĆ©ntelo de nuevo.",alertResponseTimeout:"Tiempo de respuesta agotado. Por favor, intĆ©ntelo de nuevo.",alertServiceBusy:"El servicio de voz estĆ” ocupado actualmente. Por favor, intĆ©ntelo en unos minutos.",alertMicrophoneStartFailed:"No se pudo iniciar la escucha. AsegĆŗrese de que su micrófono funcione.",alertMicrophoneCheckSettings:"No se pudo iniciar la escucha. Por favor, verifique la configuración de su micrófono.",alertSpeechRecognitionSetupFailed:"Error en la configuración del reconocimiento de voz. Por favor, actualice la pĆ”gina e intĆ©ntelo de nuevo.",alertMicrophoneAccessDenied:"Acceso al micrófono denegado. Por favor, permita el acceso al micrófono en la configuración de su navegador y actualice la pĆ”gina.",alertNoMicrophoneDetected:"No se detectó ningĆŗn micrófono. Por favor, conecte un micrófono y actualice la pĆ”gina.",alertMicrophoneError:"Error de micrófono. Por favor, verifique su micrófono."},ar:{start:"Ų§ŲØŲÆŲ£ المحادثة",connect:"اتصل",endConversation:"؄نهاؔ المحادثة",restartConversation:"Ų„Ų¹Ų§ŲÆŲ© ŲØŲÆŲ” المحادثة",hideTyping:"؄خفاؔ حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",showTyping:"؄ظهار حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",reconnecting:"Ų¬Ų§Ų±Ł Ų„Ų¹Ų§ŲÆŲ© الاتصال...",waitForResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد...",typeHere:"اكتب هنا.",noMessagesYet:"لا توجد رسائل ŲØŲ¹ŲÆ...",conversationStatus:"حالة المحادثة",conversationInProgress:"المحادثة جارية",conversationStopped:"المحادثة Ł…ŲŖŁˆŁ‚ŁŲ©",startConversation:"Ų§ŲØŲÆŲ£ المحادثة",downloadConversation:"ŲŖŁ†Ų²ŁŠŁ„ المحادثة",liveCaptions:"ŲŖŲ¹Ł„ŁŠŁ‚Ų§ŲŖ Ł†ŲµŁŠŲ© Ł…ŲØŲ§Ų“Ų±Ų©",toggleChatbot:"؄ظهار/؄خفاؔ روبوت المحادثة",avatar:"أفاتار",chat:"ŲÆŲ±ŲÆŲ“Ų©",statusInitializing:"ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ų§Ł†ŲŖŲøŲ§Ų±ŲŒ Ł†Ł‚ŁˆŁ… ŲØŲŖŲ“ŲŗŁŠŁ„ الأفاتار!",statusReconnecting:"Ł…Ų“ŁƒŁ„Ų© في Ų§Ł„Ų§ŲŖŲµŲ§Ł„ŲŒ Ų¬Ų§Ų±Ł Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© مجددًا...",statusFailed:"فؓل الاتصال. قد ŁŠŲŖŲ·Ł„ŲØ الأمر تدخلاً ŁŠŲÆŁˆŁŠŁ‹Ų§.",statusInvalidConfiguration:"الأفاتار غير Ł…Ł‡ŁŠŲ£ ŲØŲ“ŁƒŁ„ صحيح، ŁŠŲ±Ų¬Ł‰ Ų§Ł„ŲŖŁˆŲ§ŲµŁ„ Ł…Ų¹ Ų§Ł„Ł…Ų³Ų¤ŁˆŁ„.",close:"؄غلاق",lastAssistantMessage:"Ų¢Ų®Ų± رسالة من الأفاتار",fullBodyView:"Ų¹Ų±Ų¶ ŁƒŲ§Ł…Ł„ للجسم",upperBodyView:"Ų¹Ų±Ų¶ للجزؔ Ų§Ł„Ų¹Ł„ŁˆŁŠ",previousConversationFound:"ŲŖŁ… Ų§Ł„Ų¹Ų«ŁˆŲ± على Ł…Ų­Ų§ŲÆŲ«Ų© سابقة - ŁŠŲ±Ų¬Ł‰ اختيار خيار للمتابعة",secureFormTitle:"Ł†Ł…ŁˆŲ°Ų¬ آمن",secureFormDescription:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ.",name:"الاسم*",namePlaceholder:"أدخل Ų§Ų³Ł…Łƒ",phoneNumber:"رقم الهاتف",phonePlaceholder:"أدخل رقم Ł‡Ų§ŲŖŁŁƒ",email:"Ų§Ł„ŲØŲ±ŁŠŲÆ Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",emailPlaceholder:"أدخل بريدك Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",secureFormNote:"لن ŲŖŲŖŁ… Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł…Ų¹ Ł†Ł…ŁˆŲ°Ų¬ اللغة ŁˆŁ„Ł† ŁŠŲŖŁ… ŲŖŲ®Ų²ŁŠŁ†Ł‡Ų§ ŲØŲ¹ŲÆ هذه الجلسة. بال؄رسال ŁŲ„Ł†Łƒ ŲŖŁˆŲ§ŁŁ‚ على Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł„Ł„Ų­ŲµŁˆŁ„ على دعم ؄ضافي.",save:"حفظ",send:"Ų„Ų±Ų³Ų§Ł„",cancel:"؄لغاؔ",conversationEndedPrompt:"انتهت المحادثة. ŁŠŲ±Ų¬Ł‰ ŲŖŁ‚ŁŠŁŠŁ… مدى رضاك.",submit:"Ų„Ų±Ų³Ų§Ł„",skip:"تخطي",consentTitle:"Ł…ŁˆŲ§ŁŁ‚Ų© على Ł…Ų­Ų§ŲÆŲ«Ų© Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ",consentInfo1:"Ł„Ł„Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ العامة فقط — ŲØŲÆŁˆŁ† نصائح طبية أو Ł‚Ų§Ł†ŁˆŁ†ŁŠŲ© أو Ł…Ų§Ł„ŁŠŲ© أو Ų£Ł…Ł†ŁŠŲ©.",consentInfo2:"نستخدم ŲŖŲ®Ų²ŁŠŁ† الجلسة ŁˆŁ†Ų±Ų³Ł„ Ł…ŲÆŲ®Ł„Ų§ŲŖŁƒ Ł„ŲŖŁ‚ŲÆŁŠŁ… Ų§Ł„Ų±ŲÆŁˆŲÆ. لا نحتفظ ŲØŁ…Ų­Ų§ŲÆŲ«ŲŖŁƒ أو ŲØŁŠŲ§Ł†Ų§ŲŖŁƒ Ų§Ł„Ų“Ų®ŲµŁŠŲ© ŲØŲ¹ŲÆ هذه الجلسة.",consentReadOur:"اقرأ",consentTermsLabel:"Ų§Ł„Ų“Ų±ŁˆŲ·",consentAnd:"و",consentPrivacyLabel:"سياسة Ų§Ł„Ų®ŲµŁˆŲµŁŠŲ©",consentMoreDetails:"Ł„Ł„Ł…Ų²ŁŠŲÆ من Ų§Ł„ŲŖŁŲ§ŲµŁŠŁ„.",consentInfo4:"(تنطبق Ł…ŁˆŲ§ŁŁ‚ŲŖŁƒ على جلسة التصفح Ų§Ł„Ų­Ų§Ł„ŁŠŲ© فقط ŁˆŁŠŲŖŁ… مسحها عند ؄غلاق الصفحة أو النافذة)",consentAccept:"Ų£ŁˆŲ§ŁŁ‚",consentDecline:"رفض",consentAcceptAria:"Ų£ŁˆŲ§ŁŁ‚ - Ų§ŲØŲÆŲ£ المحادثة",consentDeclineAria:"رفض",interruptSpeaking:"Ų„ŁŠŁ‚Ų§Ł الأفاتار Ų§Ł„Ł…ŲŖŁƒŁ„Ł…",turnOnMic:"ŲŖŲ“ŲŗŁŠŁ„ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",turnOffMic:"Ų„ŁŠŁ‚Ų§Ł Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",tapToSpeak:"انقر للتحدث",startConversationReminder:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للتحدث.",chatPlaceholderTitle:"Ł…Ų³ŲŖŲ¹ŲÆ Ł„Ł„ŲÆŲ±ŲÆŲ“Ų©ŲŸ",chatPlaceholderDescription:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للمتابعة في وضع النص.",enterInfoOnMobile:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ في صفحة Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ المستخدم",waitCurrentResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد Ų§Ł„Ų­Ų§Ł„ŁŠ قبل Ų„Ų±Ų³Ų§Ł„ رسالة أخرى.",resumeConversationFailedNewStarted:"لم Ł†ŲŖŁ…ŁƒŁ† من استئناف Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة. ŲŖŁ… ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة بدلاً من Ų°Ł„Łƒ. ",end:"؄نهاؔ",endConversationPrompt:"هل ŲŖŲ±ŲŗŲØ في ؄نهاؔ Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ سيؤدي Ų°Ł„Łƒ ؄لى حذف المحادثة Ł†Ł‡Ų§Ų¦ŁŠŁ‹Ų§.",restartConversationPrompt:"هل أنت Ł…ŲŖŲ£ŁƒŲÆ من ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة؟ Ų³ŁŠŲŖŁ… حذف المحادثة Ų§Ł„Ų­Ų§Ł„ŁŠŲ©.",newConversation:"جديدة",conversationExpiredPrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© هذه المحادثة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل تريد ŲŖŁ†Ų²ŁŠŁ„ نسخة Ų«Ł… حذفها أو الحذف ŁŁ‚Ų·ŲŸ",conversationExpiredResumePrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل ŲŖŲ±ŲŗŲØ في ŲŖŁ†Ų²ŁŠŁ„ نسخة من سجل Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ",downloadAndClear:"ŲŖŁ†Ų²ŁŠŁ„ وحذف",downloadAndStartNew:"ŲŖŁ†Ų²ŁŠŁ„ وبدؔ جديدة",startNew:"ŲØŲÆŲ” جديدة",onlyClear:"حذف فقط",confirm:"تأكيد",ok:"Ł…ŁˆŲ§ŁŁ‚",download:"ŲŖŁ†Ų²ŁŠŁ„",alertGenericError:"Ų­ŲÆŲ« Ų®Ų·Ų£.",alertFailedEndConversation:"فؓل في ؄نهاؔ المحادثة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertFailedClearConversation:"فؓل في Ł…Ų³Ų­ المحادثة.",alertCouldNotStartListening:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertSomeErrorOccurred:"Ų­ŲÆŲ« Ų®Ų·Ų£ Ł…Ų§. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertWaitForAIResponse:"ŁŠŲ±Ų¬Ł‰ انتظار Ų±ŲÆ Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ قبل البدؔ في التحدث.",alertVoiceServicesUnavailable:"ŲŖŲ¹Ų°Ų± الاتصال ŲØŲ®ŲÆŁ…Ų§ŲŖ Ų§Ł„ŲµŁˆŲŖ. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© لاحقاً.",alertServiceTemporarilyUnavailable:"الخدمة غير Ł…ŲŖŲ§Ų­Ų© مؤقتاً. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertTooManyRequests:"طلبات متزامنة كثيرة Ų¬ŲÆŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ الانتظار لحظة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertConnectionIssue:"ŲŖŁ… اكتؓاف Ł…Ų“ŁƒŁ„Ų© في الاتصال. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§ŲŖŲµŲ§Ł„Łƒ بال؄نترنت ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertResponseTimeout:"انتهت مهلة الاستجابة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertServiceBusy:"Ų®ŲÆŁ…Ų© Ų§Ł„ŲµŁˆŲŖ Ł…Ų“ŲŗŁˆŁ„Ų© Ų­Ų§Ł„ŁŠŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© ŲØŲ¹ŲÆ ŲØŲ¶Ų¹ دقائق.",alertMicrophoneStartFailed:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. تأكد من أن Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† ŁŠŲ¹Ł…Ł„.",alertMicrophoneCheckSettings:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ التحقق من Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†.",alertSpeechRecognitionSetupFailed:"فؓل Ų„Ų¹ŲÆŲ§ŲÆ التعرف على Ų§Ł„ŁƒŁ„Ų§Ł…. ŁŠŲ±Ų¬Ł‰ تحديث الصفحة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertMicrophoneAccessDenied:"ŲŖŁ… رفض Ų§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ السماح ŲØŲ§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† في Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ المتصفح وتحديث الصفحة.",alertNoMicrophoneDetected:"لم ŁŠŲŖŁ… اكتؓاف Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ ŲŖŁˆŲµŁŠŁ„ Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† وتحديث الصفحة.",alertMicrophoneError:"Ų®Ų·Ų£ في Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†."},zh:{start:"å¼€å§‹åÆ¹čÆ",connect:"čæžęŽ„",endConversation:"ē»“ęŸåÆ¹čÆ",restartConversation:"é‡ę–°å¼€å§‹åÆ¹čÆ",hideTyping:"éšč—č¾“å…„ę”†",showTyping:"ę˜¾ē¤ŗč¾“å…„ę”†",reconnecting:"ę­£åœØé‡ę–°čæžęŽ„...",waitForResponse:"čÆ·ē­‰å¾…å›žå¤...",typeHere:"åœØę­¤č¾“å…„ć€‚",noMessagesYet:"ęš‚ę— ę¶ˆęÆ...",conversationStatus:"åÆ¹čÆēŠ¶ę€",conversationInProgress:"åÆ¹čÆčæ›č”Œäø­",conversationStopped:"åÆ¹čÆå·²åœę­¢",startConversation:"å¼€å§‹åÆ¹čÆ",downloadConversation:"äø‹č½½åÆ¹čÆ",liveCaptions:"å®žę—¶å­—å¹•",toggleChatbot:"显示/éšč—č™šę‹Ÿå½¢č±”åŠ©ę‰‹",avatar:"č™šę‹Ÿå½¢č±”",chat:"聊天",statusInitializing:"čÆ·ēØå€™ļ¼Œęˆ‘ä»¬ę­£åœØå”¤é†’åŠ©ę‰‹ļ¼",statusReconnecting:"čæžęŽ„å‡ŗēŽ°é—®é¢˜ļ¼Œę­£åœØå°čÆ•é‡ę–°čæžęŽ„...",statusFailed:"čæžęŽ„å¤±č“„ć€‚åÆčƒ½éœ€č¦ę‰‹åŠØå¤„ē†ć€‚",statusInvalidConfiguration:"č™šę‹Ÿå½¢č±”é…ē½®äøę­£ē”®ļ¼ŒčÆ·č”ē³»ē®”ē†å‘˜ć€‚",close:"关闭",lastAssistantMessage:"åŠ©ę‰‹ēš„äøŠäø€ę”ę¶ˆęÆ",fullBodyView:"全身视图",upperBodyView:"åŠčŗ«č§†å›¾",previousConversationFound:"ę‰¾åˆ°ä¹‹å‰ēš„åÆ¹čÆā€”ā€”čÆ·é€‰ę‹©äø€äøŖé€‰é”¹ē»§ē»­",secureFormTitle:"å®‰å…Øč”Øå•",secureFormDescription:"čÆ·č¾“å…„ę‚Øēš„äæ”ęÆć€‚",name:"姓名*",namePlaceholder:"čÆ·č¾“å…„å§“å",phoneNumber:"ē”µčÆå·ē ",phonePlaceholder:"čÆ·č¾“å…„ē”µčÆå·ē ",email:"电子邮件",emailPlaceholder:"请输兄电子邮件",secureFormNote:"ę‚Øēš„äæ”ęÆäøä¼šäøŽå¤§čÆ­čØ€ęØ”åž‹å…±äŗ«ļ¼Œä¼ščÆē»“ęŸåŽä¹Ÿäøä¼šč¢«å­˜å‚Øć€‚å‘é€å³č”Øē¤ŗę‚ØåŒę„å…±äŗ«ę‚Øēš„äæ”ęÆä»„čŽ·å¾—é¢å¤–ę”ÆęŒć€‚",save:"äæå­˜",send:"发送",cancel:"å–ę¶ˆ",conversationEndedPrompt:"åÆ¹čÆå·²ē»“ęŸć€‚čÆ·čÆ„ä»·ę‚Øēš„ę»”ę„åŗ¦ć€‚",submit:"ęäŗ¤",skip:"跳过",consentTitle:"åŒę„čæ›č”Œäŗŗå·„ę™ŗčƒ½åÆ¹čÆ",consentInfo1:"ä»…ä¾›äø€čˆ¬äæ”ęÆå‚č€ƒā€”ā€”äøęä¾›åŒ»ē–—ć€ę³•å¾‹ć€č“¢åŠ”ęˆ–å®‰å…Øå»ŗč®®ć€‚",consentInfo2:"ęˆ‘ä»¬ä½æē”Øä¼ščÆå­˜å‚Øå¹¶å‘é€ę‚Øēš„č¾“å…„ä»„ęä¾›å›žå¤ć€‚ęœ¬ę¬”ä¼ščÆē»“ęŸåŽęˆ‘ä»¬äøä¼šäæē•™ę‚Øēš„åÆ¹čÆęˆ–äøŖäŗŗäæ”ęÆć€‚",consentReadOur:"é˜…čÆ»ęˆ‘ä»¬ēš„",consentTermsLabel:"ę”ę¬¾",consentAnd:"和",consentPrivacyLabel:"éšē§ę”æē­–",consentMoreDetails:"äŗ†č§£ę›“å¤ščÆ¦ęƒ…ć€‚",consentInfo4:"ļ¼ˆę‚Øēš„åŒę„ä»…é€‚ē”ØäŗŽęœ¬ę¬”ä¼ščÆļ¼Œå…³é—­ę ‡ē­¾é”µęˆ–ēŖ—å£åŽå°†č¢«ęø…é™¤ļ¼‰",consentAccept:"åŒę„",consentDecline:"ę‹’ē»",consentAcceptAria:"åŒę„ā€”ā€”å¼€å§‹čŠå¤©",consentDeclineAria:"ę‹’ē»",interruptSpeaking:"ę‰“ę–­č™šę‹Ÿå½¢č±”č®²čÆ",turnOnMic:"å¼€åÆéŗ¦å…‹é£Ž",turnOffMic:"å…³é—­éŗ¦å…‹é£Ž",tapToSpeak:"ē‚¹å‡»čÆ“čÆ",startConversationReminder:"å¼€å§‹åÆ¹čÆä»„ä¾æčŠå¤©ć€‚",chatPlaceholderTitle:"å‡†å¤‡å„½čŠå¤©äŗ†å—ļ¼Ÿ",chatPlaceholderDescription:"å¼€å§‹åÆ¹čÆä»„ē»§ē»­ä½æē”Øę–‡å­—ęØ”å¼ć€‚",enterInfoOnMobile:"čÆ·åœØē”Øęˆ·äæ”ęÆé”µé¢č¾“å…„ę‚Øēš„äæ”ęÆ",waitCurrentResponse:"čÆ·ē­‰å¾…å½“å‰å›žå¤åŽå†å‘é€ę–°ę¶ˆęÆć€‚",resumeConversationFailedNewStarted:"ęˆ‘ä»¬ę— ę³•ę¢å¤ę‚Øä¹‹å‰ēš„åÆ¹čÆć€‚å·²åÆåŠØäø€äøŖę–°ēš„åÆ¹čÆć€‚",end:"ē»“ęŸ",endConversationPrompt:"ę˜Æå¦ē»“ęŸåÆ¹čÆļ¼Ÿē»“ęŸåŽå°†ę°øä¹…åˆ é™¤åŽ†å²č®°å½•ć€‚",restartConversationPrompt:"ē”®å®šč¦å¼€å§‹ę–°ēš„åÆ¹čÆå—ļ¼Ÿå½“å‰åÆ¹čÆå°†č¢«åˆ é™¤ć€‚",newConversation:"ꖰ",conversationExpiredPrompt:"ę­¤åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øč¦äø‹č½½å‰Æęœ¬å¹¶ęø…é™¤ļ¼Œčæ˜ę˜Æä»…ęø…é™¤ļ¼Ÿ",conversationExpiredResumePrompt:"ę‚Øä¹‹å‰ēš„åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øę˜Æå¦č¦äø‹č½½åÆ¹čÆč®°å½•ēš„å‰Æęœ¬ļ¼Ÿ",downloadAndClear:"下载并清除",downloadAndStartNew:"äø‹č½½å¹¶å¼€å§‹ę–°åÆ¹čÆ",startNew:"å¼€å§‹ę–°åÆ¹čÆ",onlyClear:"仅清除",confirm:"甮认",ok:"甮定",download:"äø‹č½½",alertGenericError:"å‘ē”Ÿé”™čÆÆć€‚",alertFailedEndConversation:"ę— ę³•ē»“ęŸåÆ¹čÆć€‚čÆ·é‡čÆ•ć€‚",alertFailedClearConversation:"ę— ę³•ęø…é™¤åÆ¹čÆć€‚",alertCouldNotStartListening:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·é‡čÆ•ć€‚",alertSomeErrorOccurred:"å‘ē”Ÿäŗ†é”™čÆÆć€‚čÆ·é‡čÆ•ć€‚",alertWaitForAIResponse:"请等待AIå›žå¤åŽå†å¼€å§‹čÆ“čÆć€‚",alertVoiceServicesUnavailable:"ę— ę³•čæžęŽ„åˆ°čÆ­éŸ³ęœåŠ”ć€‚čÆ·ēØåŽé‡čÆ•ć€‚",alertServiceTemporarilyUnavailable:"ęœåŠ”ęš‚ę—¶äøåÆē”Øć€‚čÆ·é‡čÆ•ć€‚",alertTooManyRequests:"åŒę—¶čÆ·ę±‚čæ‡å¤šć€‚čÆ·ēØē­‰ē‰‡åˆ»åŽé‡čÆ•ć€‚",alertConnectionIssue:"ę£€ęµ‹åˆ°čæžęŽ„é—®é¢˜ć€‚čÆ·ę£€ęŸ„ę‚Øēš„ē½‘ē»œčæžęŽ„åŽé‡čÆ•ć€‚",alertResponseTimeout:"å“åŗ”č¶…ę—¶ć€‚čÆ·é‡čÆ•ć€‚",alertServiceBusy:"čÆ­éŸ³ęœåŠ”å½“å‰ē¹åæ™ć€‚čÆ·å‡ åˆ†é’ŸåŽé‡čÆ•ć€‚",alertMicrophoneStartFailed:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ē”®äæę‚Øēš„éŗ¦å…‹é£Žę­£åøøå·„ä½œć€‚",alertMicrophoneCheckSettings:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žč®¾ē½®ć€‚",alertSpeechRecognitionSetupFailed:"čÆ­éŸ³čÆ†åˆ«č®¾ē½®å¤±č“„ć€‚čÆ·åˆ·ę–°é”µé¢åŽé‡čÆ•ć€‚",alertMicrophoneAccessDenied:"éŗ¦å…‹é£Žč®æé—®č¢«ę‹’ē»ć€‚čÆ·åœØęµč§ˆå™Øč®¾ē½®äø­å…č®øéŗ¦å…‹é£Žč®æé—®å¹¶åˆ·ę–°é”µé¢ć€‚",alertNoMicrophoneDetected:"ęœŖę£€ęµ‹åˆ°éŗ¦å…‹é£Žć€‚čÆ·čæžęŽ„éŗ¦å…‹é£Žå¹¶åˆ·ę–°é”µé¢ć€‚",alertMicrophoneError:"éŗ¦å…‹é£Žé”™čÆÆć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žć€‚"}};function Kt(t,e){const i=function(t){if(!t||"string"!=typeof t)return Xt;const e=t.toLowerCase();if(Zt[e])return e;const i=e.split("-")[0];return Zt[i]?i:Xt}(t),a=Zt[i]?.[e];return void 0!==a?a:Zt[Xt]?.[e]??e}class Jt{constructor(t,e,i){this.bus=t,this.dismissableContainer=e,this._getLanguage=i||(()=>"en"),this.dismissableAlerts=new Map,this.bus.on("event_command_Alerts_ShowDismissableAlert",(t=>{let e;e=t?.messageKey?Kt(this._getLanguage(),t.messageKey):t?.errorMessage||Kt(this._getLanguage(),"alertGenericError");const i=t?.className||"alert-danger";this.showDismissableAlert(e,i)}))}showDismissableAlert(t,e){if(this.dismissableAlerts.has(t))return;if(this.dismissableAlerts.size>=E.alerts.maxAlerts){const t=this.dismissableAlerts.keys().next().value,e=this.dismissableAlerts.get(t);e&&(e.hideToast(),this.dismissableAlerts.delete(t))}const i=C({text:t,duration:E.alerts.dismissableAlertDuration,close:!0,gravity:"top",position:"left",stopOnFocus:!0,className:`alert ${e}`,selector:this.dismissableContainer,callback:()=>{this.dismissableAlerts.delete(t)}});i.showToast(),this.dismissableAlerts.set(t,i)}}const te=t=>/[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(t);class ee{#o=null;#r="wakeLock"in navigator;get isActive(){return!!this.#o}get isSupported(){return this.#r}async request(){const t="undefined"!=typeof process&&process.env&&"test"===process.env.NODE_ENV,e="undefined"!=typeof document&&"visible"===document.visibilityState;if(this.#r&&!this.isActive&&!t&&e)try{this.#o=await navigator.wakeLock.request("screen"),this.#o.addEventListener("release",(()=>{this.#o=null}))}catch(i){}}async release(){try{await(this.#o?.release())}finally{this.#o=null,this.#r}}}const ie=k`
2
2
  <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
3
3
  width="25px" height="30.42px" viewBox="0 0 1052.000000 1280.000000"
4
4
  preserveAspectRatio="xMidYMid meet">
@@ -35,7 +35,7 @@ l-27 -54 -215 -119 c-332 -184 -779 -441 -1170 -671 -1067 -630 -1651 -1038
35
35
  38 -116 36 -205 22 -276 -44 -24 -22 -33 -24 -104 -20 -61 3 -82 8 -99 24 -46
36
36
  44 -132 65 -207 52z"/>
37
37
  </g>
38
- </svg>`,te=k`
38
+ </svg>`,ae=k`
39
39
  <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
40
40
  width="25px" height="50px" viewBox="0 0 640.000000 1280.000000"
41
41
  preserveAspectRatio="xMidYMid meet">
@@ -77,7 +77,7 @@ c94 101 142 246 150 447 4 107 9 144 25 178 19 40 20 50 9 155 -26 245 -121
77
77
  -58 374 -80 470 -16 70 -11 137 41 539 l29 220 6 -230 c4 -126 12 -275 19
78
78
  -330z"/>
79
79
  </g>
80
- </svg>`,ee=k`
80
+ </svg>`,ne=k`
81
81
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 304" aria-hidden="true" focusable="false">
82
82
  <path fill="currentColor" opacity="1.000000" stroke="none"
83
83
  d="
@@ -173,38 +173,66 @@ M138.709229,129.454376
173
173
  C109.740639,131.054550 114.375092,127.080360 120.324982,124.957504
174
174
  C127.137169,122.526985 133.365952,123.659859 138.709229,129.454376
175
175
  z"/>
176
- </svg>`,ie=k`<span class="material-icons">mic_off</span>`,ae=k`<span class="material-icons">mic</span>`,ne=k`<span class="material-icons">delete</span>`,se=k`<span class="material-icons">graphic_eq</span>`,oe=k`<span class="material-icons last-message-icon">chat_bubble</span>`,re=k`<span class="material-icons">refresh</span>`,ce=k`<span class="material-icons">send</span>`,he=k`<span class="material-icons chat-bubble-icon">chat_bubble</span>`,le=k`<span class="material-icons">close</span>`,de=k`<span class="material-icons">menu</span>`,ue=k`<span class="material-icons error-icon">error</span>`,pe=k`<span class="material-icons"> content_copy</span>`,me=k`<span class="material-icons">check</span>`,ge=t=>k`
176
+ </svg>`,se=k`
177
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="80" height="80" aria-hidden="true" focusable="false">
178
+ <!-- Main chat bubble -->
179
+ <rect x="10" y="15" width="55" height="40" rx="8" ry="8" fill="currentColor" opacity="0.15"/>
180
+ <!-- Secondary chat bubble -->
181
+ <rect x="35" y="40" width="55" height="40" rx="8" ry="8" fill="currentColor" opacity="0.3"/>
182
+ <!-- Dots in main bubble -->
183
+ <circle cx="25" cy="35" r="4" fill="currentColor" opacity="0.4"/>
184
+ <circle cx="38" cy="35" r="4" fill="currentColor" opacity="0.4"/>
185
+ <circle cx="51" cy="35" r="4" fill="currentColor" opacity="0.4"/>
186
+ </svg>`,oe=ne,re=k`<span class="material-icons">delete</span>`,ce=k`<span class="material-icons last-message-icon">chat_bubble</span>`,he=k`<span class="material-icons">refresh</span>`,le=k`<span class="material-icons">send</span>`,de=k`<span class="material-icons chat-bubble-icon">chat_bubble</span>`,ue=k`<span class="material-icons">close</span>`,pe=k`<span class="material-icons">menu</span>`,me=k`<span class="material-icons error-icon">error</span>`,ge=k`<span class="material-icons"> content_copy</span>`,ye=k`<span class="material-icons">check</span>`,ve=t=>k`
177
187
  <div class="button-container">
178
188
  <button @click="${t._handleStartConversationBtn}" type="button" class="btn start-button" id="start_conversation_button" title="${t._t("start")}">${t._t("start")}</button>
179
189
  </div>
180
- `,ye=t=>k`
190
+ `,fe=t=>k`
181
191
  <div class="button-container">
182
192
  <button @click="${t._handleConnectBtn}" type="button" class="btn-lg start-button" id="connect_button" title="${t._t("connect")}">${t._t("connect")}</button>
183
- </div>`,ve=t=>{const e=t._isConversationInProgress;return k`
193
+ </div>`,be=t=>{const e=(t=>t._isConversationPaused?"paused":t._isSpeaking?"speaking":t._isThinking?"thinking":t._isListening?"listening":"idle")(t),i=((t,e)=>{switch(e){case"paused":return t._t("reconnecting");case"speaking":return t._t("interruptSpeaking");case"thinking":return t._t("waitForResponse");case"listening":return t._t("turnOffMic");default:return t._t("turnOnMic")}})(t,e),a=t._inputsBlocked&&"idle"===e,n="paused"===e,s="idle"===e&&!a;return k`
194
+ <div class="voice-visualizer-wrapper">
195
+ <div
196
+ class="voice-visualizer state-${e} ${a||n?"visualizer-disabled":""}"
197
+ @click="${a||n?S:t._handleMicBtn}"
198
+ title="${i}"
199
+ role="button"
200
+ tabindex="${a||n?-1:0}"
201
+ aria-label="${i}"
202
+ >
203
+ <div class="audio-bar"></div>
204
+ <div class="audio-bar"></div>
205
+ <div class="audio-bar"></div>
206
+ <div class="audio-bar"></div>
207
+ <div class="audio-bar"></div>
208
+ </div>
209
+ ${s?k`<span class="visualizer-hint">${t._t("tapToSpeak")}</span>`:S}
210
+ </div>
211
+ `},_e=t=>{const e=t._isConversationInProgress;return k`
184
212
  <div class="page-wrapper avatar-wrapper" id="avatar-page" ?hidden=${"AvatarPage"!==t._shownPage}>
185
213
  <div class="avatarbox">
186
214
  <div id="avatar-container" style=${R(t._getAvatarBackgroundStyleObj())}></div>
187
215
  ${(t=>k`
188
216
  ${t._isLiveCaptionsVisible&&t._liveCaption&&""!==t._liveCaption.trim()?k`
189
217
  <div id="captions-wrapper" class="center-aligned">
190
- <div class="${"assistant"===t._liveCaptionSpeaker?"assistant-live-caption":"user-live-caption"}" style="direction: ${Zt(t._liveCaption)?"rtl":"ltr"}" @click="${t._openLastMessage}">
218
+ <div class="${"assistant"===t._liveCaptionSpeaker?"assistant-live-caption":"user-live-caption"}" style="direction: ${te(t._liveCaption)?"rtl":"ltr"}" @click="${t._openLastMessage}">
191
219
  <div class="caption-content ${t._liveCaption.split(" ").length>5?"long-text":t._liveCaption.length<10?"short-text":""}">
192
220
  <span class="${"assistant"===t._liveCaptionSpeaker?"caption-highlight":""}">${t._liveCaption}</span>
193
221
  </div>
194
222
  </div>
195
223
  </div>
196
- `:w}
224
+ `:S}
197
225
  `)(t)}
198
226
  ${e?(t=>k`
199
227
  <div class="conversation-buttons-overlay">
200
228
  ${(t=>k`
201
229
  <button @click="${t._handleEndConversationBtn}" type="button" title="${t._t("endConversation")}" class="secondary-button stop-button">
202
- ${ne}
230
+ ${re}
203
231
  </button>
204
232
  `)(t)}
205
233
  ${(t=>k`
206
234
  <button @click="${t._handleRestartConversation}" type="button" class="secondary-button restart-button" id="restart_button" title="${t._t("restartConversation")}">
207
- ${re}
235
+ ${he}
208
236
  </button>
209
237
  `)(t)}
210
238
  ${(t=>k`
@@ -218,41 +246,36 @@ z"/>
218
246
  ${(t=>{const e=t._currentMessage,i=e&&"string"==typeof e.messageText&&""!==e.messageText.trim();return k`
219
247
  ${i?k`
220
248
  <div @click="${t._openLastMessage}" class="last-message-button" title="${t._t("lastAssistantMessage")}">
221
- ${oe}
249
+ ${ce}
222
250
  </div>
223
- `:w}
251
+ `:S}
224
252
  `})(t)}
225
253
  </div>
226
- `)(t):w}
254
+ `)(t):S}
227
255
  <div class="body-icons-overlay">
228
256
  ${t._isFullBody?(t=>k`
229
257
  <div id="body-icons-wrapper" class="button-container vertical-icons">
230
258
  <div class="icon-button" @click="${t._handleFullBodyIcon}" title="${t._t("fullBodyView")}">
231
- ${te}
259
+ ${ae}
232
260
  </div>
233
261
  <div class="icon-button" @click="${t._handleUpperBodyIcon}" title="${t._t("upperBodyView")}">
234
- ${Kt}
262
+ ${ie}
235
263
  </div>
236
264
  </div>
237
- `)(t):w}
265
+ `)(t):S}
238
266
  </div>
239
267
  </div>
240
268
  <div class="voice-controls-container">
241
269
  ${(t=>{if(t._isConversationPaused)return k`
242
270
  <div class="button-container">
243
271
  <div class="state-control">
244
- <button type="button" class="button-primary voice-button voice-button-disabled" title="${t._t("reconnecting")}" disabled>
245
- ${ie}
246
- </button>
272
+ ${be(t)}
247
273
  </div>
248
274
  </div>
249
275
  `;if(t._isConversationInProgress)return k`
250
276
  <div class="button-container">
251
277
  <div class="state-control">
252
- ${t._isSpeaking?k`<button @click="${t._handleMicBtn}" type="button" class="button-primary voice-button voice-active" id="mute_button" title="${t._t("interruptSpeaking")}">${se}</button>`:w}
253
- ${t._isThinking?k`<div class="lds-dual-ring small"></div>`:w}
254
- ${t._isSpeaking||t._isThinking||t._isListening?w:k`<button id="voice_button" @click="${t._handleMicBtn}" type="button" class="button-primary voice-button" title="${t._t("turnOnMic")}" ?disabled="${t._inputsBlocked}">${ie}</button>`}
255
- ${t._isListening?k`<button id="voice_button" @click="${t._handleMicBtn}" type="button" class="button-primary voice-button voice-active" title="${t._t("turnOffMic")}">${ae}</button>`:w}
278
+ ${be(t)}
256
279
  </div>
257
280
  </div>
258
281
  ${t._showTyping?(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return k`
@@ -269,14 +292,14 @@ z"/>
269
292
  id="typing_send_button"
270
293
  class="${t._inputsBlocked?"send-button-disabled":""}"
271
294
  >
272
- ${ce}
295
+ ${le}
273
296
  </div>
274
297
  </div>
275
- `})(t):w}
276
- `;const e=t._speakingAvatar?.connectionManager;return e?.connectionModules&&Object.values(e.connectionModules).some((t=>t.isFailed()))?ye(t):ge(t)})(t)}
298
+ `})(t):S}
299
+ `;const e=t._speakingAvatar?.connectionManager;return e?.connectionModules&&Object.values(e.connectionModules).some((t=>t.isFailed()))?fe(t):ve(t)})(t)}
277
300
  </div>
278
301
  </div>
279
- `},fe=S`
302
+ `},xe=w`
280
303
 
281
304
  :host {
282
305
  --z-chatbot: 100; /* the widget panel */
@@ -419,7 +442,7 @@ z"/>
419
442
  margin: 20px;
420
443
  }
421
444
 
422
- `,be=S`
445
+ `,ke=w`
423
446
  #chatbot-container {
424
447
  height: 100%;
425
448
  width: 100%;
@@ -520,7 +543,7 @@ z"/>
520
543
  cursor: text;
521
544
  caret-color: auto; /* allow caret in real text fields */
522
545
  }
523
- .chatbot :where(button, a, [role="button"], .clickable, .voice-button, .restart-button, .stop-button, .last-message-button, .input-toggle-button, .close-icon, .menu-icon, #chat_send_button, #typing_send_button) {
546
+ .chatbot :where(button, a, [role="button"], .clickable, .voice-visualizer, .restart-button, .stop-button, .last-message-button, .input-toggle-button, .close-icon, .menu-icon, #chat_send_button, #typing_send_button) {
524
547
  cursor: pointer;
525
548
  }
526
549
 
@@ -661,7 +684,7 @@ z"/>
661
684
 
662
685
  }
663
686
 
664
- `,_e=S`
687
+ `,Se=w`
665
688
  .chatbot header {
666
689
  padding: 16px 0;
667
690
  text-align: center;
@@ -998,7 +1021,7 @@ z"/>
998
1021
  .captions-slider.round:before {
999
1022
  border-radius: 50%;
1000
1023
  }
1001
- `,xe=S`
1024
+ `,we=w`
1002
1025
 
1003
1026
  .avatar-wrapper {
1004
1027
  position: relative;
@@ -1263,61 +1286,6 @@ z"/>
1263
1286
  margin-top: 0.5rem;
1264
1287
  }
1265
1288
 
1266
-
1267
- .voice-button {
1268
- z-index: var(--z-controls);
1269
- cursor: pointer;
1270
- outline: none;
1271
- user-select: none;
1272
- position: relative;
1273
- background-color: var(--mic-color, #2222);
1274
- box-shadow: 0 2px 5px rgba(1, 1, 1, 1);
1275
- transition: background-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
1276
- }
1277
-
1278
- .voice-button::after {
1279
- content: '';
1280
- width: 100%;
1281
- height: 100%;
1282
- border-radius: 50%;
1283
- background-color: var(--mic-color, #2222);
1284
- position: absolute;
1285
- top: 0;
1286
- left: 0;
1287
- z-index: -1;
1288
- }
1289
-
1290
- .voice-active {
1291
- background-color: green;
1292
- }
1293
-
1294
- .voice-active::before {
1295
- content: '';
1296
- width: 110%;
1297
- height: 110%;
1298
- border: 5px solid green;
1299
- border-radius: 50%;
1300
- position: absolute;
1301
- top: 50%;
1302
- left: 50%;
1303
- transform: translate(-50%, -50%);
1304
- z-index: -2;
1305
- animation: pulsate infinite 1.5s;
1306
- opacity: 0.5;
1307
- }
1308
-
1309
- @keyframes pulsate {
1310
- 0% {
1311
- transform: translate(-50%, -50%) scale(1);
1312
- opacity: 0.5;
1313
- }
1314
-
1315
- 100% {
1316
- transform: translate(-50%, -50%) scale(1.3);
1317
- opacity: 0;
1318
- }
1319
- }
1320
-
1321
1289
  .time-right,
1322
1290
  .time-left {
1323
1291
  position: absolute;
@@ -1552,11 +1520,121 @@ z"/>
1552
1520
  cursor: not-allowed !important;
1553
1521
  }
1554
1522
 
1555
- /* Disabled voice button styles */
1556
- .voice-button-disabled {
1557
- opacity: 0.5 !important;
1558
- cursor: not-allowed !important;
1559
- pointer-events: none !important;
1523
+ /* ========================================
1524
+ * VOICE VISUALIZER - Animated audio bars
1525
+ * ======================================== */
1526
+ .voice-visualizer {
1527
+ display: flex;
1528
+ justify-content: center;
1529
+ align-items: center;
1530
+ width: 80px;
1531
+ height: 50px;
1532
+ background: rgba(0, 0, 0, 0.15);
1533
+ border-radius: 25px;
1534
+ padding: 8px;
1535
+ cursor: pointer;
1536
+ transition: background-color 0.3s ease;
1537
+ }
1538
+
1539
+ .voice-visualizer:hover {
1540
+ background: rgba(0, 0, 0, 0.25);
1541
+ }
1542
+
1543
+ .voice-visualizer-wrapper {
1544
+ display: flex;
1545
+ flex-direction: column;
1546
+ align-items: center;
1547
+ gap: 6px;
1548
+ }
1549
+
1550
+ .voice-visualizer.visualizer-disabled {
1551
+ opacity: 0.5;
1552
+ cursor: not-allowed;
1553
+ pointer-events: none;
1554
+ }
1555
+
1556
+ .visualizer-hint {
1557
+ font-size: 0.7rem;
1558
+ color: var(--text-color-muted, #888);
1559
+ opacity: 0.8;
1560
+ text-align: center;
1561
+ animation: fadeInHint 0.5s ease-in-out;
1562
+ }
1563
+
1564
+ @keyframes fadeInHint {
1565
+ from { opacity: 0; transform: translateY(-5px); }
1566
+ to { opacity: 0.8; transform: translateY(0); }
1567
+ }
1568
+
1569
+ .audio-bar {
1570
+ width: 6px;
1571
+ margin: 0 3px;
1572
+ background: linear-gradient(180deg, var(--primary-color, #00bfdb), var(--secondary-color, #801bea));
1573
+ border-radius: 99px;
1574
+ transform-origin: center;
1575
+ height: 10px;
1576
+ transition: all 0.3s ease;
1577
+ }
1578
+
1579
+ /* --- STATE: IDLE --- */
1580
+ .state-idle .audio-bar {
1581
+ height: 8px;
1582
+ opacity: 0.5;
1583
+ animation: none;
1584
+ }
1585
+
1586
+ /* --- STATE: LISTENING (Microphone active) --- */
1587
+ @keyframes listen-wave {
1588
+ 0%, 100% { transform: scaleY(1); opacity: 0.8; }
1589
+ 50% { transform: scaleY(1.8); opacity: 1; }
1590
+ }
1591
+ .state-listening .audio-bar {
1592
+ animation: listen-wave 1.5s infinite ease-in-out;
1593
+ }
1594
+ .state-listening .audio-bar:nth-child(1) { animation-delay: 0.0s; }
1595
+ .state-listening .audio-bar:nth-child(2) { animation-delay: 0.2s; }
1596
+ .state-listening .audio-bar:nth-child(3) { animation-delay: 0.4s; }
1597
+ .state-listening .audio-bar:nth-child(4) { animation-delay: 0.2s; }
1598
+ .state-listening .audio-bar:nth-child(5) { animation-delay: 0.0s; }
1599
+
1600
+ /* --- STATE: THINKING (Processing) --- */
1601
+ @keyframes think-wave {
1602
+ 0% { height: 8px; opacity: 0.5; }
1603
+ 50% { height: 28px; opacity: 1; }
1604
+ 100% { height: 8px; opacity: 0.5; }
1605
+ }
1606
+ .state-thinking .audio-bar {
1607
+ animation: think-wave 1s infinite;
1608
+ }
1609
+ .state-thinking .audio-bar:nth-child(1) { animation-delay: 0.0s; }
1610
+ .state-thinking .audio-bar:nth-child(2) { animation-delay: 0.1s; }
1611
+ .state-thinking .audio-bar:nth-child(3) { animation-delay: 0.2s; }
1612
+ .state-thinking .audio-bar:nth-child(4) { animation-delay: 0.3s; }
1613
+ .state-thinking .audio-bar:nth-child(5) { animation-delay: 0.4s; }
1614
+
1615
+ /* --- STATE: SPEAKING (Voice Output) --- */
1616
+ @keyframes speak-wave {
1617
+ 0% { height: 15%; }
1618
+ 20% { height: 60%; }
1619
+ 40% { height: 35%; }
1620
+ 50% { height: 100%; }
1621
+ 100% { height: 15%; }
1622
+ }
1623
+ .state-speaking .audio-bar {
1624
+ height: 30px;
1625
+ animation: speak-wave 0.8s infinite ease-in-out;
1626
+ }
1627
+ .state-speaking .audio-bar:nth-child(1) { animation-duration: 0.7s; }
1628
+ .state-speaking .audio-bar:nth-child(2) { animation-duration: 0.9s; }
1629
+ .state-speaking .audio-bar:nth-child(3) { animation-duration: 0.6s; }
1630
+ .state-speaking .audio-bar:nth-child(4) { animation-duration: 0.8s; }
1631
+ .state-speaking .audio-bar:nth-child(5) { animation-duration: 1.0s; }
1632
+
1633
+ /* --- STATE: PAUSED (Disconnected) --- */
1634
+ .state-paused .audio-bar {
1635
+ height: 8px;
1636
+ opacity: 0.3;
1637
+ animation: none;
1560
1638
  }
1561
1639
 
1562
1640
  @media (max-width: 768px) {
@@ -1590,7 +1668,7 @@ z"/>
1590
1668
  }
1591
1669
  }
1592
1670
 
1593
- `,ke=S`
1671
+ `,Ae=w`
1594
1672
 
1595
1673
  #chat-page {
1596
1674
  height: 100%;
@@ -1856,7 +1934,91 @@ z"/>
1856
1934
  max-width: 85%;
1857
1935
  }
1858
1936
  }
1859
- `,we=S`
1937
+
1938
+ /* Chat Placeholder Styles */
1939
+ .chat-placeholder-container {
1940
+ display: flex;
1941
+ flex-direction: column;
1942
+ justify-content: space-between;
1943
+ align-items: center;
1944
+ height: 100%;
1945
+ padding: 40px 20px 20px;
1946
+ box-sizing: border-box;
1947
+ }
1948
+
1949
+ .chat-placeholder-content {
1950
+ display: flex;
1951
+ flex-direction: column;
1952
+ align-items: center;
1953
+ justify-content: center;
1954
+ flex-grow: 1;
1955
+ text-align: center;
1956
+ max-width: 300px;
1957
+ }
1958
+
1959
+ .chat-placeholder-icon {
1960
+ color: var(--primary-color, #00bfdb);
1961
+ margin-bottom: 24px;
1962
+ opacity: 0.9;
1963
+ }
1964
+
1965
+ .chat-placeholder-icon svg {
1966
+ width: 80px;
1967
+ height: 80px;
1968
+ }
1969
+
1970
+ .chat-placeholder-title {
1971
+ font-size: 1.4rem;
1972
+ font-weight: 600;
1973
+ color: var(--secondary-color, #333);
1974
+ margin: 0 0 12px 0;
1975
+ letter-spacing: -0.02em;
1976
+ }
1977
+
1978
+ .chat-placeholder-description {
1979
+ font-size: 0.95rem;
1980
+ color: #666;
1981
+ margin: 0;
1982
+ line-height: 1.5;
1983
+ opacity: 0.85;
1984
+ }
1985
+
1986
+ .chat-placeholder-button {
1987
+ width: 100%;
1988
+ padding-top: 20px;
1989
+ }
1990
+
1991
+ .chat-placeholder-button .button-container {
1992
+ width: 100%;
1993
+ }
1994
+
1995
+ .chat-placeholder-button .start-button {
1996
+ width: 100%;
1997
+ }
1998
+
1999
+ .chat-wrapper.placeholder-mode {
2000
+ height: 100%;
2001
+ }
2002
+
2003
+ @media (max-width: 500px) {
2004
+ .chat-placeholder-container {
2005
+ padding: 30px 15px 15px;
2006
+ }
2007
+
2008
+ .chat-placeholder-icon svg {
2009
+ width: 60px;
2010
+ height: 60px;
2011
+ }
2012
+
2013
+ .chat-placeholder-title {
2014
+ font-size: 1.2rem;
2015
+ }
2016
+
2017
+ .chat-placeholder-description {
2018
+ font-size: 0.9rem;
2019
+ }
2020
+ }
2021
+ `,Ce=w`
1860
2022
  .chatbot footer {
1861
2023
  text-align: center;
1862
2024
  padding: 5px;
@@ -1881,7 +2043,7 @@ z"/>
1881
2043
  display: none;
1882
2044
  }
1883
2045
  }
1884
- `,Se=S`
2046
+ `,Re=w`
1885
2047
  .form-group {
1886
2048
  display: flex;
1887
2049
  flex-direction: column;
@@ -2099,18 +2261,18 @@ z"/>
2099
2261
  margin-top: 0;
2100
2262
  padding-top: 0.25rem;
2101
2263
  }
2102
- `,Ae="en",Ce={en:{start:"Start Conversation",connect:"Connect",endConversation:"End Conversation",restartConversation:"Restart Conversation",hideTyping:"Hide typing input",showTyping:"Show typing input",reconnecting:"Reconnecting...",waitForResponse:"Please wait for response...",typeHere:"Type here.",noMessagesYet:"No messages yet...",conversationStatus:"Conversation Status",conversationInProgress:"Conversation In Progress",conversationStopped:"Conversation Stopped",startConversation:"Start Conversation",downloadConversation:"Download Conversation",liveCaptions:"Live captions",toggleChatbot:"Toggle avatar chatbot",avatar:"Avatar",chat:"Chat",statusInitializing:"Hang tight, we're waking up the assistant!",statusReconnecting:"Connection issue, attempting to reconnect...",statusFailed:"Connection failed. Manual action may be required.",statusInvalidConfiguration:"The avatar is not configured correctly, contact the admin.",close:"Close",lastAssistantMessage:"Last assistant message",fullBodyView:"Full body view",upperBodyView:"Upper body view",previousConversationFound:"Previous conversation found - please choose an option to proceed",secureFormTitle:"Secure Form",secureFormDescription:"Enter your information.",name:"Name*",namePlaceholder:"Enter your name",phoneNumber:"Phone Number",phonePlaceholder:"Enter your phone number",email:"Email",emailPlaceholder:"Enter your email",secureFormNote:"Note: Your information will not be shared with the LLM and will not be stored.",save:"Save",cancel:"Cancel",conversationEndedPrompt:"Conversation ended. Please rate your satisfaction with the conversation.",submit:"Submit",skip:"Skip",consentTitle:"Consent for AI conversation",consentInfo1:"For general information only — no medical, legal, financial, or safety advice.",consentInfo2:"We use session storage and send your input to provide replies. We don’t keep your conversation or personal info after this session.",consentReadOur:"Read our",consentTermsLabel:"Terms",consentAnd:"and",consentPrivacyLabel:"Privacy Policy",consentMoreDetails:"for more details.",consentInfo4:"(Your consent applies to this session only and clears when you close the tab/window)",consentAccept:"I agree",consentDecline:"Decline",consentAcceptAria:"I agree – start chat",consentDeclineAria:"Decline",interruptSpeaking:"Interrupt speaking avatar",turnOnMic:"Turn on microphone",turnOffMic:"Turn off microphone",startConversationReminder:"Start a conversation to chat.",enterInfoOnMobile:"Enter your information in User Information page",waitCurrentResponse:"Please wait for the current response before sending another message.",resumeConversationPrompt:"Previous conversation found. Would you like to resume where you left off or end the conversation?",resume:"Resume",end:"End",endConversationPrompt:"Would you like to end the conversation? Ending it will permanently delete the conversation history.",restartConversationPrompt:"Are you sure you want to start a new conversation? Current conversation will be deleted.",newConversation:"New",conversationExpiredPrompt:"This conversation has expired and cannot be resumed. Would you like to download a copy and end or end only?",downloadAndClear:"Download & Clear",onlyClear:"Only Clear",confirm:"Confirm"},fr:{start:"DĆ©marrer la conversation",connect:"Se connecter",endConversation:"Terminer la conversation",restartConversation:"RedĆ©marrer la conversation",hideTyping:"Masquer la saisie",showTyping:"Afficher la saisie",reconnecting:"Reconnexion...",waitForResponse:"Veuillez attendre la rĆ©ponse...",typeHere:"Tapez ici.",noMessagesYet:"Pas encore de messages...",conversationStatus:"Ɖtat de la conversation",conversationInProgress:"Conversation en cours",conversationStopped:"Conversation terminĆ©e",startConversation:"Commencer la conversation",downloadConversation:"TĆ©lĆ©charger la conversation",liveCaptions:"Sous-titres en direct",toggleChatbot:"Afficher/Masquer l'avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Patientez, nous rĆ©veillons l'assistant !",statusReconnecting:"ProblĆØme de connexion, tentative de reconnexion...",statusFailed:"Ɖchec de la connexion. Une action manuelle peut ĆŖtre nĆ©cessaire.",statusInvalidConfiguration:"L'avatar n'est pas configurĆ© correctement, contactez l'administrateur.",close:"Fermer",lastAssistantMessage:"Dernier message de l'assistant",fullBodyView:"Vue du corps entier",upperBodyView:"Vue du haut du corps",previousConversationFound:"Conversation prĆ©cĆ©dente trouvĆ©e - veuillez choisir une option pour continuer.",secureFormTitle:"Formulaire sĆ©curisĆ©",secureFormDescription:"Saisissez vos informations.",name:"Nom*",namePlaceholder:"Entrez votre nom",phoneNumber:"NumĆ©ro de tĆ©lĆ©phone",phonePlaceholder:"Entrez votre numĆ©ro de tĆ©lĆ©phone",email:"E-mail",emailPlaceholder:"Entrez votre e-mail",secureFormNote:"Remarque : Vos informations ne seront pas partagĆ©es avec le LLM et ne seront pas conservĆ©es.",save:"Enregistrer",cancel:"Annuler",conversationEndedPrompt:"Conversation terminĆ©e. Veuillez Ć©valuer votre satisfaction.",submit:"Envoyer",skip:"Ignorer",consentTitle:"Consentement pour la conversation IA",consentInfo1:"ƀ titre informatif uniquement — aucun conseil mĆ©dical, juridique, financier ou de sĆ©curitĆ©.",consentInfo2:"Nous utilisons le stockage de session et envoyons votre saisie pour fournir des rĆ©ponses. Nous ne conservons pas votre conversation ni vos informations personnelles aprĆØs cette session.",consentReadOur:"Lisez nos",consentTermsLabel:"Conditions",consentAnd:"et",consentPrivacyLabel:"Politique de confidentialitĆ©",consentMoreDetails:"pour plus de dĆ©tails.",consentInfo4:"(Votre consentement s'applique uniquement Ć  cette session et est rĆ©initialisĆ© lorsque vous fermez l'onglet ou la fenĆŖtre)",consentAccept:"J'accepte",consentDecline:"Refuser",consentAcceptAria:"J'accepte – dĆ©marrer le chat",consentDeclineAria:"Refuser",interruptSpeaking:"Interrompre l'avatar",turnOnMic:"Activer le microphone",turnOffMic:"DĆ©sactiver le microphone",startConversationReminder:"DĆ©marrez une conversation pour discuter.",enterInfoOnMobile:"Saisissez vos informations dans la page Informations utilisateur",waitCurrentResponse:"Veuillez attendre la rĆ©ponse en cours avant d'envoyer un autre message.",resumeConversationPrompt:"Conversation prĆ©cĆ©dente trouvĆ©e. Souhaitez-vous reprendre où vous vous ĆŖtes arrĆŖtĆ© ou terminer la conversation ?",resume:"Reprendre",end:"Terminer",endConversationPrompt:"Souhaitez-vous terminer la conversation ? Cela supprimera dĆ©finitivement l'historique de la conversation.",restartConversationPrompt:"Voulez-vous dĆ©marrer une nouvelle conversation ? La conversation actuelle sera supprimĆ©e.",newConversation:"Nouveau",conversationExpiredPrompt:"Cette conversation a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous en tĆ©lĆ©charger une copie puis la supprimer, ou simplement la supprimer ?",downloadAndClear:"TĆ©lĆ©charger et effacer",onlyClear:"Effacer uniquement",confirm:"Confirmer"},de:{start:"Starten Sie die Konversation",connect:"Verbinden",endConversation:"GesprƤch beenden",restartConversation:"GesprƤch neu starten",hideTyping:"Eingabefeld ausblenden",showTyping:"Eingabefeld anzeigen",reconnecting:"Verbindung wird wiederhergestellt...",waitForResponse:"Bitte auf die Antwort warten...",typeHere:"Hier eingeben.",noMessagesYet:"Noch keine Nachrichten...",conversationStatus:"GesprƤchsstatus",conversationInProgress:"GesprƤch lƤuft",conversationStopped:"GesprƤch beendet",startConversation:"GesprƤch starten",downloadConversation:"GesprƤch herunterladen",liveCaptions:"Live-Untertitel",toggleChatbot:"Avatar-Chatbot ein-/ausblenden",avatar:"Avatar",chat:"Chat",statusInitializing:"Einen Moment, der Assistent wird gestartet!",statusReconnecting:"Verbindungsproblem, versuche erneut zu verbinden...",statusFailed:"Verbindung fehlgeschlagen. Mƶglicherweise ist ein manueller Eingriff erforderlich.",statusInvalidConfiguration:"Der Avatar ist nicht korrekt konfiguriert, wenden Sie sich an den Administrator.",close:"Schließen",lastAssistantMessage:"Letzte Nachricht des Assistenten",fullBodyView:"Ganzkƶrperansicht",upperBodyView:"Oberkƶrperansicht",previousConversationFound:"Früheres GesprƤch gefunden – bitte wƤhlen Sie eine Option, um fortzufahren",secureFormTitle:"Sicheres Formular",secureFormDescription:"Geben Sie Ihre Informationen ein.",name:"Name*",namePlaceholder:"Geben Sie Ihren Namen ein",phoneNumber:"Telefonnummer",phonePlaceholder:"Geben Sie Ihre Telefonnummer ein",email:"E-Mail",emailPlaceholder:"Geben Sie Ihre E-Mail ein",secureFormNote:"Hinweis: Ihre Informationen werden nicht mit dem LLM geteilt und nicht gespeichert.",save:"Speichern",cancel:"Abbrechen",conversationEndedPrompt:"GesprƤch beendet. Bitte bewerten Sie Ihre Zufriedenheit.",submit:"Senden",skip:"Überspringen",consentTitle:"Einwilligung für das KI-GesprƤch",consentInfo1:"Nur zu allgemeinen Informationszwecken – keine medizinischen, rechtlichen, finanziellen oder sicherheitsrelevanten RatschlƤge.",consentInfo2:"Wir verwenden den Sitzungspeicher und senden Ihre Eingaben, um Antworten bereitzustellen. Wir speichern Ihr GesprƤch oder persƶnliche Daten nach dieser Sitzung nicht.",consentReadOur:"Lesen Sie unsere",consentTermsLabel:"Nutzungsbedingungen",consentAnd:"und",consentPrivacyLabel:"DatenschutzerklƤrung",consentMoreDetails:"für weitere Informationen.",consentInfo4:"(Ihre Einwilligung gilt nur für diese Sitzung und wird zurückgesetzt, wenn Sie den Tab oder das Fenster schließen)",consentAccept:"Ich stimme zu",consentDecline:"Ablehnen",consentAcceptAria:"Ich stimme zu – Chat starten",consentDeclineAria:"Ablehnen",interruptSpeaking:"Sprechenden Avatar unterbrechen",turnOnMic:"Mikrofon einschalten",turnOffMic:"Mikrofon ausschalten",startConversationReminder:"Starten Sie ein GesprƤch, um zu chatten.",enterInfoOnMobile:"Geben Sie Ihre Daten auf der Seite Benutzerinformationen ein",waitCurrentResponse:"Bitte warten Sie die aktuelle Antwort ab, bevor Sie eine weitere Nachricht senden.",resumeConversationPrompt:"Früheres GesprƤch gefunden. Mƶchten Sie dort weitermachen, wo Sie aufgehƶrt haben, oder das GesprƤch beenden?",resume:"Fortsetzen",end:"Beenden",endConversationPrompt:"Mƶchten Sie das GesprƤch beenden? Dadurch wird der GesprƤchsverlauf dauerhaft gelƶscht.",restartConversationPrompt:"Mƶchten Sie ein neues GesprƤch beginnen? Das aktuelle GesprƤch wird gelƶscht.",newConversation:"Neu",conversationExpiredPrompt:"Dieses GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie herunterladen und lƶschen oder nur lƶschen?",downloadAndClear:"Herunterladen & lƶschen",onlyClear:"Nur lƶschen",confirm:"BestƤtigen"},es:{start:"Iniciar conversación",connect:"Conectar",endConversation:"Terminar conversación",restartConversation:"Reiniciar conversación",hideTyping:"Ocultar entrada de texto",showTyping:"Mostrar entrada de texto",reconnecting:"Reconectando...",waitForResponse:"Espere la respuesta...",typeHere:"Escriba aquĆ­.",noMessagesYet:"TodavĆ­a no hay mensajes...",conversationStatus:"Estado de la conversación",conversationInProgress:"Conversación en curso",conversationStopped:"Conversación detenida",startConversation:"Iniciar conversación",downloadConversation:"Descargar conversación",liveCaptions:"SubtĆ­tulos en vivo",toggleChatbot:"Mostrar/ocultar avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Espere, estamos iniciando el asistente",statusReconnecting:"Problema de conexión, intentando reconectar...",statusFailed:"La conexión falló. Puede ser necesaria una acción manual.",statusInvalidConfiguration:"El avatar no estĆ” configurado correctamente, contacte al administrador.",close:"Cerrar",lastAssistantMessage:"Último mensaje del asistente",fullBodyView:"Vista de cuerpo completo",upperBodyView:"Vista de torso",previousConversationFound:"Se encontró una conversación anterior; elija una opción para continuar",secureFormTitle:"Formulario seguro",secureFormDescription:"Ingrese su información.",name:"Nombre*",namePlaceholder:"Ingrese su nombre",phoneNumber:"NĆŗmero de telĆ©fono",phonePlaceholder:"Ingrese su nĆŗmero de telĆ©fono",email:"Correo electrónico",emailPlaceholder:"Ingrese su correo electrónico",secureFormNote:"Nota: Su información no se compartirĆ” con el LLM ni se almacenarĆ”.",save:"Guardar",cancel:"Cancelar",conversationEndedPrompt:"Conversación finalizada. Califique su satisfacción.",submit:"Enviar",skip:"Omitir",consentTitle:"Consentimiento para conversación con IA",consentInfo1:"Solo con fines informativos — sin consejos mĆ©dicos, legales, financieros ni de seguridad.",consentInfo2:"Usamos almacenamiento de sesión y enviamos su entrada para responder. No guardamos su conversación ni datos personales tras esta sesión.",consentReadOur:"Lea nuestros",consentTermsLabel:"TĆ©rminos",consentAnd:"y",consentPrivacyLabel:"PolĆ­tica de privacidad",consentMoreDetails:"para mĆ”s detalles.",consentInfo4:"(Su consentimiento se aplica solo a esta sesión y se borra al cerrar la pestaƱa o ventana)",consentAccept:"Acepto",consentDecline:"Rechazar",consentAcceptAria:"Acepto – iniciar chat",consentDeclineAria:"Rechazar",interruptSpeaking:"Interrumpir avatar que habla",turnOnMic:"Activar micrófono",turnOffMic:"Desactivar micrófono",startConversationReminder:"Inicie una conversación para chatear.",enterInfoOnMobile:"Ingrese su información en la pĆ”gina de usuario",waitCurrentResponse:"Espere la respuesta actual antes de enviar otro mensaje.",resumeConversationPrompt:"Se encontró una conversación anterior. ĀæDesea reanudar donde la dejó o terminarla?",resume:"Reanudar",end:"Terminar",endConversationPrompt:"ĀæDesea terminar la conversación? Esto eliminarĆ” el historial permanentemente.",restartConversationPrompt:"ĀæSeguro que quiere iniciar una nueva conversación? La conversación actual se eliminarĆ”.",newConversation:"Nueva",conversationExpiredPrompt:"Esta conversación ha expirado y no se puede reanudar. ĀæDesea descargar una copia y borrar o solo borrar?",downloadAndClear:"Descargar y borrar",onlyClear:"Solo borrar",confirm:"Confirmar"},ar:{start:"Ų§ŲØŲÆŲ£ المحادثة",connect:"اتصل",endConversation:"؄نهاؔ المحادثة",restartConversation:"Ų„Ų¹Ų§ŲÆŲ© ŲØŲÆŲ” المحادثة",hideTyping:"؄خفاؔ حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",showTyping:"؄ظهار حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",reconnecting:"Ų¬Ų§Ų±Ł Ų„Ų¹Ų§ŲÆŲ© الاتصال...",waitForResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد...",typeHere:"اكتب هنا.",noMessagesYet:"لا توجد رسائل ŲØŲ¹ŲÆ...",conversationStatus:"حالة المحادثة",conversationInProgress:"المحادثة جارية",conversationStopped:"المحادثة Ł…ŲŖŁˆŁ‚ŁŲ©",startConversation:"Ų§ŲØŲÆŲ£ المحادثة",downloadConversation:"ŲŖŁ†Ų²ŁŠŁ„ المحادثة",liveCaptions:"ŲŖŲ¹Ł„ŁŠŁ‚Ų§ŲŖ Ł†ŲµŁŠŲ© Ł…ŲØŲ§Ų“Ų±Ų©",toggleChatbot:"؄ظهار/؄خفاؔ روبوت المحادثة",avatar:"أفاتار",chat:"ŲÆŲ±ŲÆŲ“Ų©",statusInitializing:"ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ų§Ł†ŲŖŲøŲ§Ų±ŲŒ Ł†Ł‚ŁˆŁ… ŲØŲŖŲ“ŲŗŁŠŁ„ الأفاتار!",statusReconnecting:"Ł…Ų“ŁƒŁ„Ų© في Ų§Ł„Ų§ŲŖŲµŲ§Ł„ŲŒ Ų¬Ų§Ų±Ł Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© مجددًا...",statusFailed:"فؓل الاتصال. قد ŁŠŲŖŲ·Ł„ŲØ الأمر تدخلاً ŁŠŲÆŁˆŁŠŁ‹Ų§.",statusInvalidConfiguration:"الأفاتار غير Ł…Ł‡ŁŠŲ£ ŲØŲ“ŁƒŁ„ صحيح، ŁŠŲ±Ų¬Ł‰ Ų§Ł„ŲŖŁˆŲ§ŲµŁ„ Ł…Ų¹ Ų§Ł„Ł…Ų³Ų¤ŁˆŁ„.",close:"؄غلاق",lastAssistantMessage:"Ų¢Ų®Ų± رسالة من الأفاتار",fullBodyView:"Ų¹Ų±Ų¶ ŁƒŲ§Ł…Ł„ للجسم",upperBodyView:"Ų¹Ų±Ų¶ للجزؔ Ų§Ł„Ų¹Ł„ŁˆŁŠ",previousConversationFound:"ŲŖŁ… Ų§Ł„Ų¹Ų«ŁˆŲ± على Ł…Ų­Ų§ŲÆŲ«Ų© سابقة - ŁŠŲ±Ų¬Ł‰ اختيار خيار للمتابعة",secureFormTitle:"Ł†Ł…ŁˆŲ°Ų¬ آمن",secureFormDescription:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ.",name:"الاسم*",namePlaceholder:"أدخل Ų§Ų³Ł…Łƒ",phoneNumber:"رقم الهاتف",phonePlaceholder:"أدخل رقم Ł‡Ų§ŲŖŁŁƒ",email:"Ų§Ł„ŲØŲ±ŁŠŲÆ Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",emailPlaceholder:"أدخل بريدك Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",secureFormNote:"ملاحظة: لن ŲŖŲŖŁ… Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł…Ų¹ Ł†Ł…ŁˆŲ°Ų¬ اللغة ŁˆŁ„Ł† ŁŠŲŖŁ… ŲŖŲ®Ų²ŁŠŁ†Ł‡Ų§.",save:"حفظ",cancel:"؄لغاؔ",conversationEndedPrompt:"انتهت المحادثة. ŁŠŲ±Ų¬Ł‰ ŲŖŁ‚ŁŠŁŠŁ… مدى رضاك.",submit:"Ų„Ų±Ų³Ų§Ł„",skip:"تخطي",consentTitle:"Ł…ŁˆŲ§ŁŁ‚Ų© على Ł…Ų­Ų§ŲÆŲ«Ų© Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ",consentInfo1:"Ł„Ł„Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ العامة فقط — ŲØŲÆŁˆŁ† نصائح طبية أو Ł‚Ų§Ł†ŁˆŁ†ŁŠŲ© أو Ł…Ų§Ł„ŁŠŲ© أو Ų£Ł…Ł†ŁŠŲ©.",consentInfo2:"نستخدم ŲŖŲ®Ų²ŁŠŁ† الجلسة ŁˆŁ†Ų±Ų³Ł„ Ł…ŲÆŲ®Ł„Ų§ŲŖŁƒ Ł„ŲŖŁ‚ŲÆŁŠŁ… Ų§Ł„Ų±ŲÆŁˆŲÆ. لا نحتفظ ŲØŁ…Ų­Ų§ŲÆŲ«ŲŖŁƒ أو ŲØŁŠŲ§Ł†Ų§ŲŖŁƒ Ų§Ł„Ų“Ų®ŲµŁŠŲ© ŲØŲ¹ŲÆ هذه الجلسة.",consentReadOur:"اقرأ",consentTermsLabel:"Ų§Ł„Ų“Ų±ŁˆŲ·",consentAnd:"و",consentPrivacyLabel:"سياسة Ų§Ł„Ų®ŲµŁˆŲµŁŠŲ©",consentMoreDetails:"Ł„Ł„Ł…Ų²ŁŠŲÆ من Ų§Ł„ŲŖŁŲ§ŲµŁŠŁ„.",consentInfo4:"(تنطبق Ł…ŁˆŲ§ŁŁ‚ŲŖŁƒ على جلسة التصفح Ų§Ł„Ų­Ų§Ł„ŁŠŲ© فقط ŁˆŁŠŲŖŁ… مسحها عند ؄غلاق الصفحة أو النافذة)",consentAccept:"Ų£ŁˆŲ§ŁŁ‚",consentDecline:"رفض",consentAcceptAria:"Ų£ŁˆŲ§ŁŁ‚ - Ų§ŲØŲÆŲ£ المحادثة",consentDeclineAria:"رفض",interruptSpeaking:"Ų„ŁŠŁ‚Ų§Ł الأفاتار Ų§Ł„Ł…ŲŖŁƒŁ„Ł…",turnOnMic:"ŲŖŲ“ŲŗŁŠŁ„ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",turnOffMic:"Ų„ŁŠŁ‚Ų§Ł Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",startConversationReminder:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للتحدث.",enterInfoOnMobile:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ في صفحة Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ المستخدم",waitCurrentResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد Ų§Ł„Ų­Ų§Ł„ŁŠ قبل Ų„Ų±Ų³Ų§Ł„ رسالة أخرى.",resumeConversationPrompt:"ŲŖŁ… Ų§Ł„Ų¹Ų«ŁˆŲ± على Ł…Ų­Ų§ŲÆŲ«Ų© سابقة. هل ŲŖŲ±ŲŗŲØ في المتابعة من حيث ŲŖŁˆŁ‚ŁŲŖ أم Ų„Ł†Ł‡Ų§Ų¦Ł‡Ų§ŲŸ",resume:"استئناف",end:"؄نهاؔ",endConversationPrompt:"هل ŲŖŲ±ŲŗŲØ في ؄نهاؔ Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ سيؤدي Ų°Ł„Łƒ ؄لى حذف المحادثة Ł†Ł‡Ų§Ų¦ŁŠŁ‹Ų§.",restartConversationPrompt:"هل أنت Ł…ŲŖŲ£ŁƒŲÆ من ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة؟ Ų³ŁŠŲŖŁ… حذف المحادثة Ų§Ł„Ų­Ų§Ł„ŁŠŲ©.",newConversation:"جديدة",conversationExpiredPrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© هذه المحادثة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل تريد ŲŖŁ†Ų²ŁŠŁ„ نسخة Ų«Ł… حذفها أو الحذف ŁŁ‚Ų·ŲŸ",downloadAndClear:"ŲŖŁ†Ų²ŁŠŁ„ وحذف",onlyClear:"حذف فقط",confirm:"تأكيد"},zh:{start:"å¼€å§‹åÆ¹čÆ",connect:"čæžęŽ„",endConversation:"ē»“ęŸåÆ¹čÆ",restartConversation:"é‡ę–°å¼€å§‹åÆ¹čÆ",hideTyping:"éšč—č¾“å…„ę”†",showTyping:"ę˜¾ē¤ŗč¾“å…„ę”†",reconnecting:"ę­£åœØé‡ę–°čæžęŽ„...",waitForResponse:"čÆ·ē­‰å¾…å›žå¤...",typeHere:"åœØę­¤č¾“å…„ć€‚",noMessagesYet:"ęš‚ę— ę¶ˆęÆ...",conversationStatus:"åÆ¹čÆēŠ¶ę€",conversationInProgress:"åÆ¹čÆčæ›č”Œäø­",conversationStopped:"åÆ¹čÆå·²åœę­¢",startConversation:"å¼€å§‹åÆ¹čÆ",downloadConversation:"äø‹č½½åÆ¹čÆ",liveCaptions:"å®žę—¶å­—å¹•",toggleChatbot:"显示/éšč—č™šę‹Ÿå½¢č±”åŠ©ę‰‹",avatar:"č™šę‹Ÿå½¢č±”",chat:"聊天",statusInitializing:"čÆ·ēØå€™ļ¼Œęˆ‘ä»¬ę­£åœØå”¤é†’åŠ©ę‰‹ļ¼",statusReconnecting:"čæžęŽ„å‡ŗēŽ°é—®é¢˜ļ¼Œę­£åœØå°čÆ•é‡ę–°čæžęŽ„...",statusFailed:"čæžęŽ„å¤±č“„ć€‚åÆčƒ½éœ€č¦ę‰‹åŠØå¤„ē†ć€‚",statusInvalidConfiguration:"č™šę‹Ÿå½¢č±”é…ē½®äøę­£ē”®ļ¼ŒčÆ·č”ē³»ē®”ē†å‘˜ć€‚",close:"关闭",lastAssistantMessage:"åŠ©ę‰‹ēš„äøŠäø€ę”ę¶ˆęÆ",fullBodyView:"全身视图",upperBodyView:"åŠčŗ«č§†å›¾",previousConversationFound:"ę‰¾åˆ°ä¹‹å‰ēš„åÆ¹čÆā€”ā€”čÆ·é€‰ę‹©äø€äøŖé€‰é”¹ē»§ē»­",secureFormTitle:"å®‰å…Øč”Øå•",secureFormDescription:"čÆ·č¾“å…„ę‚Øēš„äæ”ęÆć€‚",name:"姓名*",namePlaceholder:"čÆ·č¾“å…„å§“å",phoneNumber:"ē”µčÆå·ē ",phonePlaceholder:"čÆ·č¾“å…„ē”µčÆå·ē ",email:"电子邮件",emailPlaceholder:"请输兄电子邮件",secureFormNote:"ę³Øę„ļ¼šę‚Øēš„äæ”ęÆäøä¼šäøŽå¤§čÆ­čØ€ęØ”åž‹å…±äŗ«ļ¼Œä¹Ÿäøä¼šč¢«å­˜å‚Øć€‚",save:"äæå­˜",cancel:"å–ę¶ˆ",conversationEndedPrompt:"åÆ¹čÆå·²ē»“ęŸć€‚čÆ·čÆ„ä»·ę‚Øēš„ę»”ę„åŗ¦ć€‚",submit:"ęäŗ¤",skip:"跳过",consentTitle:"åŒę„čæ›č”Œäŗŗå·„ę™ŗčƒ½åÆ¹čÆ",consentInfo1:"ä»…ä¾›äø€čˆ¬äæ”ęÆå‚č€ƒā€”ā€”äøęä¾›åŒ»ē–—ć€ę³•å¾‹ć€č“¢åŠ”ęˆ–å®‰å…Øå»ŗč®®ć€‚",consentInfo2:"ęˆ‘ä»¬ä½æē”Øä¼ščÆå­˜å‚Øå¹¶å‘é€ę‚Øēš„č¾“å…„ä»„ęä¾›å›žå¤ć€‚ęœ¬ę¬”ä¼ščÆē»“ęŸåŽęˆ‘ä»¬äøä¼šäæē•™ę‚Øēš„åÆ¹čÆęˆ–äøŖäŗŗäæ”ęÆć€‚",consentReadOur:"é˜…čÆ»ęˆ‘ä»¬ēš„",consentTermsLabel:"ę”ę¬¾",consentAnd:"和",consentPrivacyLabel:"éšē§ę”æē­–",consentMoreDetails:"äŗ†č§£ę›“å¤ščÆ¦ęƒ…ć€‚",consentInfo4:"ļ¼ˆę‚Øēš„åŒę„ä»…é€‚ē”ØäŗŽęœ¬ę¬”ä¼ščÆļ¼Œå…³é—­ę ‡ē­¾é”µęˆ–ēŖ—å£åŽå°†č¢«ęø…é™¤ļ¼‰",consentAccept:"åŒę„",consentDecline:"ę‹’ē»",consentAcceptAria:"åŒę„ā€”ā€”å¼€å§‹čŠå¤©",consentDeclineAria:"ę‹’ē»",interruptSpeaking:"ę‰“ę–­č™šę‹Ÿå½¢č±”č®²čÆ",turnOnMic:"å¼€åÆéŗ¦å…‹é£Ž",turnOffMic:"å…³é—­éŗ¦å…‹é£Ž",startConversationReminder:"å¼€å§‹åÆ¹čÆä»„ä¾æčŠå¤©ć€‚",enterInfoOnMobile:"čÆ·åœØē”Øęˆ·äæ”ęÆé”µé¢č¾“å…„ę‚Øēš„äæ”ęÆ",waitCurrentResponse:"čÆ·ē­‰å¾…å½“å‰å›žå¤åŽå†å‘é€ę–°ę¶ˆęÆć€‚",resumeConversationPrompt:"ę‰¾åˆ°ä¹‹å‰ēš„åÆ¹čÆć€‚č¦ä»Žäø­ę–­å¤„ē»§ē»­čæ˜ę˜Æē»“ęŸļ¼Ÿ",resume:"ē»§ē»­",end:"ē»“ęŸ",endConversationPrompt:"ę˜Æå¦ē»“ęŸåÆ¹čÆļ¼Ÿē»“ęŸåŽå°†ę°øä¹…åˆ é™¤åŽ†å²č®°å½•ć€‚",restartConversationPrompt:"ē”®å®šč¦å¼€å§‹ę–°ēš„åÆ¹čÆå—ļ¼Ÿå½“å‰åÆ¹čÆå°†č¢«åˆ é™¤ć€‚",newConversation:"ꖰ",conversationExpiredPrompt:"ę­¤åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øč¦äø‹č½½å‰Æęœ¬å¹¶ęø…é™¤ļ¼Œčæ˜ę˜Æä»…ęø…é™¤ļ¼Ÿ",downloadAndClear:"下载并清除",onlyClear:"仅清除",confirm:"甮认"}},Re=document.createElement("link");Re.rel="preconnect",Re.href="https://fonts.googleapis.com",Re.crossOrigin="anonymous",document.head.appendChild(Re);const Te=document.createElement("link");Te.rel="preconnect",Te.href="https://fonts.gstatic.com",Te.crossOrigin="anonymous",document.head.appendChild(Te);const Le=document.createElement("link");Le.href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block",Le.rel="stylesheet",document.head.appendChild(Le);const ze=document.createElement("link");ze.href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap",ze.rel="stylesheet",document.head.appendChild(ze);class Me extends(function(t=Object){return class extends t{constructor(...t){super(...t),this._eventBus=new Yt,this._domDisposers=[]}get bus(){return this._eventBus}_onBus(t,e){return this._eventBus.on(t,e)}_onDom(t,e,i,a){t.addEventListener(e,i,a);const n=()=>t.removeEventListener(e,i,a);return this._domDisposers.push(n),n}pushDisposer(t){if("function"!=typeof t)throw new TypeError("Disposer must be a function");this._domDisposers.push(t)}_disposeListeners(){this._eventBus.dispose(),this._domDisposers.forEach((t=>{try{t()}catch(e){}})),this._domDisposers.length=0}_createChildBus(){return new Yt}}}(A)){static get properties(){return{api_key:{type:String,attribute:"api-key"},token_endpoint:{type:String,attribute:"token-endpoint"},avatar_id:{type:String,attribute:"avatar-id"},toggler:{type:Boolean,reflect:!0,converter:t=>"false"!==t},barge_in:{type:Boolean,reflect:!0,attribute:"barge-in",converter:t=>"false"!==t},terms_href:{type:String,attribute:"terms-href"},privacy_href:{type:String,attribute:"privacy-href"},brand_name:{type:String,attribute:"brand-name"},brand_logo:{type:String,attribute:"brand-logo"},username:{type:String},phoneNumber:{type:String},email:{type:String},isTermsAccepted:{type:Boolean,attribute:"terms-accepted"},compact:{type:Boolean,reflect:!0,converter:t=>"false"!==t},target_app:{type:String,attribute:"target-app"},enable_captions:{type:Boolean,reflect:!0,attribute:"enable-captions",converter:t=>"false"!==t},uiLanguage:{type:String,attribute:"ui-language"},canvasWidth:{type:Number,reflect:!0,attribute:"canvas-width"},canvasHeight:{type:Number,reflect:!0,attribute:"canvas-height"},chatbotHeight:{type:Number,reflect:!0,attribute:"chatbot-height"},avatarBackground:{type:String,reflect:!0,attribute:"avatar-background"},cornerRadius:{type:String,reflect:!0,attribute:"corner-radius"},_canvasWidth:{type:Number,attribute:!1},_canvasHeight:{type:Number,attribute:!1},_chatbotHeight:{type:Number,attribute:!1},_language:{type:String,attribute:!1},_avatarName:{type:String,attribute:!1},_currentMessage:{type:Object,attribute:!1},_actorSnapshot:{type:Object,attribute:!1},_conversationTranscript:{type:Array,attribute:!1},_showConversationPanel:{type:Boolean,attribute:!1},_showChatbot:{type:Boolean,attribute:!1},_showMenu:{type:Boolean,attribute:!1},_shownPage:{type:String,attribute:!1},_showUserData:{type:Boolean,attribute:!1},_showSatisfactionScore:{type:Boolean,attribute:!1},_showLastMessage:{type:Boolean,attribute:!1},_satisfactionScore:{type:Number,attribute:!1},_lastMessageText:{type:String,attribute:!1},_liveCaption:{type:String,attribute:!1},_liveCaptionSpeaker:{type:String,attribute:!1},_isLiveCaptionsVisible:{type:Boolean,attribute:!1,reflect:!1},_showConfirmationDialog:{type:Boolean,attribute:!1},_dialogMessage:{type:String,attribute:!1},_confirmButtonLabel:{type:String,attribute:!1},_cancelButtonLabel:{type:String,attribute:!1},_showCopyTick:{type:Boolean,attribute:!1},_isFullBody:{type:Boolean,attribute:!1},_showTyping:{type:Boolean,attribute:!1},_statusBarStatus:{type:String,attribute:!1},_inputsBlocked:{type:Boolean,attribute:!1},_isThinking:{type:Boolean,attribute:!1},_isListening:{type:Boolean,attribute:!1},_isSpeaking:{type:Boolean,attribute:!1},_isConversationInProgress:{type:Boolean,attribute:!1},_isConversationPaused:{type:Boolean,attribute:!1},_isConversationResumable:{type:Boolean,attribute:!1},_isInitializingConversation:{type:Boolean,attribute:!1},_isConversationTimedOut:{type:Boolean,attribute:!1},_isStartingConversation:{type:Boolean,attribute:!1},_isConversationStopped:{type:Boolean,attribute:!1},_isDisconnected:{type:Boolean,attribute:!1},_isFailed:{type:Boolean,attribute:!1},_avatarRunning:{type:Boolean,attribute:!1},_showChatConsentDialog:{type:Boolean,attribute:!1}}}static get observedAttributes(){const t=super.observedAttributes??[];return[...new Set([...t,"api_key","token_endpoint","avatar_id","terms_href","privacy_href","brand_name","brand_logo","target_app","enable_captions","barge_in"])]}attributeChangedCallback(t,e,i){if(super.attributeChangedCallback&&super.attributeChangedCallback(t,e,i),t in{api_key:"api-key",token_endpoint:"token-endpoint",avatar_id:"avatar-id",terms_href:"terms-href",privacy_href:"privacy-href",brand_name:"brand-name",brand_logo:"brand-logo",target_app:"target-app",enable_captions:"enable-captions",barge_in:"barge-in",avatar_background:"avatar-background"}){try{this._deprecatedAttrWarnings=this._deprecatedAttrWarnings||new Set,this._deprecatedAttrWarnings.has(t)||this._deprecatedAttrWarnings.add(t)}catch(a){}switch(t){case"enable_captions":case"barge_in":{const e=null!==i&&"false"!==i;this[t]=e;break}case"avatar_background":this.avatarBackground=i;break;default:this[t]=i}}}static styles=[fe,be,_e,ke,xe,Se,we];constructor(){super(),this.api_key="",this.token_endpoint="",this.avatar_id="",this.toggler=!0,this.barge_in=!1,this.terms_href="",this.privacy_href="",this.brand_name="",this.brand_logo="",this.compact=!1,this.target_app="web",this.enable_captions=!0,this.uiLanguage=Ae,this.canvasWidth=E.dom.canvasWidth,this.canvasHeight=E.dom.canvasHeight,this.chatbotHeight=E.dom.canvasHeight+E.dom.headerAndFooterHeight,this._canvasWidth=E.dom.canvasWidth,this._canvasHeight=E.dom.canvasHeight,this._chatbotHeight=E.dom.canvasHeight+E.dom.headerAndFooterHeight,this._speakingAvatar=null,this._language="",this.username="",this.phoneNumber="",this.email="",this.isTermsAccepted=!1,this._avatarName="Assistant",this._conversationTranscript=[],this._currentMessage=null,this._actorSnapshot={value:"initializing",context:{transcript:[]},matches:()=>!1},this._showConversationPanel=!1,this._showChatbot=!1,this._showMenu=!1,this._shownPage="LoaderPage",(this.api_key||this.token_endpoint)&&this.avatar_id?this._statusBarStatus="initializing":(this._shownPage="ErrorPage",this._statusBarStatus="invalidConfiguration"),this._showUserData=!1,this._showSatisfactionScore=!1,this._showLastMessage=!1,this._satisfactionScore=null,this._lastMessageText="",this._liveCaption="",this._liveCaptionSpeaker="",this._isLiveCaptionsVisible=!0,this._alerts=null,this._showConfirmationDialog=!1,this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel"),this._stateTestMode=E.test.stateTestMode,this._showCopyTick=!1,this._isFullBody=!0,this._showTyping=!1,this._wakeLock=new Jt,this._focusTimeoutId=null,this.captionsTimeoutId=null,this._userCaptionClearTimeoutId=null,this._connection="unknown",this._initTriggered=!1,this._initInProgress=!1,this._initPromise=null,this._inputsBlocked=!1,this._isThinking=!1,this._isListening=!1,this._isSpeaking=!1,this._isConversationInProgress=!1,this._isConversationPaused=!1,this._isConversationResumable=!1,this._isInitializingConversation=!1,this._isConversationTimedOut=!1,this._isStartingConversation=!1,this._isConversationStopped=!1,this._isDisconnected=!1,this._isFailed=!1,this._avatarRunning=!1,this._showChatConsentDialog=!1,this.avatarBackground="",this.cornerRadius=void 0,this._dirManagedByUiLanguage=!1,this._lastUiChatbotMode={isShown:null,chatbotMode:null},this._speakingAvatar=new Gt(this.bus),this._applyBargeInPreference(),this._setupAvatarStateSubscription()}_t(t){return function(t,e){const i=function(t){if(!t||"string"!=typeof t)return Ae;const e=t.toLowerCase();if(Ce[e])return e;const i=e.split("-")[0];return Ce[i]?i:Ae}(t),a=Ce[i]?.[e];return void 0!==a?a:Ce[Ae]?.[e]??e}(this.uiLanguage,t)}_applyUiLanguage(){this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_applyDirectionFromUiLanguage(){const t=!0===this._dirManagedByUiLanguage,e=this.getAttribute("dir");if(!t&&("rtl"===e||"ltr"===e||"auto"===e))return;const i=(this.uiLanguage||Ae).toLowerCase().split("-")[0],a=["ar","he","fa","ur"].includes(i)?"rtl":"ltr";this.dir!==a?(this.dir=a,this._dirManagedByUiLanguage=!0):t||(this._dirManagedByUiLanguage=!0)}_getAvatarBackgroundStyleObj(){const t=(this.avatarBackground??"").toString().trim();if(!t)return{};const e=t.toLowerCase();if(e.includes("url(")||e.includes("expression(")||e.includes("@import")||e.includes("@supports")||e.includes("@media"))return{};if(this._bgTestEl??="undefined"!=typeof document&&document?.createElement?document.createElement("div"):null,!this._bgTestEl)return{};const i=this._bgTestEl;if(/^(linear-gradient|radial-gradient|conic-gradient)\(/i.test(t)){if("undefined"!=typeof CSS&&CSS.supports?.("background-image",t))return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{};try{return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{}}catch(a){return{}}}if("undefined"!=typeof CSS&&CSS.supports?.("color",t))return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{};try{return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{}}catch(a){return{}}}_applyBargeInPreference(){const t=!1!==this.barge_in;try{E?.speech?.bargeIn&&(E.speech.bargeIn.enabled=t)}catch(e){}if(this._speakingAvatar?.setBargeInEnabled)try{const e=this._speakingAvatar.setBargeInEnabled(t);e&&"function"==typeof e.catch&&e.catch((t=>{}))}catch(e){}}firstUpdated(){const t=this.renderRoot.querySelector("#toastify-dismissable-alerts");this._alerts=new Xt(this.bus,t);try{const t=()=>this.classList.add("icons-ready");document.fonts&&document.fonts.ready?document.fonts.ready.then(t).catch((()=>t())):setTimeout(t,300)}catch(e){}}_setupAvatarStateSubscription(){if(this._speakingAvatar?.avatarOrchestrator){if(this._orchestratorUnsub){try{this._orchestratorUnsub()}catch{}this._orchestratorUnsub=null}this._orchestratorUnsub=this._speakingAvatar.avatarOrchestrator.subscribeProjected(((t,e)=>{if(!e)return;const i=this._actorSnapshot;this._actorSnapshot=e;let a=!1;const n=(t,e)=>{this[t]!==e&&(this[t]=e,a=!0)};try{n("_isConversationInProgress",!!e.hasTag?.("conversation_in_progress")),n("_isConversationPaused",!!e.hasTag?.("conversation_paused")),n("_isSpeaking",!!e.hasTag?.("speaking")),n("_isListening",!!e.hasTag?.("listening")),n("_isThinking",!!e.hasTag?.("thinking")),n("_inputsBlocked",!!e.hasTag?.("inputs_blocked")),n("_isConversationResumable",!!e.matches?.("lifecycle.conversation.resumable")),n("_isInitializingConversation",!(!e.matches?.("lifecycle.conversation.initializingConversation")&&!e.matches?.("lifecycle.conversation.initializing"))),n("_isConversationTimedOut",!!e.matches?.("lifecycle.conversation.timedOut")),n("_isStartingConversation",!(!e.matches?.("lifecycle.conversation.inProgress.startingConversation")&&!e.matches?.("lifecycle.conversation.starting"))),n("_isConversationStopped",!!e.matches?.("lifecycle.conversation.stopped")),n("_isDisconnected",!!e.matches?.("connection.disconnected")),n("_isFailed",!(!e.matches?.("lifecycle.init.failed")&&!e.matches?.("lifecycle.failed")))}catch(s){}try{const t=i?.matches?.("lifecycle.conversation.resumable"),a=e.matches?.("lifecycle.conversation.resumable");!a||t||this._showConfirmationDialog||this.toggler&&!1===this._showChatbot||this._showResumeConversationDialog()}catch(s){}(a||i!==e)&&this.updateAlertStatus()}))}}updated(t){if(this.__postUpdateQueue||(this.__postUpdateQueue=[]),(t.has("toggler")||t.has("compact"))&&this.toggler&&this.compact&&(this.compact=!1),t.has("compact")&&this.compact&&this.isInitialized()&&(this._shownPage="AvatarPage"),t.has("uiLanguage")&&(this._applyUiLanguage(),this._applyDirectionFromUiLanguage()),t.has("barge_in")&&this.__postUpdateQueue.push((()=>this._applyBargeInPreference())),this.isInitialized()&&this._speakingAvatar?.sessionData&&(t.has("username")&&this.username!==this._speakingAvatar.sessionData.username&&(this._speakingAvatar.sessionData.username=this.username),t.has("phoneNumber")&&this.phoneNumber!==this._speakingAvatar.sessionData.phoneNumber&&(this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber),t.has("email")&&this.email!==this._speakingAvatar.sessionData.email&&(this._speakingAvatar.sessionData.email=this.email),t.has("isTermsAccepted")&&this.isTermsAccepted!==this._speakingAvatar.sessionData.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted)),t.has("api_key")||t.has("token_endpoint")||t.has("avatar_id")){const t=!(!this.api_key&&!this.token_endpoint||!this.avatar_id);t&&!this._initTriggered?(this._initTriggered=!0,this.__postUpdateQueue.push((()=>this._initialize()))):t||(this._initTriggered=!1,this.__postUpdateQueue.push((()=>this.updateAlertStatus("ErrorPage"))))}if((t.has("_showChatbot")||t.has("_shownPage"))&&(this.__postUpdateQueue.push((()=>{this._speakingAvatar?.chatSocket&&this._syncUiChatbotMode()})),t.has("_shownPage")&&this.__postUpdateQueue.push((()=>this._speakingAvatar?.avatarOrchestrator?.sendEvent("PAGE_CHANGED",{newPage:this._shownPage}))),t.has("_showChatbot")&&this.__postUpdateQueue.push((()=>{if(!("mobile"===this.target_app||this.toggler&&window.innerWidth<768))try{this.style.removeProperty("--chatbot-dynamic-height")}catch(t){}requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>{try{this._speakingAvatar?.avatarModule?.onResize?.()}catch(t){}}))}))}))),this.toggler&&t.has("_showChatbot")&&this._showChatbot&&!this._isConversationInProgress){const t=!!this._isConversationResumable;this._startOrResumeConversation(!t)}if(t.has("_shownPage")&&("ChatPage"===this._shownPage?this._scheduleInputFocus("chat"):"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing")),t.has("_showTyping")&&"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing"),t.has("_inputsBlocked")&&!this._inputsBlocked&&!0===t.get("_inputsBlocked")&&this._scheduleInputFocus(),t.has("canvasWidth")||t.has("canvasHeight")||t.has("chatbotHeight")){const t=()=>this.updateSize();this.__postUpdateQueue.push((()=>requestAnimationFrame(t)))}if(this.__postUpdateQueue.length){const t=this.__postUpdateQueue.splice(0);Promise.resolve().then((()=>{for(const i of t)try{i()}catch(e){}}))}if(t.has("_showChatConsentDialog")&&(this._showChatConsentDialog?this._activateConsentFocusTrap():this._deactivateConsentFocusTrap()),t.has("cornerRadius"))try{const t=this.cornerRadius;if(null==t||""===t)this.style.removeProperty("--corner-radius");else{const e=String(t).trim(),i=/^-?\d+(?:\.\d+)?$/.test(e)?`${e}px`:e;this.style.setProperty("--corner-radius",i)}}catch(e){}}render(){return k`
2264
+ `,Te=document.createElement("link");Te.rel="preconnect",Te.href="https://fonts.googleapis.com",Te.crossOrigin="anonymous",document.head.appendChild(Te);const Le=document.createElement("link");Le.rel="preconnect",Le.href="https://fonts.gstatic.com",Le.crossOrigin="anonymous",document.head.appendChild(Le);const ze=document.createElement("link");ze.href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block",ze.rel="stylesheet",document.head.appendChild(ze);const Ie=document.createElement("link");Ie.href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap",Ie.rel="stylesheet",document.head.appendChild(Ie);class Me extends(function(t=Object){return class extends t{constructor(...t){super(...t),this._eventBus=new Yt,this._domDisposers=[]}get bus(){return this._eventBus}_onBus(t,e){return this._eventBus.on(t,e)}_onDom(t,e,i,a){t.addEventListener(e,i,a);const n=()=>t.removeEventListener(e,i,a);return this._domDisposers.push(n),n}pushDisposer(t){if("function"!=typeof t)throw new TypeError("Disposer must be a function");this._domDisposers.push(t)}_disposeListeners(){this._eventBus.dispose(),this._domDisposers.forEach((t=>{try{t()}catch(e){}})),this._domDisposers.length=0}_createChildBus(){return new Yt}}}(A)){static get properties(){return{api_key:{type:String,attribute:"api-key"},token_endpoint:{type:String,attribute:"token-endpoint"},avatar_id:{type:String,attribute:"avatar-id"},toggler:{type:Boolean,reflect:!0,converter:t=>"false"!==t},barge_in:{type:Boolean,reflect:!0,attribute:"barge-in",converter:t=>"false"!==t},terms_href:{type:String,attribute:"terms-href"},privacy_href:{type:String,attribute:"privacy-href"},brand_name:{type:String,attribute:"brand-name"},brand_logo:{type:String,attribute:"brand-logo"},username:{type:String},phoneNumber:{type:String},email:{type:String},isTermsAccepted:{type:Boolean,attribute:"terms-accepted"},compact:{type:Boolean,reflect:!0,converter:t=>"false"!==t},target_app:{type:String,attribute:"target-app"},enable_captions:{type:Boolean,reflect:!0,attribute:"enable-captions",converter:t=>"false"!==t},uiLanguage:{type:String,attribute:"ui-language"},canvasWidth:{type:Number,reflect:!0,attribute:"canvas-width"},canvasHeight:{type:Number,reflect:!0,attribute:"canvas-height"},chatbotHeight:{type:Number,reflect:!0,attribute:"chatbot-height"},avatarBackground:{type:String,reflect:!0,attribute:"avatar-background"},cornerRadius:{type:String,reflect:!0,attribute:"corner-radius"},_canvasWidth:{type:Number,attribute:!1},_canvasHeight:{type:Number,attribute:!1},_chatbotHeight:{type:Number,attribute:!1},_language:{type:String,attribute:!1},_avatarName:{type:String,attribute:!1},_currentMessage:{type:Object,attribute:!1},_actorSnapshot:{type:Object,attribute:!1},_conversationTranscript:{type:Array,attribute:!1},_showConversationPanel:{type:Boolean,attribute:!1},_showChatbot:{type:Boolean,attribute:!1},_showMenu:{type:Boolean,attribute:!1},_shownPage:{type:String,attribute:!1},_showUserData:{type:Boolean,attribute:!1},_showSatisfactionScore:{type:Boolean,attribute:!1},_showLastMessage:{type:Boolean,attribute:!1},_satisfactionScore:{type:Number,attribute:!1},_lastMessageText:{type:String,attribute:!1},_liveCaption:{type:String,attribute:!1},_liveCaptionSpeaker:{type:String,attribute:!1},_isLiveCaptionsVisible:{type:Boolean,attribute:!1,reflect:!1},_showConfirmationDialog:{type:Boolean,attribute:!1},_dialogMessage:{type:String,attribute:!1},_confirmButtonLabel:{type:String,attribute:!1},_cancelButtonLabel:{type:String,attribute:!1},_showCopyTick:{type:Boolean,attribute:!1},_isFullBody:{type:Boolean,attribute:!1},_showTyping:{type:Boolean,attribute:!1},_statusBarStatus:{type:String,attribute:!1},_inputsBlocked:{type:Boolean,attribute:!1},_isThinking:{type:Boolean,attribute:!1},_isListening:{type:Boolean,attribute:!1},_isSpeaking:{type:Boolean,attribute:!1},_isConversationInProgress:{type:Boolean,attribute:!1},_isConversationPaused:{type:Boolean,attribute:!1},_isAutoResuming:{type:Boolean,attribute:!1},_isResumeExpired:{type:Boolean,attribute:!1},_isInitializingConversation:{type:Boolean,attribute:!1},_isConversationTimedOut:{type:Boolean,attribute:!1},_isStartingConversation:{type:Boolean,attribute:!1},_isConversationStopped:{type:Boolean,attribute:!1},_isDisconnected:{type:Boolean,attribute:!1},_isFailed:{type:Boolean,attribute:!1},_avatarRunning:{type:Boolean,attribute:!1},_showChatConsentDialog:{type:Boolean,attribute:!1}}}static get observedAttributes(){const t=super.observedAttributes??[];return[...new Set([...t,"api_key","token_endpoint","avatar_id","terms_href","privacy_href","brand_name","brand_logo","target_app","enable_captions","barge_in"])]}attributeChangedCallback(t,e,i){if(super.attributeChangedCallback&&super.attributeChangedCallback(t,e,i),t in{api_key:"api-key",token_endpoint:"token-endpoint",avatar_id:"avatar-id",terms_href:"terms-href",privacy_href:"privacy-href",brand_name:"brand-name",brand_logo:"brand-logo",target_app:"target-app",enable_captions:"enable-captions",barge_in:"barge-in",avatar_background:"avatar-background"}){try{this._deprecatedAttrWarnings=this._deprecatedAttrWarnings||new Set,this._deprecatedAttrWarnings.has(t)||this._deprecatedAttrWarnings.add(t)}catch(a){}switch(t){case"enable_captions":case"barge_in":{const e=null!==i&&"false"!==i;this[t]=e;break}case"avatar_background":this.avatarBackground=i;break;default:this[t]=i}}}static styles=[xe,ke,Se,Ae,we,Re,Ce];constructor(){super(),this.api_key="",this.token_endpoint="",this.avatar_id="",this.toggler=!0,this.barge_in=!1,this.terms_href="",this.privacy_href="",this.brand_name="",this.brand_logo="",this.compact=!1,this.target_app="web",this.enable_captions=!0,this.uiLanguage=Xt,this.canvasWidth=E.dom.canvasWidth,this.canvasHeight=E.dom.canvasHeight,this.chatbotHeight=E.dom.canvasHeight+E.dom.headerAndFooterHeight,this._canvasWidth=E.dom.canvasWidth,this._canvasHeight=E.dom.canvasHeight,this._chatbotHeight=E.dom.canvasHeight+E.dom.headerAndFooterHeight,this._speakingAvatar=null,this._language="",this.username="",this.phoneNumber="",this.email="",this.isTermsAccepted=!1,this._avatarName="Assistant",this._conversationTranscript=[],this._currentMessage=null,this._actorSnapshot={value:"initializing",context:{transcript:[]},matches:()=>!1},this._showConversationPanel=!1,this._showChatbot=!1,this._showMenu=!1,this._shownPage="LoaderPage",this._savedChatbotMode=null,(this.api_key||this.token_endpoint)&&this.avatar_id?this._statusBarStatus="initializing":(this._shownPage="ErrorPage",this._statusBarStatus="invalidConfiguration"),this._showUserData=!1,this._showSatisfactionScore=!1,this._showLastMessage=!1,this._satisfactionScore=null,this._lastMessageText="",this._liveCaption="",this._liveCaptionSpeaker="",this._isLiveCaptionsVisible=!0,this._alerts=null,this._showConfirmationDialog=!1,this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel"),this._stateTestMode=E.test.stateTestMode,this._showCopyTick=!1,this._isFullBody=!0,this._showTyping=!1,this._wakeLock=new ee,this._focusTimeoutId=null,this.captionsTimeoutId=null,this._userCaptionClearTimeoutId=null,this._connection="unknown",this._initTriggered=!1,this._initInProgress=!1,this._initPromise=null,this._inputsBlocked=!1,this._isThinking=!1,this._isListening=!1,this._isSpeaking=!1,this._isConversationInProgress=!1,this._isConversationPaused=!1,this._isAutoResuming=!1,this._isResumeExpired=!1,this._isInitializingConversation=!1,this._isConversationTimedOut=!1,this._isStartingConversation=!1,this._isConversationStopped=!1,this._isDisconnected=!1,this._isFailed=!1,this._avatarRunning=!1,this._showChatConsentDialog=!1,this.avatarBackground="",this.cornerRadius=void 0,this._dirManagedByUiLanguage=!1,this._lastUiChatbotMode={isShown:null,chatbotMode:null},this._speakingAvatar=new Qt(this.bus),this._applyBargeInPreference(),this._setupAvatarStateSubscription()}_t(t){return Kt(this.uiLanguage,t)}_applyUiLanguage(){this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_applyDirectionFromUiLanguage(){const t=!0===this._dirManagedByUiLanguage,e=this.getAttribute("dir");if(!t&&("rtl"===e||"ltr"===e||"auto"===e))return;const i=(this.uiLanguage||Xt).toLowerCase().split("-")[0],a=["ar","he","fa","ur"].includes(i)?"rtl":"ltr";this.dir!==a?(this.dir=a,this._dirManagedByUiLanguage=!0):t||(this._dirManagedByUiLanguage=!0)}_getAvatarBackgroundStyleObj(){const t=(this.avatarBackground??"").toString().trim();if(!t)return{};const e=t.toLowerCase();if(e.includes("url(")||e.includes("expression(")||e.includes("@import")||e.includes("@supports")||e.includes("@media"))return{};if(this._bgTestEl??="undefined"!=typeof document&&document?.createElement?document.createElement("div"):null,!this._bgTestEl)return{};const i=this._bgTestEl;if(/^(linear-gradient|radial-gradient|conic-gradient)\(/i.test(t)){if("undefined"!=typeof CSS&&CSS.supports?.("background-image",t))return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{};try{return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{}}catch(a){return{}}}if("undefined"!=typeof CSS&&CSS.supports?.("color",t))return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{};try{return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{}}catch(a){return{}}}_applyBargeInPreference(){const t=!1!==this.barge_in;try{E?.speech?.bargeIn&&(E.speech.bargeIn.enabled=t)}catch(e){}if(this._speakingAvatar?.setBargeInEnabled)try{const e=this._speakingAvatar.setBargeInEnabled(t);e&&"function"==typeof e.catch&&e.catch((t=>{}))}catch(e){}}firstUpdated(){const t=this.renderRoot.querySelector("#toastify-dismissable-alerts");this._alerts=new Jt(this.bus,t,(()=>this.uiLanguage));try{const t=()=>this.classList.add("icons-ready");document.fonts&&document.fonts.ready?document.fonts.ready.then(t).catch((()=>t())):setTimeout(t,300)}catch(e){}}_setupAvatarStateSubscription(){if(this._speakingAvatar?.avatarOrchestrator){if(this._orchestratorUnsub){try{this._orchestratorUnsub()}catch{}this._orchestratorUnsub=null}this._orchestratorUnsub=this._speakingAvatar.avatarOrchestrator.subscribeProjected(((t,e)=>{if(!e)return;const i=this._actorSnapshot;this._actorSnapshot=e;let a=!1;const n=(t,e)=>{this[t]!==e&&(this[t]=e,a=!0)};try{n("_isConversationInProgress",!!e.hasTag?.("conversation_in_progress")),n("_isConversationPaused",!!e.hasTag?.("conversation_paused")),n("_isSpeaking",!!e.hasTag?.("speaking")),n("_isListening",!!e.hasTag?.("listening")),n("_isThinking",!!e.hasTag?.("thinking")),n("_inputsBlocked",!!e.hasTag?.("inputs_blocked")),n("_isAutoResuming",!!e.matches?.("lifecycle.conversation.autoResuming")),n("_isResumeExpired",!!e.matches?.("lifecycle.conversation.resumeExpired")),n("_isInitializingConversation",!(!e.matches?.("lifecycle.conversation.initializingConversation")&&!e.matches?.("lifecycle.conversation.initializing"))),n("_isConversationTimedOut",!!e.matches?.("lifecycle.conversation.timedOut")),n("_isStartingConversation",!!(e.matches?.("lifecycle.conversation.inProgress.startingConversation")||e.matches?.("lifecycle.conversation.starting")||e.matches?.("lifecycle.conversation.autoResuming"))),n("_isConversationStopped",!!e.matches?.("lifecycle.conversation.stopped")),n("_isDisconnected",!!e.matches?.("connection.disconnected")),n("_isFailed",!(!e.matches?.("lifecycle.init.failed")&&!e.matches?.("lifecycle.failed")))}catch(s){}(a||i!==e)&&this.updateAlertStatus()}))}}updated(t){if(this.__postUpdateQueue||(this.__postUpdateQueue=[]),(t.has("toggler")||t.has("compact"))&&this.toggler&&this.compact&&(this.compact=!1),(t.has("target_app")||t.has("toggler"))&&"mobile"===this.target_app&&this.toggler&&(this.toggler=!1),t.has("compact")&&this.compact&&this.isInitialized()&&(this._shownPage="AvatarPage"),t.has("uiLanguage")&&(this._applyUiLanguage(),this._applyDirectionFromUiLanguage()),t.has("barge_in")&&this.__postUpdateQueue.push((()=>this._applyBargeInPreference())),this.isInitialized()&&this._speakingAvatar?.sessionData&&(t.has("username")&&this.username!==this._speakingAvatar.sessionData.username&&(this._speakingAvatar.sessionData.username=this.username),t.has("phoneNumber")&&this.phoneNumber!==this._speakingAvatar.sessionData.phoneNumber&&(this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber),t.has("email")&&this.email!==this._speakingAvatar.sessionData.email&&(this._speakingAvatar.sessionData.email=this.email),t.has("isTermsAccepted")&&this.isTermsAccepted!==this._speakingAvatar.sessionData.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted)),t.has("api_key")||t.has("token_endpoint")||t.has("avatar_id")){const t=!(!this.api_key&&!this.token_endpoint||!this.avatar_id);t&&!this._initTriggered?(this._initTriggered=!0,this.__postUpdateQueue.push((()=>this._initialize()))):t||(this._initTriggered=!1,this.__postUpdateQueue.push((()=>this.updateAlertStatus("ErrorPage"))))}if((t.has("_showChatbot")||t.has("_shownPage"))&&(this.__postUpdateQueue.push((()=>{this._speakingAvatar?.chatSocket&&this._syncUiChatbotMode()})),t.has("_shownPage")&&this.__postUpdateQueue.push((()=>this._speakingAvatar?.avatarOrchestrator?.sendEvent("PAGE_CHANGED",{newPage:this._shownPage}))),t.has("_showChatbot")&&this.__postUpdateQueue.push((()=>{if(!("mobile"===this.target_app||this.toggler&&window.innerWidth<768))try{this.style.removeProperty("--chatbot-dynamic-height")}catch(t){}requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>{try{this._speakingAvatar?.avatarModule?.onResize?.()}catch(t){}}))}))}))),this.toggler&&t.has("_showChatbot")&&this._showChatbot&&!this._isConversationInProgress&&!this._isAutoResuming&&!this._isResumeExpired&&this._startOrResumeConversation(!0),t.has("_shownPage")&&("ChatPage"===this._shownPage?(this._scheduleInputFocus("chat"),this._scheduleChatScroll(),setTimeout((()=>this._scheduleChatScroll()),80)):"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing")),t.has("_showTyping")&&"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing"),t.has("_inputsBlocked")&&!this._inputsBlocked&&!0===t.get("_inputsBlocked")&&this._scheduleInputFocus(),t.has("canvasWidth")||t.has("canvasHeight")||t.has("chatbotHeight")){const t=()=>this.updateSize();this.__postUpdateQueue.push((()=>requestAnimationFrame(t)))}if(this.__postUpdateQueue.length){const t=this.__postUpdateQueue.splice(0);Promise.resolve().then((()=>{for(const i of t)try{i()}catch(e){}}))}if(t.has("_showChatConsentDialog")&&(this._showChatConsentDialog?this._activateConsentFocusTrap():this._deactivateConsentFocusTrap()),t.has("cornerRadius"))try{const t=this.cornerRadius;if(null==t||""===t)this.style.removeProperty("--corner-radius");else{const e=String(t).trim(),i=/^-?\d+(?:\.\d+)?$/.test(e)?`${e}px`:e;this.style.setProperty("--corner-radius",i)}}catch(e){}}render(){return k`
2103
2265
  <div id="chatbot-container" class="${(t=this)._showChatbot||!t.toggler?"show-chatbot":""}${t.toggler?"":" embedded"}">
2104
2266
  ${t.toggler?(t=>k`
2105
2267
  <button id="chatbot-toggler" @click="${t._handleToggleChatbot}" aria-label="${t._t("toggleChatbot")}">
2106
- ${ee}
2107
- ${le}
2268
+ ${oe}
2269
+ ${ue}
2108
2270
  </button>
2109
- `)(t):w}
2110
- ${t._stateTestMode?(t=>{const e=t._actorSnapshot,i="function"==typeof t.initStatus?t.initStatus():"UNKNOWN",a=!!t._isStartingConversation,n=!!t._isInitializingConversation,s=!!t._isConversationInProgress,o=!!t._isConversationPaused,r=!!t._isConversationResumable,c=!!t._isConversationStopped,h=!!t._isFailed,l=h?"FAILED":a?"STARTING":n?"INITIALIZING":s?"IN_PROGRESS":o?"PAUSED":r?"RESUMABLE":c?"STOPPED":"CLEARED",d=!!t._isSpeaking,u=!!t._isThinking||!!t._isStartingConversation,p=s&&!d&&!u&&!t._isListening,m=!!t._isListening,g=d?"speaking":u?"thinking":m?"listening":p?"idle":a?"startingConversation":"",y=!!t._inputsBlocked||u,v=t._speakingAvatar?.connectionManager,f=!0===v?.allConnectionsReady,b=!!t._isDisconnected,_=f?"connected":b?"disconnected":h?"recovering":"connecting",x=function(t){const e=t?.value;if(!e)return"";const i=(t,e=[])=>{if("string"==typeof t)return[e.concat(t).join(".")];if(t&&"object"==typeof t){const a=[];for(const n of Object.keys(t))a.push(...i(t[n],e.concat(n)));return a}return[]};try{return i(e).join(" | ")}catch(a){try{return JSON.stringify(e)}catch{return String(e)}}}(e),S=!t.toggler||t._showChatbot,A="AvatarPage"===t._shownPage?"AVATAR":"CHAT",C=e?.context?.chatSocket?.chatbotMode||"unknown";return k`
2271
+ `)(t):S}
2272
+ ${t._stateTestMode?(t=>{const e=t._actorSnapshot,i="function"==typeof t.initStatus?t.initStatus():"UNKNOWN",a=!!t._isStartingConversation,n=!!t._isInitializingConversation,s=!!t._isConversationInProgress,o=!!t._isConversationPaused,r=!!t._isConversationResumable,c=!!t._isConversationStopped,h=!!t._isFailed,l=h?"FAILED":a?"STARTING":n?"INITIALIZING":s?"IN_PROGRESS":o?"PAUSED":r?"RESUMABLE":c?"STOPPED":"CLEARED",d=!!t._isSpeaking,u=!!t._isThinking||!!t._isStartingConversation,p=s&&!d&&!u&&!t._isListening,m=!!t._isListening,g=d?"speaking":u?"thinking":m?"listening":p?"idle":a?"startingConversation":"",y=!!t._inputsBlocked||u,v=t._speakingAvatar?.connectionManager,f=!0===v?.allConnectionsReady,b=!!t._isDisconnected,_=f?"connected":b?"disconnected":h?"recovering":"connecting",x=function(t){const e=t?.value;if(!e)return"";const i=(t,e=[])=>{if("string"==typeof t)return[e.concat(t).join(".")];if(t&&"object"==typeof t){const a=[];for(const n of Object.keys(t))a.push(...i(t[n],e.concat(n)));return a}return[]};try{return i(e).join(" | ")}catch(a){try{return JSON.stringify(e)}catch{return String(e)}}}(e),w=!t.toggler||t._showChatbot,A="AvatarPage"===t._shownPage?"AVATAR":"CHAT",C=e?.context?.chatSocket?.chatbotMode||"unknown";return k`
2111
2273
  <div class="test-mode-states">
2112
2274
  <div><b>FSM</b>: ${x||"(no state)"}</div>
2113
- <div><b>UI</b>: Chatbot Visible=${String(S)}, Mode (UI → FSM)=${A} → ${C}</div>
2275
+ <div><b>UI</b>: Chatbot Visible=${String(w)}, Mode (UI → FSM)=${A} → ${C}</div>
2114
2276
  <div>Initialization: ${i}</div>
2115
2277
  <div>Conversation: ${l}</div>
2116
2278
  <div>Substate: ${g}</div>
@@ -2130,12 +2292,12 @@ z"/>
2130
2292
  <button @click="${()=>t._testSetSpeechConnected("disconnected")}">Disconnect Speech</button>
2131
2293
  <button @click="${()=>t._testSetSpeechConnected("failed")}">Fail Speech</button>
2132
2294
  <button @click="${()=>t._testSetSpeechConnected()}">Connect Speech</button>
2133
- ${v?.reconnectFailedModules?k`<button @click="${()=>v.reconnectFailedModules(!0)}">Reconnect Failed</button>`:w}
2134
- ${v?.reconnectDisconnectedModules?k`<button @click="${()=>v.reconnectDisconnectedModules()}">Reconnect All</button>`:w}
2295
+ ${v?.reconnectFailedModules?k`<button @click="${()=>v.reconnectFailedModules(!0)}">Reconnect Failed</button>`:S}
2296
+ ${v?.reconnectDisconnectedModules?k`<button @click="${()=>v.reconnectDisconnectedModules()}">Reconnect All</button>`:S}
2135
2297
  </div>
2136
2298
  </div>
2137
- `})(t):w}
2138
- ${(()=>w)()}
2299
+ `})(t):S}
2300
+ ${(()=>S)()}
2139
2301
  <div
2140
2302
  class="chatbot ${t.target_app} ${t.compact?"compact":""}"
2141
2303
  @click="${t._handleChatbotClick}"
@@ -2143,12 +2305,12 @@ z"/>
2143
2305
  ${t.toggler||"mobile"===t.target_app?`width: ${t._canvasWidth}px; height: ${"mobile"===t.target_app||t.toggler&&window.innerWidth<768?"calc(var(--chatbot-dynamic-height) - var(--chatbot-bottom-offset, 0px))":`${t._chatbotHeight}px`};`:`width: 100%; height: ${t._chatbotHeight}px;`}
2144
2306
  "
2145
2307
  >
2146
- ${t.compact?w:(t=>k`
2308
+ ${t.compact?S:(t=>k`
2147
2309
  <header @click="${t=>t.stopPropagation()}">
2148
2310
  <div class="header-container">
2149
2311
  <div class="header-left">
2150
2312
  <div class="menu-icon" @click="${t._handleToggleMenu}">
2151
- ${t._showMenu?le:de}
2313
+ ${t._showMenu?ue:pe}
2152
2314
  </div>
2153
2315
  ${(t=>{const e=t._isConversationInProgress,i=t._isStartingConversation||t._isInitializingConversation,a=t._isConversationStopped,n=t._isConversationResumable;return k`
2154
2316
  ${t._showMenu?k`<div class="menu-backdrop" @click="${t._handleToggleMenu}"></div>`:null}
@@ -2193,19 +2355,19 @@ z"/>
2193
2355
  </div>
2194
2356
  </div>
2195
2357
  </div>
2196
- `:w)(t)}
2358
+ `:S)(t)}
2197
2359
  </div>
2198
2360
  <div class="header-right">
2199
2361
  ${"mobile"!==t.target_app&&t.toggler?k`
2200
2362
  <div @click="${t._closeChatbot}" class="close-icon" title="${t._t("close")}">
2201
- ${le}
2363
+ ${ue}
2202
2364
  </div>
2203
- `:w}
2365
+ `:S}
2204
2366
  ${t.brand_logo?k`
2205
2367
  <div>
2206
2368
  <img src="${t.brand_logo}" class="logo-image">
2207
2369
  </div>
2208
- `:w}
2370
+ `:S}
2209
2371
  </div>
2210
2372
  </div>
2211
2373
  </header>
@@ -2214,11 +2376,11 @@ z"/>
2214
2376
  <div
2215
2377
  class="chatbot-body ${"ChatPage"===t._shownPage?"chat-mode":""} ${t.target_app} ${t.compact?"compact":""}"
2216
2378
  >
2217
- ${(t=>{const e=t._statusBarStatus;if(!e||"connected"===e)return w;const i={initializing:t._t("statusInitializing"),disconnected:t._t("statusReconnecting"),recovering:t._t("statusReconnecting"),failed:t._t("statusFailed"),invalidConfiguration:t._t("statusInvalidConfiguration")}[e]||"";return i?k`
2379
+ ${(t=>{const e=t._statusBarStatus;if(!e||"connected"===e)return S;const i={initializing:t._t("statusInitializing"),disconnected:t._t("statusReconnecting"),recovering:t._t("statusReconnecting"),failed:t._t("statusFailed"),invalidConfiguration:t._t("statusInvalidConfiguration")}[e]||"";return i?k`
2218
2380
  <div class="status-bar status--${e}" role="status">
2219
2381
  ${i}
2220
2382
  </div>
2221
- `:w})(t)}
2383
+ `:S})(t)}
2222
2384
  <div id="toastify-dismissable-alerts"></div>
2223
2385
  ${(t=>"LoaderPage"===t._shownPage?k`
2224
2386
  <div class="page-wrapper" id="loader_page">
@@ -2226,9 +2388,9 @@ z"/>
2226
2388
  <div class="lds-dual-ring"></div>
2227
2389
  </div>
2228
2390
  </div>
2229
- `:w)(t)}
2230
- ${ve(t)}
2231
- ${t.compact?w:(t=>{let e,i="";const a=t._isStartingConversation,n=t._isInitializingConversation,s=t._isConversationInProgress,o=t._isConversationPaused,r=t._isConversationResumable;return a||n?(e=k`
2391
+ `:S)(t)}
2392
+ ${_e(t)}
2393
+ ${t.compact?S:(t=>{let e,i="";const a=t._isStartingConversation,n=t._isInitializingConversation,s=t._isConversationInProgress,o=t._isConversationPaused,r=t._isConversationResumable;return a||n?(e=k`
2232
2394
  <div class="chat-start-container center-aligned">
2233
2395
  <div class="lds-dual-ring small"></div>
2234
2396
  </div>`,i="center-aligned"):r?(e=k`
@@ -2236,9 +2398,9 @@ z"/>
2236
2398
  <small>${t._t("previousConversationFound")}</small>
2237
2399
  </div>`,i="center-aligned"):s||o?e=k`
2238
2400
  <ul class="chatbox">
2239
- ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:a})=>{const n=Zt(i)?"rtl":"ltr";return k`
2401
+ ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:a})=>{const n=te(i)?"rtl":"ltr";return k`
2240
2402
  <li class="chat ${e}">
2241
- ${"assistant"===e?he:""}
2403
+ ${"assistant"===e?de:""}
2242
2404
  <div style="direction: ${n}; text-align: ${"rtl"===n?"right":"left"}" class="message-container">
2243
2405
  <p class="message-bubble" style="word-wrap: break-word; word-break: break-word;">${i}</p>
2244
2406
  <small class="message-time ${"rtl"===n?"time-left":"time-right"}">${a}</small>
@@ -2254,7 +2416,7 @@ z"/>
2254
2416
  <div class="dot"></div>
2255
2417
  <div class="dot"></div>
2256
2418
  </div>
2257
- `:w}
2419
+ `:S}
2258
2420
  <textarea
2259
2421
  @keyup="${t._handleChatKeyUp}"
2260
2422
  type="text"
@@ -2267,14 +2429,23 @@ z"/>
2267
2429
  id="chat_send_button"
2268
2430
  class="${t._inputsBlocked?"send-button-disabled":""}"
2269
2431
  >
2270
- ${ce}
2432
+ ${le}
2271
2433
  </div>
2272
2434
  </div>
2273
2435
  `})(t)}
2274
2436
  `:(e=k`
2275
- <div class="chat-start-container center-aligned">
2276
- ${ge(t)}
2277
- </div>`,i="center-aligned"),k`
2437
+ <div class="chat-placeholder-container">
2438
+ <div class="chat-placeholder-content">
2439
+ <div class="chat-placeholder-icon">
2440
+ ${se}
2441
+ </div>
2442
+ <h3 class="chat-placeholder-title">${t._t("chatPlaceholderTitle")}</h3>
2443
+ <p class="chat-placeholder-description">${t._t("chatPlaceholderDescription")}</p>
2444
+ </div>
2445
+ <div class="chat-placeholder-button">
2446
+ ${ve(t)}
2447
+ </div>
2448
+ </div>`,i="placeholder-mode"),k`
2278
2449
  <div class="page-wrapper" id="chat-page" ?hidden=${"ChatPage"!==t._shownPage}>
2279
2450
  <div class="chat-wrapper ${i}">
2280
2451
  ${e}
@@ -2284,19 +2455,19 @@ z"/>
2284
2455
  ${(t=>"ErrorPage"===t._shownPage?k`
2285
2456
  <div class="page-wrapper" id="error_page">
2286
2457
  <div class="page-center">
2287
- ${ue}
2458
+ ${me}
2288
2459
  </div>
2289
2460
  </div>
2290
- `:w)(t)}
2461
+ `:S)(t)}
2291
2462
  ${(t=>"DisconnectedPage"===t._shownPage?k`
2292
2463
  <div class="page-wrapper" id="disconnected_page">
2293
2464
  <div class="page-center">
2294
- ${ye(t)}
2465
+ ${fe(t)}
2295
2466
  </div>
2296
2467
  </div>
2297
- `:w)(t)}
2468
+ `:S)(t)}
2298
2469
  </div>
2299
- ${"mobile"===t.target_app||t.compact?w:(t=>{const e=t.brand_name||"Sentifyd",i=!!t.brand_name;return k`
2470
+ ${"mobile"===t.target_app||t.compact?S:(t=>{const e=t.brand_name||"Sentifyd",i=!!t.brand_name;return k`
2300
2471
  <footer>
2301
2472
  ${i?k`<small>${e}</small>`:k`<small><a href="https://sentifyd.io" target="_blank">Sentifyd</a></small>`}
2302
2473
  </footer>
@@ -2304,15 +2475,15 @@ z"/>
2304
2475
  ${(t=>t._showLastMessage?k`
2305
2476
  <div class="last-message" @click="${t._closeLastMessage}">
2306
2477
  <div class="last-message-content">
2307
- <div style="direction: ${Zt(t._lastMessageText)?"rtl":"ltr"}" class="last-message-scrollable">
2478
+ <div style="direction: ${te(t._lastMessageText)?"rtl":"ltr"}" class="last-message-scrollable">
2308
2479
  ${t._lastMessageText}
2309
2480
  <button class="last-message-copy-button" @click="${e=>((t,e)=>{t.stopPropagation();const i=e._lastMessageText;i&&navigator.clipboard.writeText(i).then((()=>{e._showCopyTick=!0,setTimeout((()=>{e._showCopyTick=!1}),1500)})).catch((t=>{}))})(e,t)}">
2310
- ${t._showCopyTick?me:pe}
2481
+ ${t._showCopyTick?ye:ge}
2311
2482
  </button>
2312
2483
  </div>
2313
2484
  </div>
2314
2485
  </div>
2315
- `:w)(t)}
2486
+ `:S)(t)}
2316
2487
  ${(t=>t._showConfirmationDialog?k`
2317
2488
  <div class="dialog-overlay">
2318
2489
  <div class="dialog">
@@ -2324,7 +2495,7 @@ z"/>
2324
2495
  </div>
2325
2496
  </div>
2326
2497
  </div>
2327
- `:w)(t)}
2498
+ `:S)(t)}
2328
2499
  ${(t=>t._showUserData?k`
2329
2500
  <div class="dialog-overlay">
2330
2501
  <div class="dialog">
@@ -2335,21 +2506,21 @@ z"/>
2335
2506
  <input @input="${e=>t.username=e.target.value}" type="text" id="username" placeholder="${t._t("namePlaceholder")}" .value=${t.username} required>
2336
2507
  </div>
2337
2508
  <div class="form-group">
2338
- <label for="phoneNumber">${t._t("phoneNumber")}</label>
2339
- <input @input="${e=>t.phoneNumber=e.target.value}" type="tel" id="phoneNumber" placeholder="${t._t("phonePlaceholder")}" .value=${t.phoneNumber}>
2509
+ <label for="email">${t._t("email")}*</label>
2510
+ <input @input="${e=>t.email=e.target.value}" type="email" id="email" placeholder="${t._t("emailPlaceholder")}" .value=${t.email} required>
2340
2511
  </div>
2341
2512
  <div class="form-group">
2342
- <label for="email">${t._t("email")}</label>
2343
- <input @input="${e=>t.email=e.target.value}" type="email" id="email" placeholder="${t._t("emailPlaceholder")}" .value=${t.email}>
2513
+ <label for="phoneNumber">${t._t("phoneNumber")}</label>
2514
+ <input @input="${e=>t.phoneNumber=e.target.value}" type="tel" id="phoneNumber" placeholder="${t._t("phonePlaceholder")}" .value=${t.phoneNumber}>
2344
2515
  </div>
2345
- <div> <p>${t._t("secureFormNote")}</p></div>
2516
+ <div> <p style="font-size: 0.8em;">${t._t("secureFormNote")}</p></div>
2346
2517
  <div class="dialog-button-group" style="text-align: start;">
2347
- <button class="button-save" @click="${t._handleSaveClick}" type="button" ?disabled="${t._isUserPageSaved()}">${t._t("save")}</button>
2518
+ <button class="button-save" @click="${t._handleSaveClick}" type="button" ?disabled="${!t.username?.trim()||!t.email?.trim()}">${t._t("send")}</button>
2348
2519
  <button class="button-cancel" @click="${t._handleCancelClick}">${t._t("cancel")}</button>
2349
2520
  </div>
2350
2521
  </div>
2351
2522
  </div>
2352
- `:w)(t)}
2523
+ `:S)(t)}
2353
2524
  ${(t=>t._showSatisfactionScore?k`
2354
2525
  <div class="dialog-overlay">
2355
2526
  <div class="dialog">
@@ -2384,7 +2555,7 @@ z"/>
2384
2555
  </div>
2385
2556
  </div>
2386
2557
  </div>
2387
- `:w)(t)}
2558
+ `:S)(t)}
2388
2559
  ${(t=>t._showChatConsentDialog?k`
2389
2560
  <div class="dialog-overlay">
2390
2561
  <div class="dialog consent-dialog" role="dialog" aria-modal="true" aria-labelledby="chat-consent-title">
@@ -2406,7 +2577,7 @@ z"/>
2406
2577
  <button class="button-cancel" aria-label="${t._t("consentDeclineAria")}" @click="${t._handleConsentDecline}" type="button">${t._t("consentDecline")}</button>
2407
2578
  </div>
2408
2579
  </div>
2409
- </div>`:w)(t)}
2580
+ </div>`:S)(t)}
2410
2581
  </div>
2411
2582
  </div>
2412
- `;var t}_scheduleInputFocus(t=null){this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._focusTimeoutId=requestAnimationFrame((()=>{try{const e=t||this._getCurrentInputType();if(!e)return void(this._focusTimeoutId=null);const i="chat"===e?"#message_input":"#typed_input",a=this.shadowRoot.querySelector(i);a&&!a.disabled&&this._isElementFocusable(a)&&document.activeElement!==a&&a.focus()}catch(e){}finally{this._focusTimeoutId=null}}))}_getCurrentInputType(){return"ChatPage"===this._shownPage?"chat":"AvatarPage"===this._shownPage&&this._showTyping?"typing":null}_isElementFocusable(t){if(!t)return!1;if(null===t.offsetParent)return!1;if("none"===t.style.display||"hidden"===t.style.visibility)return!1;try{const e=window.getComputedStyle(t);return"none"!==e.display&&"hidden"!==e.visibility}catch(e){return!0}}async connectedCallback(){super.connectedCallback(),["visibilitychange","pagehide","freeze"].forEach((t=>{this._onDom(document,t,(t=>this._handleVisibilityChange(t)))})),this._onDom(window,"focus",(t=>this._handleVisibilityChange(t))),this._onDom(window,"pageshow",(t=>this._handleVisibilityChange(t))),this._handleVisibilityChange({type:"init"}),requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>this.updateSize()))})),this._onBus("event_command_UI_UpdateCurrentMessage",(t=>{this._currentMessage={speaker:t.speaker,messageText:t.messageText,time:(new Date).toLocaleTimeString("en-US",{hour12:!1})}})),this._onBus("event_command_UI_UpdateSTTCaption",(t=>{if(this.enable_captions){const e=(t=>{if(t.length<=40)return t;const e=t.length-40,i=t.indexOf(" ",e);return-1!==i?t.slice(i).trim():t.slice(0,e).trim()})(t.STTCaption);this._updateLiveCaption(!0,e,"user")}})),this._onBus("event_command_UI_PlayCaptions",(t=>{if(this.enable_captions){const e=this._speakingAvatar?.avatarModule?.liveCaptions;e&&e.playCaptions(((t,e="",i=!1)=>{this._updateLiveCaption(t,e,"assistant",i)}),t.audioStartTime)}})),this._onBus("event_command_UI_ClearCaptions",(()=>{this._updateLiveCaption(!1,"","")})),this._onBus("event_command_UI_ClearConversation",(()=>{document.hidden||this._idleSpeakingAvatar(),this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript]),this._updateLiveCaption(!1),this._currentMessage=null})),this._onBus("event_status_Conversation_MessageAppended",(t=>{try{this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript])}catch(e){}if("user"===t?.speaker){this._userCaptionClearTimeoutId&&clearTimeout(this._userCaptionClearTimeoutId);const t=E?.captions?.captionTimeout;this._userCaptionClearTimeoutId=setTimeout((()=>{try{"user"===this._liveCaptionSpeaker&&this._updateLiveCaption(!1,"","")}finally{this._userCaptionClearTimeoutId=null}}),t)}this._scheduleChatScroll(),setTimeout((()=>this._scheduleChatScroll()),80)})),this._onBus("event_status_Conversation_Found_Initialized",(()=>{this.toggler&&!1===this._showChatbot||this._showResumeConversationDialog()})),this._onBus("event_status_Conversation_TimedOut",(t=>{this.showConfirmationDialog(this._t("conversationExpiredPrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),(()=>{this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),this._t("downloadAndClear"),this._t("onlyClear"))})),this._onBus("event_command_UI_RequestUserData",(()=>{"mobile"===this.target_app?this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("enterInfoOnMobile"),className:"alert-warning"}):this._showUserData=!0})),this._onBus("event_command_UI_EnableCaptions",(()=>{this.enable_captions=!0})),this._onBus("event_command_UI_DisableCaptions",(()=>{this.enable_captions=!1})),this._onBus("event_status_Avatar_RenderingStateChanged",(t=>{const e=!!t?.running;this._avatarRunning!==e&&(this._avatarRunning=e)})),this._onBus("event_command_UI_SwitchToChatMode",(()=>{"ChatPage"!==this._shownPage?this._shownPage="ChatPage":this._syncUiChatbotMode()})),this._onBus("event_command_UI_SwitchToAvatarMode",(()=>{"AvatarPage"!==this._shownPage?this._shownPage="AvatarPage":this._syncUiChatbotMode();try{this._startListening()}catch(t){}})),this._onBus("event_command_UI_EndConversation",(()=>{this._endConversation()})),this._onDom(window,"resize",this.handleWindowResize.bind(this));try{const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null;t&&(this._onDom(t,"resize",this.handleWindowResize.bind(this)),this._onDom(t,"scroll",this.handleWindowResize.bind(this)))}catch(e){}this.resizeObserver=new ResizeObserver((t=>{if(!t||!t.length)return;const i=t[0],{width:a,height:n}=i.contentRect||{};if((!this.toggler||!1!==this._showChatbot)&&a>120&&n>120&&(E.dom.canvasWidth=Math.round(a),E.dom.canvasHeight=Math.round(n),this._speakingAvatar&&this._speakingAvatar.avatarModule))try{this._speakingAvatar.avatarModule.onResize()}catch(e){}}));const t=this.renderRoot.querySelector("#avatar-container");t&&this.resizeObserver.observe(t);try{this.hostResizeObserver=new ResizeObserver((()=>{requestAnimationFrame((()=>this.updateSize()))})),this.hostResizeObserver.observe(this)}catch(e){}}disconnectedCallback(){if(super.disconnectedCallback(),this._disposeListeners(),this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._speakingAvatar?.destroy?.(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.hostResizeObserver){try{this.hostResizeObserver.disconnect()}catch(t){}this.hostResizeObserver=null}}updateSize(){const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null,e=t?Math.round(t.width):window.innerWidth,i=t?Math.round(t.height):window.innerHeight,a=t?Math.round(t.offsetTop):0,n=e<E.dom.smallDisplayWidth;let s,o;const r=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:null},c=r(this.canvasWidth),h=r(this.canvasHeight),l=r(this.chatbotHeight),d=(this.compact?0:E.dom.headerAndFooterHeight)+E.dom.controlsHeight;if("mobile"===this.target_app){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else if(this.toggler)if(n){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else{const t=Math.max(120,c??(E.dom.canvasWidth||400)),e=Math.max(120,h??(E.dom.canvasHeight||500));s=t,o=Math.max(120,l??e+d)}else{const t=this.getBoundingClientRect?.()||{},a=Math.round(t.width||this.offsetWidth||this.clientWidth||e),n=Math.round(t.height||this.offsetHeight||this.clientHeight||i),r=Math.max(120,c??a),u=Math.max(120,h??(E.dom.canvasHeight||n));s=r;const p=n>=120?n:u+d;o=Math.max(120,l??(h?u+d:p))}this._canvasWidth===s&&this._chatbotHeight===o||(this._canvasWidth=s,this._chatbotHeight=o)}async _initialize(){if(this._initInProgress)return this._initPromise;this._initInProgress=!0,this._initPromise=(async()=>{if(""===this.api_key&&""===this.token_endpoint||""===this.avatar_id)this.updateAlertStatus("ErrorPage");else{this.updateAlertStatus("LoaderPage");try{this._showChatbot="true"===await at.getItem("showChatbot_"+this.avatar_id),await this.updateComplete,await this._initializeSpeakingAvatar()}catch(t){this.updateAlertStatus("DisconnectedPage")}}})();try{await this._initPromise}finally{this._initInProgress=!1,this._initPromise=null}}async _initializeSpeakingAvatar(){const t={avatarAPIKey:this.api_key,avatarId:this.avatar_id,avatarContainer:this.renderRoot.querySelector("#avatar-container"),tokenEndpoint:this.token_endpoint,targetApp:this.target_app};this._wakeLock.request();try{if(!(await this._speakingAvatar.init(t)))throw new Error("Initialization failed");this._avatarName=this._speakingAvatar.sessionData.avatarName,this._language=this._speakingAvatar.sessionData.language,this.username=this._speakingAvatar.sessionData.username,this.phoneNumber=this._speakingAvatar.sessionData.phoneNumber,this.email=this._speakingAvatar.sessionData.email,!0===this.isTermsAccepted?this._speakingAvatar.sessionData.isTermsAccepted=!0:this.isTermsAccepted=this._speakingAvatar.sessionData.isTermsAccepted,this._isFullBody=this._speakingAvatar?.avatarModule?.isFullBody,this._setupAvatarStateSubscription();const e=null!==this._speakingAvatar?.sessionData?.trainingId;e&&(this._initConversation(),this._syncUiChatbotMode()),this._shownPage=e?"AvatarPage":"ErrorPage",this.compact&&e&&(this._shownPage="AvatarPage")}catch(e){throw e}}handleWindowResize(){this.updateSize()}_handleVisibilityChange(t){let e=!0;try{const i="string"==typeof t?t:t?.type;e=!(document.hidden||"hidden"===document.visibilityState),"pagehide"!==i&&"freeze"!==i||(e=!1),"pageshow"!==i&&"focus"!==i||(e=!0)}catch(a){e=!0}const i=this._speakingAvatar?.avatarOrchestrator;i&&"function"==typeof i.sendEvent?i.sendEvent("VISIBILITY_CHANGED",{isVisible:e}):e?this._resumeAfterForeground():this._pauseAvatarForBackground()}_pauseAvatarForBackground(){this._speakingAvatar?.avatarOrchestrator?(this._speakingAvatar.avatarOrchestrator.is("speaking")&&this._speakingAvatar.avatarOrchestrator.sendEvent("INTERRUPT"),this._speakingAvatar.avatarOrchestrator.is("listening")&&this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"),this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._idleSpeakingAvatar(),this._wakeLock.release()):this._wakeLock.release()}_resumeAfterForeground(){}_idleSpeakingAvatar(){this._speakingAvatar&&this._speakingAvatar.avatarOrchestrator&&(this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"))}_startListening(){this._inputsBlocked||this._isConversationInProgress&&this._speakingAvatar?.avatarOrchestrator?.is("idle")&&this._speakingAvatar.avatarOrchestrator.sendEvent("LISTEN")}_initConversation(){this.isInitialized()&&this._speakingAvatar.avatarOrchestrator.sendEvent("INIT_CONVERSATION")}_startOrResumeConversation(t=!1){Promise.resolve(this._hasChatConsent()).then((e=>{e?this._proceedStartConversation(t):this._showChatConsentDialog=!0})).catch((()=>{this._showChatConsentDialog=!0}))}_proceedStartConversation(t){try{const t=!(document.hidden||"hidden"===document.visibilityState);this._speakingAvatar?.avatarOrchestrator?.sendEvent("VISIBILITY_CHANGED",{isVisible:t})}catch(e){}this._speakingAvatar?.sessionData&&!0===this.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=!0),this._speakingAvatar.avatarOrchestrator.sendEvent("START_CONVERSATION",{fresh:t,termsAccepted:!0===this.isTermsAccepted})}_showResumeConversationDialog(){this.showConfirmationDialog(this._t("resumeConversationPrompt"),(()=>{this._startOrResumeConversation(!1)}),(()=>{this._endConversation(!1)}),this._t("resume"),this._t("end"))}_endConversation(t=!0){t?this._showSatisfactionScore=!0:this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0})}_updateLiveCaption(t,e="",i="",a=!1,n=!1){const s=E?.captions??{},o=s.captionChangeDelay??200,r=s.captionTimeout??1500,c=this._liveCaptionSpeaker;t&&"user"===i&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),n?(this._isLiveCaptionsVisible=!1,setTimeout((()=>{this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i}),o)):(this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i),t||"user"===(i||c)&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),a&&(this.captionsTimeoutId=setTimeout((()=>{this._isLiveCaptionsVisible=!1,this._liveCaption="",this._liveCaptionSpeaker="",this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this.captionsTimeoutId=null}),r))}updateAlertStatus(t=null){const e=this._actorSnapshot;e?.context;const i=!(!this.api_key&&!this.token_endpoint||!this.avatar_id),a=this._speakingAvatar?.sessionData&&null===this._speakingAvatar.sessionData.trainingId;let n=null;n=i?e?.matches?.("lifecycle.init.initializing")?"initializing":e?.matches?.("lifecycle.init.failed")?"failed":a?"invalidConfiguration":e?.matches?.("connection.connected")?"connected":"recovering":"invalidConfiguration","initializing"!==n||"connected"!==this._statusBarStatus&&"recovering"!==this._statusBarStatus||(n=this._statusBarStatus),this._statusBarStatus!==n&&(this._statusBarStatus=n),null!==t&&this._shownPage!==t&&(this._shownPage=t)}get initStatusValue(){return this.initStatus()}initStatus(){const t=this._actorSnapshot;if(!t)return"INITIALIZING";if(!this.api_key&&!this.token_endpoint||!this.avatar_id)return"INVALID";if(t.matches?.("lifecycle.init.failed"))return"FAILED";if(t.context?.initFailed&&t.matches?.("lifecycle.init.initializing"))return"FAILED";if(t.matches?.("lifecycle.init.initializing"))return"INITIALIZING";const e=this._speakingAvatar?.sessionData;return e&&e.avatarId&&null===e.trainingId?"INVALID":"COMPLETED"}isInitialized(){return"COMPLETED"===this.initStatus()}isInitializing(){return"INITIALIZING"===this.initStatus()}_handleToggleChatbot(){this._showChatbot||this._isConversationInProgress||this._isInitializingConversation?this._updateChatbotVisibility(!this._showChatbot):(this._updateChatbotVisibility(!0),this.isInitialized()&&this._startOrResumeConversation())}_updateChatbotVisibility(t){this._showChatbot=t,at.setItem("showChatbot_"+this.avatar_id,String(t))}_openLastMessage(t){this._lastMessageText=this._currentMessage.messageText,this._showLastMessage=!0}_closeLastMessage(){this._showLastMessage=!1}_showMenuOnHover(){window.matchMedia("(hover: hover)").matches&&(this._showMenu=!0,this.shadowRoot.getElementById("menu").classList.remove("hidden"))}_handleChatbotClick(){if(!this.compact){const t=this.shadowRoot.getElementById("menu");t?.classList.add("hide"),setTimeout((()=>{t?.classList.contains("hide")&&(this._showMenu=!1)}),500)}}_closeChatbot(){this._updateChatbotVisibility(!1)}_handleToggleMenu(){this._showMenu=!this._showMenu}_handleMicBtn(){const t=this._speakingAvatar?.avatarOrchestrator;t&&(this._isConversationInProgress||this._isStartingConversation)?t.sendEvent("MIC_BUTTON"):this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("startConversationReminder")})}_handleShowChatPage(){if(this.isInitialized()){if(this.compact)return;this._shownPage="ChatPage",this._showMenu=!1}}_handleShowAvatarPage(){this.isInitialized()&&(this._shownPage="AvatarPage",this._startListening(),this._showMenu=!1)}_handleShowUserData(t){t.preventDefault(),this._showUserData=!0,this._showMenu=!1}_handleEndConversationBtn(){this.showConfirmationDialog(this._t("endConversationPrompt"),(()=>{this._endConversation()}),(()=>{}),this._t("end"),this._t("cancel")),this._showMenu=!1}_handleStartConversationMenuBtn(t){t.preventDefault(),t.stopPropagation(),this._shouldConfirmRestart()?this._handleRestartConversation():(this._startOrResumeConversation(),this._showMenu=!1)}_handleStartConversationBtn(t){t.preventDefault(),this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation()}_handleRestartConversation(){this.showConfirmationDialog(this._t("restartConversationPrompt"),(()=>{this._idleSpeakingAvatar(),this._startOrResumeConversation(!0)}),(()=>{}),this._t("newConversation"),this._t("cancel"))}_consentStorageKey(){return`chatConsent_${this.avatar_id||"unknown"}`}async _hasChatConsent(){if(!0===this.isTermsAccepted)return!0;try{return"accepted"===await at.getItem(this._consentStorageKey())}catch(t){return!1}}async _handleConsentAccept(){try{await at.setItem(this._consentStorageKey(),"accepted")}catch(t){}this._showChatConsentDialog=!1;try{this.isTermsAccepted=!0,this._speakingAvatar?.sessionData&&(this._speakingAvatar.sessionData.isTermsAccepted=!0)}catch(t){}this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}async _handleConsentDecline(){try{await at.setItem(this._consentStorageKey(),"declined")}catch(t){}this._showChatConsentDialog=!1}_activateConsentFocusTrap(){requestAnimationFrame((()=>{try{this.shadowRoot?.querySelector(".dialog .button-save")?.focus()}catch(t){}}));const t=t=>{if(this._showChatConsentDialog&&("Escape"===t.key&&(this._showChatConsentDialog=!1,t.stopPropagation()),"Tab"===t.key)){const e=Array.from(this.shadowRoot.querySelectorAll(".dialog button"));if(!e.length)return;const i=e.indexOf(document.activeElement);t.preventDefault(),(t.shiftKey?i<=0?e[e.length-1]:e[i-1]:i===e.length-1?e[0]:e[i+1]).focus()}};this._consentKeyHandler=t,this.addEventListener("keydown",t)}_deactivateConsentFocusTrap(){this._consentKeyHandler&&(this.removeEventListener("keydown",this._consentKeyHandler),this._consentKeyHandler=null)}_canDownloadTranscript(){return this._conversationTranscript.length>0}_handleDownloadTranscriptMenuBtn(t){t.preventDefault(),this._callDownloadTranscript(),this._showMenu=!1}_callDownloadTranscript(){((t,e,i,a)=>{const n=(new Date).toLocaleString().replace(/[/:, ]/g,"-");let s=`\nConversation Transcript\n\nDate: ${(new Date).toLocaleString()}\nAssistant: ${e}\nUser: ${i||"User"}\nFormat: Speaker: message [time]\n${t?`(Powered by ${t})`:""}\n\n\n_____________________________________\n\n`;a.forEach((t=>{const{speaker:a,messageText:n,time:o}=t;s+=`${"user"===a?i||"User":"assistant"===a?e:null}: ${n} [${o}]\n\n`}));const o=new Blob([s],{type:"text/plain;charset=utf-8"}),r=document.createElement("a");r.href=URL.createObjectURL(o),r.download=`transcript-${e}-${n}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r)})(this.brand_name,this._speakingAvatar.sessionData.avatarName,this._speakingAvatar.sessionData.username,this._conversationTranscript)}async _handleSaveClick(){this._speakingAvatar.sessionData.username=this.username,this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber,this._speakingAvatar.sessionData.email=this.email,this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted,this._speakingAvatar?.chatSocket?.sendUserData(),this._showUserData=!1}_handleCancelClick(){this._showUserData=!1}_isUserPageSaved(){return this._speakingAvatar.sessionData.username===this.username&&this._speakingAvatar.sessionData.phoneNumber===this.phoneNumber&&this._speakingAvatar.sessionData.email===this.email&&this._speakingAvatar.sessionData.isTermsAccepted===this.isTermsAccepted}_handleChatKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTextMessage())}_handleSendTextMessage(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#message_input"),e=t.value;e&&""!==e.trim()&&(t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e}))}_handleTypingKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTypedInput())}_handleSendTypedInput(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#typed_input"),e=t.value;e&&""!==e.trim()&&(t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e,chatbotMode:"AVATAR"}))}showConfirmationDialog(t,e,i,a,n){this._dialogMessage=t,this._confirmDialog=e,this._cancelDialog=i,this._confirmButtonLabel=a??this._t("confirm"),this._cancelButtonLabel=n??this._t("cancel"),this._showConfirmationDialog=!0}_handleConfirm(){this._confirmDialog&&this._confirmDialog(),this._resetDialog()}_handleCancel(){this._cancelDialog&&this._cancelDialog(),this._resetDialog()}_resetDialog(){this._showConfirmationDialog=!1,this._confirmDialog=()=>{},this._cancelDialog=()=>{},this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_handleToggleCaptionsSwitch(t){this.enable_captions=t.target.checked}_handleVisemeButtonClick(t){this.bus.emit("event_command_visemeButtonClick",{visemeId:t.target.getAttribute("data-viseme-id")})}_handleFacialButtonClick(t){this.bus.emit("event_command_facialButtonClick",{facialId:t.target.getAttribute("data-facial-id")})}_handleConnectBtn(){"COMPLETED"!==this.initStatus()?this._initialize():this.bus.emit("event_command_ConnectionManager_ReconnectFailedModules")}_handleUpperBodyIcon(){this._speakingAvatar?.avatarModule?.setView("upper")}_handleFullBodyIcon(){this._speakingAvatar?.avatarModule?.setView("full")}_handleMidBodyIcon(){this._speakingAvatar?.avatarModule?.setView("mid")}_handleHeadBodyIcon(){this._speakingAvatar?.avatarModule?.setView("head")}_handleSubmitScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:this._satisfactionScore}),this._showSatisfactionScore=!1}_handleCancelScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0}),this._showSatisfactionScore=!1}_scheduleChatScroll(){try{if("ChatPage"!==this._shownPage)return;requestAnimationFrame((()=>{try{const t=this.shadowRoot?.querySelector(".chatbox");t&&(t.scrollTop=t.scrollHeight)}catch(t){}}))}catch(t){}}_syncUiChatbotMode(){if(!this._speakingAvatar?.avatarOrchestrator||!this._speakingAvatar?.chatSocket)return;const t={isShown:!this.toggler||this._showChatbot,chatbotMode:"AvatarPage"===this._shownPage?"AVATAR":"CHAT"};t.isShown===this._lastUiChatbotMode.isShown&&t.chatbotMode===this._lastUiChatbotMode.chatbotMode||(this._speakingAvatar.avatarOrchestrator.sendEvent("UI_CHATBOT_MODE",t),this._lastUiChatbotMode=t)}_handleToggleTyping(){this._showTyping=!this._showTyping}_testSetAuthConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.authentication.updateConnectionState(t)}_testSetSocketConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.chatSocket.updateConnectionState(t)}_testSetSpeechConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules["speech-token"].updateConnectionState(t)}_shouldConfirmRestart(){return!!(this._isConversationInProgress||this._isConversationPaused||this._isConversationResumable||this._isConversationTimedOut||this._isInitializingConversation)}}const Ie="undefined"!=typeof window&&void 0!==window.sessionStorage,Ee={getItem:t=>Promise.resolve(Ie?window.sessionStorage.getItem(t):null),setItem:(t,e)=>Promise.resolve(Ie?window.sessionStorage.setItem(t,e):void 0),removeItem:t=>Promise.resolve(Ie?window.sessionStorage.removeItem(t):void 0)};function Pe(t){at.setInstance(t)}function De(){"undefined"!=typeof window&&void 0!==window.customElements&&(customElements.get("sentifyd-bot")||customElements.define("sentifyd-bot",Me))}function He(t){if(De(),t.containerId&&document.querySelector(`#${t.containerId} sentifyd-bot`))return document.querySelector(`#${t.containerId} sentifyd-bot`);let e=document.body;if(t.containerId){const i=document.getElementById(t.containerId);i&&(e=i)}const i=document.createElement("sentifyd-bot");return Object.keys(t).forEach((e=>{if("containerId"===e||"customAttributes"===e)return;const a=t[e];if(null!=a&&""!==a){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();i.setAttribute(t,"boolean"==typeof a?String(a):a)}})),t.customAttributes&&Object.keys(t.customAttributes).forEach((e=>{const a=t.customAttributes[e];null!=a&&""!==a&&i.setAttribute(e,String(a))})),e.appendChild(i),i}at.setInstance(Ee),"undefined"!=typeof window&&De();export{Me as SentifydBot,He as createSentifydBot,Pe as initializeStorage,De as registerSentifydBot};
2583
+ `;var t}_scheduleInputFocus(t=null){this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._focusTimeoutId=requestAnimationFrame((()=>{try{const e=t||this._getCurrentInputType();if(!e)return void(this._focusTimeoutId=null);const i="chat"===e?"#message_input":"#typed_input",a=this.shadowRoot.querySelector(i);a&&!a.disabled&&this._isElementFocusable(a)&&document.activeElement!==a&&a.focus()}catch(e){}finally{this._focusTimeoutId=null}}))}_getCurrentInputType(){return"ChatPage"===this._shownPage?"chat":"AvatarPage"===this._shownPage&&this._showTyping?"typing":null}_isElementFocusable(t){if(!t)return!1;if(null===t.offsetParent)return!1;if("none"===t.style.display||"hidden"===t.style.visibility)return!1;try{const e=window.getComputedStyle(t);return"none"!==e.display&&"hidden"!==e.visibility}catch(e){return!0}}async connectedCallback(){super.connectedCallback(),["visibilitychange","pagehide","freeze"].forEach((t=>{this._onDom(document,t,(t=>this._handleVisibilityChange(t)))})),this._onDom(window,"focus",(t=>this._handleVisibilityChange(t))),this._onDom(window,"pageshow",(t=>this._handleVisibilityChange(t))),this._handleVisibilityChange({type:"init"}),requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>this.updateSize()))})),this._onBus("event_command_UI_UpdateCurrentMessage",(t=>{this._currentMessage={speaker:t.speaker,messageText:t.messageText,time:(new Date).toLocaleTimeString("en-US",{hour12:!1})}})),this._onBus("event_command_UI_UpdateSTTCaption",(t=>{if(this.enable_captions){const e=(t=>{if(t.length<=40)return t;const e=t.length-40,i=t.indexOf(" ",e);return-1!==i?t.slice(i).trim():t.slice(0,e).trim()})(t.STTCaption);this._updateLiveCaption(!0,e,"user")}})),this._onBus("event_command_UI_PlayCaptions",(t=>{if(this.enable_captions){const e=this._speakingAvatar?.avatarModule?.liveCaptions;e&&e.playCaptions(((t,e="",i=!1)=>{this._updateLiveCaption(t,e,"assistant",i)}),t.audioStartTime)}})),this._onBus("event_command_UI_ClearCaptions",(()=>{this._updateLiveCaption(!1,"","")})),this._onBus("event_command_UI_ClearConversation",(()=>{document.hidden||this._idleSpeakingAvatar(),this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript]),this._updateLiveCaption(!1),this._currentMessage=null})),this._onBus("event_status_Conversation_MessageAppended",(t=>{try{this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript])}catch(e){}if("user"===t?.speaker){this._userCaptionClearTimeoutId&&clearTimeout(this._userCaptionClearTimeoutId);const t=E?.captions?.captionTimeout;this._userCaptionClearTimeoutId=setTimeout((()=>{try{"user"===this._liveCaptionSpeaker&&this._updateLiveCaption(!1,"","")}finally{this._userCaptionClearTimeoutId=null}}),t)}this._scheduleChatScroll(),setTimeout((()=>this._scheduleChatScroll()),80)})),this._onBus("event_status_Conversation_TimedOut",(t=>{this.showConfirmationDialog(this._t("conversationExpiredPrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),(()=>{this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),this._t("downloadAndClear"),this._t("onlyClear"))})),this._onBus("event_status_Conversation_ResumedSuccessfully",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}})),this._onBus("event_status_Conversation_ResumeFailedAndRestarted",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("resumeConversationFailedNewStarted"),className:"alert-warning"})})),this._onBus("event_status_Conversation_ResumeExpired",(()=>{this.showConfirmationDialog(this._t("conversationExpiredResumePrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar.avatarOrchestrator.sendEvent("DISMISS")}),(()=>{this._speakingAvatar.avatarOrchestrator.sendEvent("DISMISS")}),this._t("download"),this._t("ok"))})),this._onBus("event_command_UI_RequestUserData",(()=>{"mobile"===this.target_app?this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("enterInfoOnMobile"),className:"alert-warning"}):this._showUserData=!0})),this._onBus("event_command_UI_EnableCaptions",(()=>{this.enable_captions=!0})),this._onBus("event_command_UI_DisableCaptions",(()=>{this.enable_captions=!1})),this._onBus("event_status_Avatar_RenderingStateChanged",(t=>{const e=!!t?.running;this._avatarRunning!==e&&(this._avatarRunning=e)})),this._onBus("event_command_UI_SwitchToChatMode",(()=>{"ChatPage"!==this._shownPage?this._shownPage="ChatPage":this._syncUiChatbotMode()})),this._onBus("event_command_UI_SwitchToAvatarMode",(()=>{"AvatarPage"!==this._shownPage?this._shownPage="AvatarPage":this._syncUiChatbotMode();try{this._startListening()}catch(t){}})),this._onBus("event_command_UI_EndConversation",(()=>{this._endConversation()})),this._onDom(window,"resize",this.handleWindowResize.bind(this));try{const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null;t&&(this._onDom(t,"resize",this.handleWindowResize.bind(this)),this._onDom(t,"scroll",this.handleWindowResize.bind(this)))}catch(e){}this.resizeObserver=new ResizeObserver((t=>{if(!t||!t.length)return;const i=t[0],{width:a,height:n}=i.contentRect||{};if((!this.toggler||!1!==this._showChatbot)&&a>120&&n>120&&(E.dom.canvasWidth=Math.round(a),E.dom.canvasHeight=Math.round(n),this._speakingAvatar&&this._speakingAvatar.avatarModule))try{this._speakingAvatar.avatarModule.onResize()}catch(e){}}));const t=this.renderRoot.querySelector("#avatar-container");t&&this.resizeObserver.observe(t);try{this.hostResizeObserver=new ResizeObserver((()=>{requestAnimationFrame((()=>this.updateSize()))})),this.hostResizeObserver.observe(this)}catch(e){}}disconnectedCallback(){if(super.disconnectedCallback(),this._disposeListeners(),this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._speakingAvatar?.destroy?.(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.hostResizeObserver){try{this.hostResizeObserver.disconnect()}catch(t){}this.hostResizeObserver=null}}updateSize(){const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null,e=t?Math.round(t.width):window.innerWidth,i=t?Math.round(t.height):window.innerHeight,a=t?Math.round(t.offsetTop):0,n=e<E.dom.smallDisplayWidth;let s,o;const r=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:null},c=r(this.canvasWidth),h=r(this.canvasHeight),l=r(this.chatbotHeight),d=(this.compact?0:E.dom.headerAndFooterHeight)+E.dom.controlsHeight;if("mobile"===this.target_app){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else if(this.toggler)if(n){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else{const t=Math.max(120,c??(E.dom.canvasWidth||400)),e=Math.max(120,h??(E.dom.canvasHeight||500));s=t,o=Math.max(120,l??e+d)}else{const t=this.getBoundingClientRect?.()||{},a=Math.round(t.width||this.offsetWidth||this.clientWidth||e),n=Math.round(t.height||this.offsetHeight||this.clientHeight||i),r=Math.max(120,c??a),u=Math.max(120,h??(E.dom.canvasHeight||n));s=r;const p=n>=120?n:u+d;o=Math.max(120,l??(h?u+d:p))}this._canvasWidth===s&&this._chatbotHeight===o||(this._canvasWidth=s,this._chatbotHeight=o)}async _initialize(){if(this._initInProgress)return this._initPromise;this._initInProgress=!0,this._initPromise=(async()=>{if(""===this.api_key&&""===this.token_endpoint||""===this.avatar_id)this.updateAlertStatus("ErrorPage");else{this.updateAlertStatus("LoaderPage");try{const t=await this._getChatbotState();this._showChatbot=t.isVisible,this._savedChatbotMode=t.mode,null!==t.enableCaptions&&(this.enable_captions=t.enableCaptions),await this.updateComplete,await this._initializeSpeakingAvatar()}catch(t){this.updateAlertStatus("DisconnectedPage")}}})();try{await this._initPromise}finally{this._initInProgress=!1,this._initPromise=null}}async _initializeSpeakingAvatar(){const t={avatarAPIKey:this.api_key,avatarId:this.avatar_id,avatarContainer:this.renderRoot.querySelector("#avatar-container"),tokenEndpoint:this.token_endpoint,targetApp:this.target_app};this._wakeLock.request();try{if(!(await this._speakingAvatar.init(t)))throw new Error("Initialization failed");this._avatarName=this._speakingAvatar.sessionData.avatarName,this._language=this._speakingAvatar.sessionData.language,this.username=this._speakingAvatar.sessionData.username,this.phoneNumber=this._speakingAvatar.sessionData.phoneNumber,this.email=this._speakingAvatar.sessionData.email,!0===this.isTermsAccepted?this._speakingAvatar.sessionData.isTermsAccepted=!0:this.isTermsAccepted=this._speakingAvatar.sessionData.isTermsAccepted,this._isFullBody=this._speakingAvatar?.avatarModule?.isFullBody,this._setupAvatarStateSubscription();const e=null!==this._speakingAvatar?.sessionData?.trainingId;e&&(this._initConversation(),this._syncUiChatbotMode()),e?this.compact?this._shownPage="AvatarPage":"CHAT"===this._savedChatbotMode?this._shownPage="ChatPage":this._shownPage="AvatarPage":this._shownPage="ErrorPage"}catch(e){throw e}}handleWindowResize(){this.updateSize()}_handleVisibilityChange(t){let e=!0;try{const i="string"==typeof t?t:t?.type;e=!(document.hidden||"hidden"===document.visibilityState),"pagehide"!==i&&"freeze"!==i||(e=!1),"pageshow"!==i&&"focus"!==i||(e=!0)}catch(a){e=!0}const i=this._speakingAvatar?.avatarOrchestrator;i&&"function"==typeof i.sendEvent?i.sendEvent("VISIBILITY_CHANGED",{isVisible:e}):e?this._resumeAfterForeground():this._pauseAvatarForBackground()}_pauseAvatarForBackground(){this._speakingAvatar?.avatarOrchestrator?(this._speakingAvatar.avatarOrchestrator.is("speaking")&&this._speakingAvatar.avatarOrchestrator.sendEvent("INTERRUPT"),this._speakingAvatar.avatarOrchestrator.is("listening")&&this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"),this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._idleSpeakingAvatar(),this._wakeLock.release()):this._wakeLock.release()}_resumeAfterForeground(){}_idleSpeakingAvatar(){this._speakingAvatar&&this._speakingAvatar.avatarOrchestrator&&(this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"))}_startListening(){this._inputsBlocked||this._isConversationInProgress&&this._speakingAvatar?.avatarOrchestrator?.is("idle")&&this._speakingAvatar.avatarOrchestrator.sendEvent("LISTEN")}_initConversation(){this.isInitialized()&&this._speakingAvatar.avatarOrchestrator.sendEvent("INIT_CONVERSATION")}_startOrResumeConversation(t=!1){Promise.resolve(this._hasChatConsent()).then((e=>{e?this._proceedStartConversation(t):this._showChatConsentDialog=!0})).catch((()=>{this._showChatConsentDialog=!0}))}_proceedStartConversation(t){try{const t=!(document.hidden||"hidden"===document.visibilityState);this._speakingAvatar?.avatarOrchestrator?.sendEvent("VISIBILITY_CHANGED",{isVisible:t})}catch(e){}this._speakingAvatar?.sessionData&&!0===this.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=!0),this._speakingAvatar.avatarOrchestrator.sendEvent("START_CONVERSATION",{fresh:t,termsAccepted:!0===this.isTermsAccepted})}_endConversation(t=!0){t?this._showSatisfactionScore=!0:this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0})}_updateLiveCaption(t,e="",i="",a=!1,n=!1){const s=E?.captions??{},o=s.captionChangeDelay??200,r=s.captionTimeout??1500,c=this._liveCaptionSpeaker;t&&"user"===i&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),n?(this._isLiveCaptionsVisible=!1,setTimeout((()=>{this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i}),o)):(this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i),t||"user"===(i||c)&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),a&&(this.captionsTimeoutId=setTimeout((()=>{this._isLiveCaptionsVisible=!1,this._liveCaption="",this._liveCaptionSpeaker="",this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this.captionsTimeoutId=null}),r))}updateAlertStatus(t=null){const e=this._actorSnapshot;e?.context;const i=!(!this.api_key&&!this.token_endpoint||!this.avatar_id),a=this._speakingAvatar?.sessionData&&null===this._speakingAvatar.sessionData.trainingId;let n=null;n=i?e?.matches?.("lifecycle.init.initializing")?"initializing":e?.matches?.("lifecycle.init.failed")?"failed":a?"invalidConfiguration":e?.matches?.("connection.connected")?"connected":"recovering":"invalidConfiguration","initializing"!==n||"connected"!==this._statusBarStatus&&"recovering"!==this._statusBarStatus||(n=this._statusBarStatus),this._statusBarStatus!==n&&(this._statusBarStatus=n),null!==t&&this._shownPage!==t&&(this._shownPage=t)}get initStatusValue(){return this.initStatus()}initStatus(){const t=this._actorSnapshot;if(!t)return"INITIALIZING";if(!this.api_key&&!this.token_endpoint||!this.avatar_id)return"INVALID";if(t.matches?.("lifecycle.init.failed"))return"FAILED";if(t.context?.initFailed&&t.matches?.("lifecycle.init.initializing"))return"FAILED";if(t.matches?.("lifecycle.init.initializing"))return"INITIALIZING";const e=this._speakingAvatar?.sessionData;return e&&e.avatarId&&null===e.trainingId?"INVALID":"COMPLETED"}isInitialized(){return"COMPLETED"===this.initStatus()}isInitializing(){return"INITIALIZING"===this.initStatus()}_handleToggleChatbot(){this._showChatbot||this._isConversationInProgress||this._isInitializingConversation?this._updateChatbotVisibility(!this._showChatbot):(this._updateChatbotVisibility(!0),this.isInitialized()&&this._startOrResumeConversation())}_updateChatbotVisibility(t){this._showChatbot=t,this._saveChatbotState()}_saveChatbotState(){const t="ChatPage"===this._shownPage?"CHAT":"AVATAR",e={isVisible:this._showChatbot,mode:t,enableCaptions:this.enable_captions};at.setItem("chatbotState_"+this.avatar_id,JSON.stringify(e))}async _getChatbotState(){try{const t=await at.getItem("chatbotState_"+this.avatar_id);if(t){const e=JSON.parse(t);return{isVisible:!0===e.isVisible,mode:e.mode||"AVATAR",enableCaptions:void 0!==e.enableCaptions?e.enableCaptions:null}}}catch(t){}return{isVisible:!1,mode:"AVATAR",enableCaptions:null}}_openLastMessage(t){this._lastMessageText=this._currentMessage.messageText,this._showLastMessage=!0}_closeLastMessage(){this._showLastMessage=!1}_showMenuOnHover(){window.matchMedia("(hover: hover)").matches&&(this._showMenu=!0,this.shadowRoot.getElementById("menu").classList.remove("hidden"))}_handleChatbotClick(){if(!this.compact){const t=this.shadowRoot.getElementById("menu");t?.classList.add("hide"),setTimeout((()=>{t?.classList.contains("hide")&&(this._showMenu=!1)}),500)}}_closeChatbot(){this._updateChatbotVisibility(!1)}_handleToggleMenu(){this._showMenu=!this._showMenu}_handleMicBtn(){const t=this._speakingAvatar?.avatarOrchestrator;t&&(this._isConversationInProgress||this._isStartingConversation)?(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.sendEvent("MIC_BUTTON")):this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("startConversationReminder")})}_handleShowChatPage(){if(this.isInitialized()){if(this.compact)return;this._shownPage="ChatPage",this._showMenu=!1,this._saveChatbotState()}}_handleShowAvatarPage(){this.isInitialized()&&(this._shownPage="AvatarPage",this._startListening(),this._showMenu=!1,this._saveChatbotState())}_handleShowUserData(t){t.preventDefault(),this._showUserData=!0,this._showMenu=!1}_handleEndConversationBtn(){this.showConfirmationDialog(this._t("endConversationPrompt"),(()=>{this._endConversation()}),(()=>{}),this._t("end"),this._t("cancel")),this._showMenu=!1}_handleStartConversationMenuBtn(t){t.preventDefault(),t.stopPropagation(),this._shouldConfirmRestart()?this._handleRestartConversation():(this._startOrResumeConversation(!0),this._showMenu=!1)}_handleStartConversationBtn(t){t.preventDefault(),this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}_handleRestartConversation(){this.showConfirmationDialog(this._t("restartConversationPrompt"),(()=>{this._idleSpeakingAvatar(),this._startOrResumeConversation(!0)}),(()=>{}),this._t("newConversation"),this._t("cancel"))}_consentStorageKey(){return`chatConsent_${this.avatar_id||"unknown"}`}async _hasChatConsent(){if(!0===this.isTermsAccepted)return!0;try{return"accepted"===await at.getItem(this._consentStorageKey())}catch(t){return!1}}async _handleConsentAccept(){try{await at.setItem(this._consentStorageKey(),"accepted")}catch(t){}this._showChatConsentDialog=!1;try{this.isTermsAccepted=!0,this._speakingAvatar?.sessionData&&(this._speakingAvatar.sessionData.isTermsAccepted=!0)}catch(t){}this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}async _handleConsentDecline(){try{await at.setItem(this._consentStorageKey(),"declined")}catch(t){}this._showChatConsentDialog=!1}_activateConsentFocusTrap(){requestAnimationFrame((()=>{try{this.shadowRoot?.querySelector(".dialog .button-save")?.focus()}catch(t){}}));const t=t=>{if(this._showChatConsentDialog&&("Escape"===t.key&&(this._showChatConsentDialog=!1,t.stopPropagation()),"Tab"===t.key)){const e=Array.from(this.shadowRoot.querySelectorAll(".dialog button"));if(!e.length)return;const i=e.indexOf(document.activeElement);t.preventDefault(),(t.shiftKey?i<=0?e[e.length-1]:e[i-1]:i===e.length-1?e[0]:e[i+1]).focus()}};this._consentKeyHandler=t,this.addEventListener("keydown",t)}_deactivateConsentFocusTrap(){this._consentKeyHandler&&(this.removeEventListener("keydown",this._consentKeyHandler),this._consentKeyHandler=null)}_canDownloadTranscript(){return this._conversationTranscript.length>0}_handleDownloadTranscriptMenuBtn(t){t.preventDefault(),this._callDownloadTranscript(),this._showMenu=!1}_callDownloadTranscript(){((t,e,i,a)=>{const n=(new Date).toLocaleString().replace(/[/:, ]/g,"-");let s=`\ufeff\nCONVERSATION TRANSCRIPT\n\n\nšŸ“… Date: ${(new Date).toLocaleString()}\nšŸ¤– Assistant: ${e}\nšŸ‘¤ User: ${i||"User"}${t?`\n⚔ Powered by ${t}`:""}\n\n`;a.forEach((t=>{const{speaker:a,messageText:n,time:o}=t;let r,c;if("user"===a)r=i||"User",c="šŸ‘¤";else{if("assistant"!==a)return;r=e,c="šŸ¤–"}s+=`${c} ${r} [${o}]\n${n}\n\n─────────────────────\n\n`}));const o=new Blob([s],{type:"text/plain;charset=utf-8"}),r=document.createElement("a");r.href=URL.createObjectURL(o),r.download=`transcript-${e}-${n}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r)})(this.brand_name,this._speakingAvatar.sessionData.avatarName,this._speakingAvatar.sessionData.username,this._conversationTranscript)}async _handleSaveClick(){this._speakingAvatar.sessionData.username=this.username,this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber,this._speakingAvatar.sessionData.email=this.email,this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted,this._speakingAvatar?.chatSocket?.sendUserData(),this._showUserData=!1}_handleCancelClick(){this._showUserData=!1}_handleChatKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTextMessage())}_handleSendTextMessage(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#message_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e}))}_handleTypingKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTypedInput())}_handleSendTypedInput(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#typed_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e,chatbotMode:"AVATAR"}))}showConfirmationDialog(t,e,i,a,n){this._dialogMessage=t,this._confirmDialog=e,this._cancelDialog=i,this._confirmButtonLabel=a??this._t("confirm"),this._cancelButtonLabel=n??this._t("cancel"),this._showConfirmationDialog=!0}_handleConfirm(){this._confirmDialog&&this._confirmDialog(),this._resetDialog()}_handleCancel(){this._cancelDialog&&this._cancelDialog(),this._resetDialog()}_resetDialog(){this._showConfirmationDialog=!1,this._confirmDialog=()=>{},this._cancelDialog=()=>{},this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_handleToggleCaptionsSwitch(t){this.enable_captions=t.target.checked,this._saveChatbotState()}_handleVisemeButtonClick(t){this.bus.emit("event_command_visemeButtonClick",{visemeId:t.target.getAttribute("data-viseme-id")})}_handleFacialButtonClick(t){this.bus.emit("event_command_facialButtonClick",{facialId:t.target.getAttribute("data-facial-id")})}_handleConnectBtn(){"COMPLETED"!==this.initStatus()?this._initialize():this.bus.emit("event_command_ConnectionManager_ReconnectFailedModules")}_handleUpperBodyIcon(){this._speakingAvatar?.avatarModule?.setView("upper")}_handleFullBodyIcon(){this._speakingAvatar?.avatarModule?.setView("full")}_handleMidBodyIcon(){this._speakingAvatar?.avatarModule?.setView("mid")}_handleHeadBodyIcon(){this._speakingAvatar?.avatarModule?.setView("head")}_handleSubmitScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:this._satisfactionScore}),this._showSatisfactionScore=!1}_handleCancelScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0}),this._showSatisfactionScore=!1}_scheduleChatScroll(){try{if("ChatPage"!==this._shownPage)return;requestAnimationFrame((()=>{try{const t=this.shadowRoot?.querySelector(".chatbox");t&&(t.scrollTop=t.scrollHeight)}catch(t){}}))}catch(t){}}_syncUiChatbotMode(){if(!this._speakingAvatar?.avatarOrchestrator||!this._speakingAvatar?.chatSocket)return;const t={isShown:!this.toggler||this._showChatbot,chatbotMode:"AvatarPage"===this._shownPage?"AVATAR":"CHAT"};t.isShown===this._lastUiChatbotMode.isShown&&t.chatbotMode===this._lastUiChatbotMode.chatbotMode||(this._speakingAvatar.avatarOrchestrator.sendEvent("UI_CHATBOT_MODE",t),this._lastUiChatbotMode=t)}_handleToggleTyping(){this._showTyping=!this._showTyping}_testSetAuthConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.authentication.updateConnectionState(t)}_testSetSocketConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.chatSocket.updateConnectionState(t)}_testSetSpeechConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules["speech-token"].updateConnectionState(t)}_shouldConfirmRestart(){return!!(this._isConversationInProgress||this._isConversationPaused||this._isConversationResumable||this._isConversationTimedOut||this._isInitializingConversation)}}const Ee="undefined"!=typeof window&&void 0!==window.sessionStorage,Pe={getItem:t=>Promise.resolve(Ee?window.sessionStorage.getItem(t):null),setItem:(t,e)=>Promise.resolve(Ee?window.sessionStorage.setItem(t,e):void 0),removeItem:t=>Promise.resolve(Ee?window.sessionStorage.removeItem(t):void 0)};function De(t){at.setInstance(t)}function He(){"undefined"!=typeof window&&void 0!==window.customElements&&(customElements.get("sentifyd-bot")||customElements.define("sentifyd-bot",Me))}function Oe(t){if(He(),t.containerId&&document.querySelector(`#${t.containerId} sentifyd-bot`))return document.querySelector(`#${t.containerId} sentifyd-bot`);let e=document.body;if(t.containerId){const i=document.getElementById(t.containerId);i&&(e=i)}const i=document.createElement("sentifyd-bot");return Object.keys(t).forEach((e=>{if("containerId"===e||"customAttributes"===e)return;const a=t[e];if(null!=a&&""!==a){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();i.setAttribute(t,"boolean"==typeof a?String(a):a)}})),t.customAttributes&&Object.keys(t.customAttributes).forEach((e=>{const a=t.customAttributes[e];null!=a&&""!==a&&i.setAttribute(e,String(a))})),e.appendChild(i),i}at.setInstance(Pe),"undefined"!=typeof window&&He();export{Me as SentifydBot,Oe as createSentifydBot,De as initializeStorage,He as registerSentifydBot};