sentifyd-bot 1.1.4 → 1.1.5

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 +66 -17
  2. package/package.json +1 -1
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 n,CancellationReason as a,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,n,a)=>{t.emit("event_command_Avatar_PlayOrStopGesture",{gesture:e,duration:i,mirror:n,ms:a})},j=async(t,e,i)=>{t.emit("event_command_Avatar_PlayOrStopAnimation",{animation:e,dur:i})},q=async(t,e,i,n,a)=>{t.emit("event_command_Avatar_ControlAvatarLookAt",{target:e,t:i,x:n,y:a})};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,n)=>{this.socket=t(this.socketUrl,{auth:{token:`Bearer ${e}`},path:"/socket.io",reconnection:!0,reconnectionAttempts:5,reconnectionDelay:500,reconnectionDelayMax:1e4}),this.registerWebsocketEventHandlers(i,n)}))}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,n)=>{this.isSocketConnected()?this.socket.emit(t,e,(t=>{i(t)})):(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),n(new Error("Socket not connected")))}))}timeoutEmit(t,e,i,n){this.isSocketConnected()?n?this.socket.timeout(i).emit(t,e,n):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(n){e=n,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}i=!0}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(n){}},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(n){}},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,n){if(X._instance)return X._instance;super("chatSocket"),this.validateDependencies({bus:t,auth:e,sessionData:i,avatarOrchestrator:n}),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=n,this.pendingDelayedActions=null,this.turn=null,this.INTERRUPT_WATCHDOG=15e3,X._instance=this}static getInstance(t,e,i,n){return X._instance||(X._instance=new X(t,e,i,n)),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,n)=>{i||"success"!==n?.status?e(new Error(i||n?.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,streaming:!1,isTermsAccepted:!0===this.sessionData.isTermsAccepted},Y,(async(i,n)=>{if(i||"success"!==n?.status)e(new Error(i||n?.error?.message||"Conversation start failed"));else try{await this.processAIResponse(n),t(n)}catch(a){e(a)}}))}))}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)),n=e.filter((t=>!1===t.immediate));if(i.length>0&&await P(i,this.bus),n.length>0&&(this.pendingDelayedActions=n),"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 n=z(new Date);return this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:t.messageText,time:n,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:n,avatarOrchestrator:a,autoDetectLanguage:s}={}){this.validateDependencies({recognizer:t,speechConfig:e,audioConfig:i,bus:n,avatarOrchestrator:a}),this.bus=n,this.avatarOrchestrator=a,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,n){if(!t)throw new Error("speechConfig is required");const{recognizer:a,audioConfig:s}=await this.init(t,e),o=new Z({recognizer:a,speechConfig:t,audioConfig:s,bus:i,avatarOrchestrator:n,autoDetectLanguage:!!e});return o._registerRecognizerEvents(),o}static async init(t,n){try{const a=e.fromDefaultMicrophoneInput();let s=null;return s=n?i.FromConfig(t,n,a):new i(t,a),{recognizer:s,audioConfig:a}}catch(a){throw new Error("Error in SpeechRecognition initialization: "+a)}}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===n.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===a.Error&&this._handleAzureSpeechError(e),this.stop()}}_handleAzureSpeechError(t){const e=t.errorCode,i=t.errorDetails||"No additional details available";let n="",a=!1;switch(e){case s.NoError:n="An unexpected error occurred. Please try again.";break;case s.AuthenticationFailure:n="Unable to connect to voice services. Please try again later.",a=!0;break;case s.BadRequestParameters:n="Voice service is temporarily unavailable. Please try again in a moment.";break;case s.TooManyRequests:n="Too many simultaneous requests. Please wait a moment and try again.";break;case s.ConnectionFailure:n="Connection issue detected. Please check your internet connection and try again.";break;case s.ServiceTimeout:n="Response timeout. Please try again.";break;case s.ServiceError:n="Voice service is temporarily unavailable. Please try again in a moment.";break;case s.RuntimeError:n="An unexpected error occurred. Please refresh the page and try again.";break;case s.Forbidden:n="Voice service is currently busy. Please try again in a few minutes.";break;default:n="An unknown error occurred. Please try again."}a&&this.bus.emit("event_error_VoiceBot_ExpiredOrInvalidToken",i),this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:n})}_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,n]of Object.entries(this.languageDurations))n>e&&(e=n,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:n,bus:a,auth:s,avatarOrchestrator:o,sessionData:r}={}){this.validateDependencies({speechService:t,speechConfig:e,speechRecognizer:n,bus:a,auth:s,avatarOrchestrator:o,sessionData:r}),this.sessionData=r,this.speechService=t,this.speechConfig=e,this.speechRecognizer=n,this.bus=a,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,n){const{speechService:a,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r}=await this.init(n,t,i,e);return new K({speechService:a,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r,bus:t,auth:i,avatarOrchestrator:e,sessionData:n})}static async init(t,e,i,n){try{const a=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"===a?s.length>0?l=c.fromLanguages(s):h.speechRecognitionLanguage="en-US":h.speechRecognitionLanguage=a;const x=await Z.build(h,l,e,n);return{speechService:d,speechConfig:h,autoDetectSourceLanguageConfig:l,speechRecognizer:x}}catch(a){throw new Error("Error in VoiceBot initialization",{cause:a})}}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],n=Math.max(10,Math.min(e,i||e)),a=Math.max(1.5*n,i||10*n),s=Math.sqrt(n*a);this._micBpf.frequency.value=Number.isFinite(s)?s:1e3;const o=Math.log2(a/n),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)),n=this._avatarAnalyser?this._readRms(this._avatarAnalyser,this._avatarBuffer):0,a=this._clamp01(n),s=this._updateEnvelope("_micEnvelope",i,e),o=this._updateEnvelope("_avatarEnvelope",a,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:a,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:a,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:a,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:a,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:a,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:n,effectiveMic:a,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:n,effectiveMic:a,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:n,effectiveMic:a,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(n){return 0}let i=0;for(let a=0;a<e.length;a++){const t=e[a];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 n="number"==typeof this[t]?this[t]:e,a=Math.min(Math.max(this.config.envelopeAttack,0),.999),s=Math.min(Math.max(this.config.envelopeRelease,0),.999),o=e>=n?a:s,r=Math.max(i/16.7,.1),c=n+(e-n)*(1-Math.pow(o,r)),h=this._clamp01(c);return this[t]=h,h}_updateLeakEstimate({micSignal:t,avatarSignal:e,candidateActive:i}){const n=this.config.leakMinAvatar??0,a=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>n&&t<.8*this.config.absoluteMicOverride&&!u){const i=t/Math.max(e,1e-5);c+=(Math.max(s,Math.min(i,o))-c)*a,this._leakEstimate=c,this._debugLeakUpdate({ratio:i,estimate:c}),this._lastAvatarBelowMin=null}else if(e<=n&&c>s){const t=this.config.leakDecayHoldMs??1e3,i=this.config.leakDecayRate??.1*a;null==this._lastAvatarBelowMin&&(this._lastAvatarBelowMin=r),e<=n?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 n=e-this._noiseMean;this._noiseVar+=i*n}_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 nt={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 at 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 at(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 n=i.avatarId;t.id=n;const a={accessToken:e.data.access_token,refreshToken:e.data.refresh_token,avatarParameters:i};await t.updateAuthData(a),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:n,onError:a}){this.serverBaseURL=t,this.getRefreshToken=e,this.onSuccess=n,this.onError=a,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 n=await i.json();if(!n?.data?.access_token)throw new Error("Invalid token data received during refresh.");this.updateAccessToken&&await this.updateAccessToken(n.data.access_token),"function"==typeof this.onSuccess&&this.onSuccess(n.data.access_token),t(!0)}catch(n){"function"==typeof this.onError&&this.onError(n),e(n)}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="",n=""){this.id=n,this.targetApp=t,this.#t=e,this.tokenEndpoint=i;try{return await this.authenticate(),this.startTokenRefreshInterval(),!0}catch(a){return this.handleAuthenticationFailure(`Error during authentication initialization: ${a.message}`,a),!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 at?t.reason:t?.message||null,statusCode:t instanceof at&&"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 n=`${this.serverBaseURL}${t}`,a=new Headers({"Content-Type":"application/json"}),s=this.getAccessToken();if(!s)throw new Error("Cannot call the API without an access token");a.append("Authorization",`Bearer ${s}`);const o={method:e,headers:a,body:i?JSON.stringify(i):void 0};try{let t=await fetch(n,o);if(401===t.status)try{await this.authenticate();const e={...o,headers:{...o.headers,Authorization:`Bearer ${this.getAccessToken()}`}};if(t=await fetch(n,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.#n();return!(t&&t.accessToken&&t.refreshToken&&t.avatarParameters&&!this.isTokenCloseToExpiration())}async logout(){this.id&&await async function(t){if(t)try{await nt.removeItem(`authData_${t}`)}catch(e){}}(this.id),this.stopTokenRefreshInterval(),this.#e=null,this.#i=null,this.avatarParameters=null,this.clearFailureDetails(),this.setDisconnected()}async#a(){if(!this.id)return!1;const t=await async function(t){if(!t)return null;try{const e=await nt.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}}#n(){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 n=this.#n()||{};t&&(this.#e=t,n.accessToken=t),e&&(this.#i=e,n.refreshToken=e),i&&(this.avatarParameters=i,n.avatarParameters=i);try{await async function(t,e){if(t)try{await nt.setItem(`authData_${t}`,JSON.stringify(e))}catch(i){}}(this.id,n),this.clearFailureDetails()}catch(a){}}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 at?e.reason:e instanceof Error?e.message:null,statusCode:e instanceof at&&"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 nt.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 nt.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 nt.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 n={speaker:i,messageText:L(t),time:e};return this.transcript.push(n),await this.saveConversationData(),n}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:n,trainingId:a,language:s,autodetectLanguages:o,voice:r,wordsPerMinute:c}=t;if(![i,n,e,s,r].every((t=>null!=t&&""!==t))||!Array.isArray(o))return!1;this._trainingId=null===a||""===a?null:a,this._avatarId=i,this._avatarName=n,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(n){}},({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(n){}},({context:t,event:e})=>{const{message:i,time:n}=e?.payload||{};t.conversation&&i&&(async()=>{try{const a=n||(new Date).toLocaleTimeString(),s=await t.conversation.appendMessage(i,a,"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 a=e?.payload?.newPage;if(!a)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"!==a&&(o||r)&&(o?i.send({type:"INTERRUPT"}):r&&i.send({type:"IDLE"})),"AvatarPage"===a)try{const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&t.isPageVisible&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}catch(n){}}catch(a){}},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 n=e&&(e.payload?.isVisible??e.isVisible),a=void 0===n?!!t.isPageVisible:!!n,s=a&&!t.isPageVisible;if(!a&&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:a,pendingStart:null}}s&&t.voiceBot&&i.getSnapshot().matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})}try{if(a&&"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:a}})),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(n){}},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:n,turnId:a}=e.payload||{};t.voiceBot&&void 0!==a&&(t.voiceBot._currentTurnId=a,t.voiceBot._expectedTurnId=a),t.talkingAvatar&&i&&n&&t.talkingAvatar.startStreaming(i,n,a)},onInterruptSpeaking:({context:t,self:e})=>{if(t.voiceBot){const i=Date.now();if(i-t.voiceBot._lastInterruptionTime<t.voiceBot.INTERRUPTION_DEBOUNCE)return;const n=-1!==t.voiceBot._expectedTurnId,a=t.voiceBot._isHandlingAudioEnd,s=e.getSnapshot(),o=s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart");n&&o&&!a&&(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 n=e.payload;if(!n||void 0===n.isShown&&!n.chatbotMode)return;const a=n.chatbotMode;if(t.chatSocket&&(void 0!==a&&(t.chatSocket.chatbotMode=a),void 0!==n.isShown&&(t.chatSocket.isChatbotShown=n.isShown)),"CHAT"===a){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"===a)try{const e=i.getSnapshot(),n=e.matches?.("lifecycle.conversation.inProgress"),a=e.matches?.("lifecycle.conversation.inProgress.idle"),s=!!t.isPageVisible;n&&a&&s&&i.send({type:"LISTEN"})}catch(s){}if(!1===n.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===n.isShown)try{const e=i.getSnapshot(),n=e.matches?.("lifecycle.conversation.inProgress"),s=e.matches?.("lifecycle.conversation.inProgress.idle"),o=!!t.isPageVisible;"AVATAR"===(void 0!==a?a:t.chatSocket?.chatbotMode)&&n&&s&&o&&i.send({type:"LISTEN"})}catch(s){}try{const e=void 0!==a?a:t.chatSocket?.chatbotMode,i=void 0!==n.isShown?n.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(n){}},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:n,chatbotMode:a}=e.payload||{};if(!n)return;if(t.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:n.message||"Conversation error. Please try again."}),908===n.code&&void 0!==n.conversationId)return void i.send({type:"CONVERSATION_TIMEOUT",payload:{conversationId:n.conversationId}});const s=i.getSnapshot();s.matches("lifecycle.conversation.inProgress.thinking")&&i.send({type:"IDLE"}),"AVATAR"===a&&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,n=Array.isArray(t.conversation.conversationData?.transcript)&&t.conversation.conversationData.transcript.length>0;return e&&(i||n)}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:n,talkingAvatar:a}=t||{};if(!i||!n)throw new Error("Conversation or ChatSocket module not available");if(await Promise.resolve(),a?.conversationStreamActive)try{await(a.stopConversationStream?.())}catch(s){}return e&&i.conversationId&&await i.notifyConversationEnd(),await i.notifyConversationStart(e),await n.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:n,bus:a}=t||{};if(!e||!n)throw new Error("Dependencies not available");if(!i||!i.messageText)throw new Error("Invalid speech payload");const s=await n.appendMessage(i.messageText,z(new Date),"user");try{a?.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:n,bus:a}=t||{};if(!e||!n)throw new Error("Dependencies not available");if(!i||!i.message)throw new Error("Invalid text payload");const s=await n.appendMessage(i.message,z(new Date),"user");try{a?.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:n,time:a,notify:s}=t||{};if(e)try{const t=a||z(new Date),c=await e.appendMessage(n,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:n,time:a||z(new Date)}})}catch(r){}}else try{"function"==typeof s&&s({message:{speaker:"assistant",messageText:n,time:a||z(new Date)}})}catch(r){}})),endConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i,talkingAvatar:n,voiceBot:a,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{n?.interruptSpeaking?.()}catch(c){}try{await(n?.stopConversationStream?.())}catch(c){}try{n?.liveCaptions?.clearCaptions?.(),a?.stopListening?.()}catch(c){}return!0})),clearConversationActor:p((async({input:t})=>{const{conversation:e,talkingAvatar:i,payload:n}=t||{};if(!e)return!0;const{conversationId:a}=n||{};if(a===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(n){}return{resumable:!0}}}catch(a){throw a}return{resumable:!1}})),cleanupInterruptionActor:p((async({input:t})=>{const{talkingAvatar:e,chatSocket:i,voiceBot:n}=t||{};try{try{e?.liveCaptions?.clearCaptions?.()}catch(a){}if(n)try{n.stopListening?.()}catch(a){}try{e?.interruptSpeaking?.()}catch(a){}try{i?.interruptCurrentTurn?.()}catch(a){}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 n={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,n=e.lifecycle;if(!i||!n)return!1;if(i.initInitializing!==n.initInitializing||i.initFailed!==n.initFailed||i.convoStopped!==n.convoStopped||i.convoResumable!==n.convoResumable||i.convoInProgress!==n.convoInProgress||i.convoStarting!==n.convoStarting||i.convoInitializing!==n.convoInitializing||i.conversationSubstate!==n.conversationSubstate)return!1;const a=t.connection,s=e.connection;if(!a||!s)return!1;if(a.connected!==s.connected||a.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}(n,e)&&(e=n,t(n,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 n,a;const s=()=>{n&&clearTimeout(n),a&&this.bus.off("connectionStateChanged",a)};n=setTimeout((()=>{s(),i(new Error("Connection timeout"))}),t),a=()=>{this._allConnectionsReady&&(s(),e(!0))},this.bus.on("connectionStateChanged",a)}))}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 n;if("type"===e)n=i.type;else if("stiffness"===e)n=i.k.every((t=>t===i.k[0]))?i.k[0]:[...i.k];else if("damping"===e)n=i.c.every((t=>t===i.c[0]))?i.c[0]:[...i.c];else if("external"===e)n=i.ext<1?i.ext:null;else if("limits"===e)n=i.limits?.map((t=>null===t?null:[...t]));else if("deltaLocal"===e)n=i.dl?[...i.dl]:null;else if("excludes"===e)n=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)n=i.dw?[...i.dw]:null;else if("pivot"===e)n=i.pivot;else{if("helper"!==e)throw new Error("Unsupported property '"+e+"'.");n=i.helper}return n}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 n=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":n.isPoint=!0,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"link":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!1;break;case"mix1":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"mix2":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!0;break;case"full":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!0;break;default:throw new Error("Unknown type'"+i+"'.")}n.type=i.slice()}else if("stiffness"===e){if(!i)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(i)&&i>=0)n.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.");n.k=[...i]}}else if("damping"===e){if(!i)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(i)&&i>=0)n.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.");n.c=[...i]}}else if("external"===e)if(null==i)n.ext=1;else{if(!(!Number.isNaN(i)&&i>=0&&i<=1))throw new Error("External (if set) must be a number between [0,1].");n.ext=i}else if("limits"===e)if(null==i)n.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.");n.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)n.excludes=null;else{if(!Array.isArray(i))throw new Error("Excludes (if set) must null, or an array.");n.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 a={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.");a.deltaLocal=[...t.deltaLocal]}n.excludes.push(a)}))}this.showHelpers()}else if("helper"===e){if(null==i)n.helper=null;else{if(!1!==i&&!0!==i)throw new Error("Helper, if set, must be false or true.");n.helper=i}this.showHelpers()}else if("pivot"===e)if(null==i)n.pivot=null;else{if(!1!==i&&!0!==i)throw new Error("Pivot, if set, must be false or true.");if(!0===i&&0===n.type)throw new Error("Point type bone can't be a pivot.");n.pivot=i}else if("deltaLocal"===e)if(null==i)n.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.");n.dl=[...i]}else{if("deltaWorld"!==e)throw new Error("Unsupported property "+e);if(null==i)n.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.");n.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,n=t=>t.parent?.isBone?[t,...n(t.parent)]:[t],a=t=>{n(t).forEach((t=>{i.has(t)||(this.objectsUpdate.push(t),i.add(t))}))};this.data.forEach((t=>{a(t.bone),t.excludes&&t.excludes.forEach((t=>{a(t.bone)}))})),this.objectsUpdate.sort(((t,i)=>e.get(t)-e.get(i)))}setup(t,e,i){this.dispose();const n=(t,e)=>{if(!t)throw this.dispose(),new Error(e)};n(t?.isScene,"First parameter must be Scene."),this.scene=t,n(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,n(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+": ";n(t.bone,i+"Bone not specified.");const a=t.bone;n("string"==typeof a&&a.length>0,i+"Bone name must be a non-empty string.");const s=this.armature.getObjectByName(a);n(s,i+"Bone '"+a+"' not found."),n(s.parent?.isBone,i+"Bone must have a parent bone."),n(this.data.every((t=>t.bone!==s)),i+"Bone '"+a+"' already exists."),s.updateMatrixWorld(!0);const o={name:a,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[a]=o;try{this.setValue(a,"type",t.type),this.setValue(a,"stiffness",t.stiffness),this.setValue(a,"damping",t.damping),this.setValue(a,"external",t.external),this.setValue(a,"limits",t.limits),this.setValue(a,"excludes",t.excludes),this.setValue(a,"deltaLocal",t.deltaLocal),this.setValue(a,"deltaWorld",t.deltaWorld),this.setValue(a,"pivot",t.pivot),this.setValue(a,"helper",t.helper)}catch(r){n(!1,i+r)}})),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,i,n,a,s;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,n=this.objectsUpdate.length;e<n;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,n=this.data.length;e<n;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,a=s.children.length;i<a;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,a=s.excludes.length;i<a;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),n=new g.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});gt.objects[e]=new g.Mesh(i,n),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),n=new g.Color(this.opt.helperBoneColor2),a=gt.pivots.map((t=>t&&this.opt.isPivots?[n.r,n.g,n.b]:[i.r,i.g,i.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(a,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),n=new g.Color(this.opt.helperLinkColor2),a=gt.bones.map((t=>[i.r,i.g,i.b,n.r,n.g,n.b])).flat();t.setAttribute("color",new g.Float32BufferAttribute(a,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,n=gt.bones.length;e<n;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 a=0;a<64;a++)this.b64Lookup["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(a)]=a;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 n=[];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),n.push(i)})),this.ikMesh.bind(new g.Skeleton(n)),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),n=new Uint8Array(i);let a,s,o,r,c,h=0;for(a=0;a<t.length;a+=4)s=this.b64Lookup[t.charCodeAt(a)],o=this.b64Lookup[t.charCodeAt(a+1)],r=this.b64Lookup[t.charCodeAt(a+2)],c=this.b64Lookup[t.charCodeAt(a+3)],n[h++]=s<<2|o>>4,n[h++]=(15&o)<<4|r>>2,n[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),n=new Uint8Array(i),a=0;for(let s=0;s<t.length;s++)n.set(new Uint8Array(t[s]),a),a+=t[s].byteLength;return i}pcmToAudioBuffer(t){const e=new Int16Array(t),i=new Float32Array(e.length);for(let a=0;a<e.length;a++)i[a]=e[a]>=32768?-(65536-e[a])/32768:e[a]/32767;const n=this.audioCtx.createBuffer(1,i.length,this.opt.pcmSampleRate);return n.copyToChannel(i,0,0),n}propsToThreeObjects(t){const e={};for(let[i,n]of Object.entries(t)){const t=i.split(".");let a=Array.isArray(n.x)?this.gaussianRandom(...n.x):n.x,s=Array.isArray(n.y)?this.gaussianRandom(...n.y):n.y,o=Array.isArray(n.z)?this.gaussianRandom(...n.z):n.z;"position"===t[1]||"scale"===t[1]?e[i]=new g.Vector3(a,s,o):"rotation"===t[1]?(i=t[0]+".quaternion",e[i]=(new g.Quaternion).setFromEuler(new g.Euler(a,s,o,"XYZ")).normalize()):"quaternion"===t[1]&&(e[i]=new g.Quaternion(a,s,o,n.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,n=!1){t.forEach((t=>{if(!n&&t.morphTargetDictionary.hasOwnProperty(e))return;const a=t.geometry;let s=null,o=null;for(const[e,n]of Object.entries(i))if(t.morphTargetDictionary.hasOwnProperty(e)){const i=t.morphTargetDictionary[e],r=a.morphAttributes.position[i],c=a.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)*n,i=s.getY(t)+r.getY(t)*n,a=s.getZ(t)+r.getZ(t)*n;s.setXYZ(t,e,i,a)}if(c)for(let t=0;t<r.count;t++){const e=o.getX(t)+c.getX(t)*n,i=o.getY(t)+c.getY(t)*n,a=o.getZ(t)+c.getZ(t)*n;o.setXYZ(t,e,i,a)}}if(s){a.morphAttributes.position.push(s),o&&a.morphAttributes.normal.push(o);const i=a.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 n=await i.loadAsync(t.url,e);const a=[this.opt.modelRoot];if(this.posePropNames.forEach((t=>a.push(t.split(".")[0]))),a.forEach((t=>{if(!n.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=n.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=n.animations,this.userData=n.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(n.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,n=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,a=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-n)*Math.tan(r/2),l=a;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 n=this.poseAvatar.props[e];if(n){let a=(t-i.t)/i.d;a>1||!this.poseBase.props.hasOwnProperty(e)?n.copy(i):n.isQuaternion?n.copy(this.poseBase.props[e].slerp(i,this.easing(a))):n.isVector3&&n.copy(this.poseBase.props[e].lerp(i,this.easing(a)))}}}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 n=null,a=null;if(null!==i.fixed){if(n=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===n){i.needsUpdate=!1;continue}}else null!==i.realtime?(i.ref=null,i.base=null,a=i.realtime):null!==i.system?(n=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?(n=null,i.system=null,i.systemd=null):(i.systemd-=t,i.systemd<0&&(i.systemd=0),i.value===n&&(n=null)):i.value===n&&(n=null,i.system=null)):null!==i.newvalue?(i.ref=null,i.base=null,a=i.newvalue,i.newvalue=null):null!==i.base?(n=i.base,i.ref=null,i.value===n&&(n=null,i.base=null,i.needsUpdate=!1)):(i.ref=null,null!==i.baseline&&i.value!==i.baseline?(n=i.baseline,i.base=i.baseline):i.needsUpdate=!1);if(null!==n){let e=n-i.value;e>=0?e<.005?(a=n,i.v=0):(i.v<i.maxv&&(i.v+=i.acc*t),a=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?(a=n,i.v=0):(i.v>-i.maxv&&(i.v-=i.acc*t),a=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!==a&&a!==i.value&&(i.value=a,null!==i.onchange&&i.onchange(a)),a=i.limit(i.value),a===i.applied)continue}else{if(null===a||a===i.value)continue;i.value=a,null!==i.onchange&&i.onchange(a)}switch(i.applied=a,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,n)=>{0===n?(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 n=i.applied/20,a={x:n,y:n/2,z:3*n},s={x:1/(1+n)-1,y:1/(1+n/2)-1,z:1/(1+3*n)-1};this.poseDelta.props["Spine1.scale"]=a,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,n)=>{const a=t[0].split(".");if("position"===a[1]||"rotation"===a[1]||"quaternion"===a[1]){const s="quaternion"===a[1]?a[0]+".rotation":t[0],o=t[1].isQuaternion?(new g.Euler).setFromQuaternion(t[1]):t[1];i+=(n?", ":"")+"'"+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,n=e[0]+"."+("quaternion"===e[1]?"rotation":e[1]);if(this.poseWeightOnLeft||(n.startsWith("Left")?(n="Right"+n.substring(4),i="Right"+i.substring(4)):n.startsWith("Right")&&(n="Left"+n.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(n)){const e={};e[n]=this.poseTarget.template.props[n],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,n]of Object.entries(t))n.isQuaternion&&(i.startsWith("Left")?i="Right"+i.substring(4):i.startsWith("Right")&&(i="Left"+i.substring(5)),n.x*=-1,n.w*=-1),e[i]=n.clone(),e[i].t=n.t,e[i].d=n.d;return e}poseFactory(t,e=2e3){const i={template:t,props:this.propsToThreeObjects(t.props)};for(const[n,a]of Object.entries(i.props)){if(this.opt.modelMovementFactor<1&&t.standing&&("Hips.quaternion"===n||"Spine.quaternion"===n||"Spine1.quaternion"===n||"Spine2.quaternion"===n||"Neck.quaternion"===n||"LeftUpLeg.quaternion"===n||"LeftLeg.quaternion"===n||"RightUpLeg.quaternion"===n||"RightLeg.quaternion"===n)){const t=this.poseStraight[n],e=a.angleTo(t);a.rotateTowards(t,(1-this.opt.modelMovementFactor)*e)}a.t=this.animClock,a.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),n=t&&t===this.poseCurrentTemplate,a=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,(!n&&!a||n&&a)&&(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,n=1,a=!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 n=0;n<o.alt.length;n++){let a=this.valueFn(o.alt[n].p);if(i+=void 0===a?(1-i)/(o.alt.length-1-n):a,e<i){t=o.alt[n];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=a?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)+n*this.gaussianRandom(...e):"boolean"==typeof e?e:e instanceof Object&&e.constructor===Object?Object.assign({},e):(void 0===t?0:t)+n*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,n,a,s=null){t=this.valueFn(t),a<i&&(a=i),a>n&&(a=n);let o=((e=this.valueFn(e))-t)/(n-i);return s&&(o*=s((a-i)/(n-i))),o*a+(t-o*i)}gaussianRandom(t,e,i=1,n=5){let a=0;for(let s=0;s<n;s++)a+=Math.random();return t+Math.pow(a/n,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,n,a,s,o=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),i=2,a=10;i<a;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,a=10;i<a;i++)this.volumeFrequencyData[i]>o&&(o=this.volumeFrequencyData[i]);let r=null,c=null;const h=[];for(i=0,a=this.animQueue.length;i<a;i++){const t=this.animQueue[i];if(!(this.animClock<t.ts[0])){for(n=t.ndx||0,s=t.ts.length;n<s&&!(this.animClock<t.ts[n]);n++)for(let[e,i]of Object.entries(t.vs))if(this.mtAvatar.hasOwnProperty(e)){if(null===i[n+1])continue;const a=this.mtAvatar[e];if(null===i[n]&&(i[n]=a.value),n===s-1)a.newvalue=i[n];else{a.newvalue=i[n+1];const s=t.ts[n+1]-t.ts[n];let o=1;s>1e-4&&(o=(this.animClock-t.ts[n])/s),o<1&&(a.easing&&(o=a.easing(o)),a.newvalue=(1-o)*i[n]+o*a.newvalue),a.ref&&a.ref!==t.vs&&a.ref.hasOwnProperty(e)&&delete a.ref[e],a.ref=t.vs}if(o)switch(e){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":a.newvalue*=1+o/255-.5}a.needsUpdate=!0}else"eyeContact"===e&&null!==i[n]&&!1!==r?r=Boolean(i[n]):"headMove"===e&&null!==i[n]&&!1!==c?0===i[n]?c=!1:(Math.random()<i[n]&&(c=!0),i[n]=null):null!==i[n]&&(h.push({mt:e,val:i[n]}),i[n]=null);n===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),a--)):t.ndx=n-1}}for(let l=0,d=h.length;l<d;l++)switch(n=h[l].val,h[l].mt){case"speak":this.speakText(n);break;case"subtitles":this.onSubtitles&&"function"==typeof this.onSubtitles&&this.onSubtitles(n);break;case"pose":this.poseName=n,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...n);break;case"function":n&&"function"==typeof n&&n();break;case"moveto":Object.entries(n.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}]},n.x?new g.Vector3(n.x,n.y,n.z):null,!0,n.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}]},n.x?new g.Vector3(n.x,n.y,n.z):null,!0,n.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,n=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:[n,n,0],headRotateZ:[-i/4,-i/4,0]}})))):(i=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,n=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,n,n,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)],n=this.mtAvatar[i],n.needsUpdate||Object.assign(n,{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,n=Math.abs(i),n>1e-4&&(s=n*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/n)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(i)*Math.min(n,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 n="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[n]&&(this.lipsync[t]=new e[n])}))}catch(i){}const a=e+"lipsync-"+t.toLowerCase()+".mjs";import(a).then((e=>{this.lipsync[t]=new e[n]}))}}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,n=null){const a=/[!\.\?\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(a);const f=m[g].match(r),b=m[g].match(s);if(v&&!t&&!f&&m[g+1].match(a)&&(v=!1),i&&(h+=m[g]),y&&(n&&!n.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 n=(e=e||{}).lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,a={};if(t.words){let e=[];for(let a=0;a<t.words.length;a++){const s=t.words[a],o=t.wtimes[a];let r=t.wdurations[a];if(s.length&&(i&&e.push({template:{name:"subtitles"},ts:[o],vs:{subtitles:[" "+s]}}),!t.visemes)){const t=this.lipsyncPreProcessText(s,n),i=this.lipsyncWordsToVisemes(t,n);if(i&&i.visemes&&i.visemes.length){const t=i.times[i.visemes.length-1]+i.durations[i.visemes.length-1],n=Math.min(r,Math.max(0,r-150*i.visemes.length));let a=.6+this.convertRange(n,[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 n=o+i.times[s]/t*r,c=i.durations[s]/t*r;e.push({template:{name:"viseme"},ts:[n-Math.min(60,2*c/3),n+Math.min(25,c/2),n+c+Math.min(60,c/2)],vs:{["viseme_"+i.visemes[s]]:[null,"PP"===i.visemes[s]||"FF"===i.visemes[s]?.9:a,0]}})}}}}if(t.visemes)for(let i=0;i<t.visemes.length;i++){const n=t.visemes[i],a=t.vtimes[i],s=t.vdurations[i];e.push({template:{name:"viseme"},ts:[a-2*s/3,a+s/2,a+s+s/2],vs:{["viseme_"+n]:[null,"PP"===n||"FF"===n?.9:.6,0]}})}if(t.markers)for(let i=0;i<t.markers.length;i++){const n=t.markers[i],a=t.mtimes[i];e.push({template:{name:"markers"},ts:[a],vs:{function:[n]}})}e.length&&(a.anim=e)}if(t.audio&&(a.audio=t.audio),t.anim?.name){let e=this.animFactory(t.anim,!1,1,1,!0);a.anim?a.anim.push(e):a.anim=[e]}i&&(a.onSubtitles=i),Object.keys(a).length&&(this.speechQueue.push(a),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 n=0;t.anim&&(n=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]+n;this.animQueue.push(t)}))),this.audioSpeechSource.start(n/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 n=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),i),a=await n.json();if(200===n.status&&a&&a.audioContent){const e=this.b64ToArrayBuffer(a.audioContent),i=await this.audioCtx.decodeAudioData(e);this.speakWithHands();const n=[0];let s=0;t.text.forEach(((t,e)=>{if(e>0){let e=n[n.length-1];a.timepoints[s]&&(e=1e3*a.timepoints[s].timeSeconds,a.timepoints[s].markName===""+t.mark&&s++),n.push(e)}}));const o=[{mark:0,time:0}];n.forEach(((t,e)=>{if(e>0){let i=t-n[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,n=null,a=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=a,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=n||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 n=t.visemes[i],a=e+t.vtimes[i],s=t.vdurations[i],o={template:{name:"viseme"},ts:[a-2*s/3,a+s/2,a+s+s/2],vs:{["viseme_"+n]:[null,"PP"===n||"FF"===n?.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 n=t.words[i],a=t.wtimes[i];let s=t.wdurations[i];if(n.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+a],vs:{subtitles:[" "+n]}}),"words"==this.streamLipsyncType)){const t=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,i=this.lipsyncPreProcessText(n,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 n=.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+a+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:n,0]}})}}}}if(t.anims&&"blendshapes"==this.streamLipsyncType)for(let i=0;i<t.anims.length;i++){let n=t.anims[i];n.delay+=e;let a=this.animFactory(n,!1,1,1,!0);this.animQueue.push(a)}}}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 n=Math.max(-1,Math.min(1,t.audio[e]));i[e]=n<0?32768*n:32767*n}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,n=this.animQueue.findIndex((t=>"lookat"===t.template.name));-1!==n&&this.animQueue.splice(n,1);const a={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(a))}}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(),n=Math.atan2(i.x,i.z),a=Math.asin(-i.y);Pt.set(a,n,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 n=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const a=(new g.Vector3).setFromMatrixPosition(this.objectLeftEye.matrixWorld),s=(new g.Vector3).setFromMatrixPosition(this.objectRightEye.matrixWorld),o=(new g.Vector3).addVectors(a,s).divideScalar(2);o.project(this.camera);let r=(o.x+1)/2*n.width+n.left,c=-(o.y-1)/2*n.height+n.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(),n=new g.Vector2((t-i.left)/i.width*2-1,-(e-i.top)/i.height*2+1),a=new g.Raycaster;a.setFromCamera(n,this.camera);const s=a.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=[],n=[];i.push(100+Math.round(500*Math.random())),n.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=>{n[0].props[t+".quaternion"]=this.ikMesh.getObjectByName(t).quaternion.clone()})),i.push(1e3+Math.round(500*Math.random())),n.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach((t=>{n[1].props[t+".quaternion"]=null}));const a=this.animFactory({name:"talkinghands",delay:t,dt:i,vs:{moveto:n}});this.animQueue.push(a)}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,n=0,a=.01){if(!this.armature)return;let s=this.animClips.find((e=>e.url===t+"-"+n));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),n=this.mixer.clipAction(s.clip);n.setLoop(g.LoopRepeat,e),n.clampWhenFinished=!0,n.fadeIn(.5).play()}else{const s=new b;let o=await s.loadAsync(t,e);if(o&&o.animations&&o.animations[n]){let s=o.animations[n];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]*a;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+"-"+n,clip:s,pose:c}),this.playAnimation(t,e,i,n,a)}}}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,n=0,a=.01){if(!this.armature)return;let s=this.poseTemplates[t];if(!s){const e=this.animPoses.find((e=>e.url===t+"-"+n));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[n]){let s=o.animations[n];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]*a,t.values[1]*a,t.values[2]*a):"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+"-"+n,pose:c}),this.playPose(t,e,i,n,a)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,i=!1,n=1e3){if(!this.armature)return;let a=this.gestureTemplates[t];if(a){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(a),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=n,this.poseTarget.props.hasOwnProperty(t)&&(this.poseTarget.props[t].copy(e),this.poseTarget.props[t].t=this.animClock,this.poseTarget.props[t].d=n);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,n),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],n=t.ts[t.ts.length-1]-i;if(1e3*e-n>0){const a=[];for(let e=1;e<t.ts.length;e++)a.push(t.ts[e]-t.ts[e-1]);const o=s.template?.rescale||a.map((t=>t/n)),r=1e3*e-n;t.ts=t.ts.map(((t,e,n)=>0===e?i:n[e-1]+a[e-1]+o[e-1]*r))}else{const a=1e3*e/n;t.ts=t.ts.map((t=>i+a*(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,n]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,n=null){const a=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,n=m.length;i<n;i++){const n=m[i].bone;n.matrixWorld.decompose(r,c,h),c.invert(),s.setFromMatrixPosition(p.matrixWorld),o.subVectors(s,r),o.applyQuaternion(c),o.normalize(),a.subVectors(e,r),a.applyQuaternion(c),a.normalize();let u=a.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,a),l.normalize(),Et.setFromAxisAngle(l,u),n.quaternion.multiply(Et),n.rotation.setFromVector3(d.setFromEuler(n.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))),n.updateMatrixWorld(!0),t=!0)}if(!t)break}n&&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=n}))}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,n=t.duration;let a=this.currentCaptions[this.currentCaptions.length-1],s=null;if(a&&Number.isFinite(a._lastEndOffsetMs)&&(s=i-a._lastEndOffsetMs),!a||function(t,e,i){const n=t.text,a=n.length,s=$t.preferBreakAfter.test(n.slice(-1)),o=$t.softBreakAfter.test(n.slice(-1));return!!t.isDisplayed||null!=i&&i>=$t.pauseBreakMs&&a>=$t.minChars||(r=a)+(r?1:0)+e.length>$t.maxChars||!!(s&&a>=$t.minChars)||!!(a>=$t.softChars&&o);var r}(a,e,s)){const t={text:e,audioOffset:i,duration:n,isDisplayed:!1,_lastEndOffsetMs:i+n,get renderText(){return(t=this.text)?` ${t.trim()} `:" ";var t}};this.currentCaptions.push(t)}else a.text=(r=e,((o=a.text).length>0&&!/\s$/.test(o)&&!/^[\s.,!?;:…)]/.test(r)?o+" "+r:o+r).replace(/\s{2,}/g," ")),a.duration+=n,a._lastEndOffsetMs=i+n;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 n=this.currentCaptions[this.currentCaptionIndex];if(!n)return void t(!1);const a=Math.max(0,n.audioOffset-(performance.now()-e));this.displayTimeoutId=setTimeout((()=>{this.displayTimeoutId=null,this.currentCaptions[this.currentCaptionIndex]?(n.isDisplayed=!0,t(!0,n.text),this.durationTimeoutId=setTimeout((()=>{this.durationTimeoutId=null,this.currentCaptionIndex++,i()}),n.duration)):t(!1)}),a)};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:n}=await this.audioReader.read();if(n)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:n}=await this.lipsyncReader.read();if(n)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(),n=e.length,a=Object.create(null);for(let o=0;o<i.length;o++){const[t,s]=i[o],r=new Float32Array(n);for(let i=0;i<n;i++){const n=e[i];r[i]=Array.isArray(n)||ArrayBuffer.isView(n)?n[t]??0:0}a[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(n),vs:a})}handleReceivedWordBoundaryEvent(t){try{this.liveCaptions.handleWordBoundaryEvent(t)}catch(s){}const e=this.speak,i=t.text,n=t.audioOffset,a=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(n),e.wdurations.push(a)):"SpeechSynthesisBoundaryType.Sentence"===t.boundaryType&&n>500&&(e.markers.push((()=>{this.talkingAvatar.lookAtCamera(500)})),e.mtimes.push(n-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(a){}try{e?.cancel?.()}catch(a){}return this.handleAudioEndOnce(i,"suppressed"),void(this.currentTurnId=null)}const n=i;this._endedTurns.delete(n??"__null__");try{this.startStreamPump(t),this.startLipsyncPump(e),this.conversationStreamActive||await this.startConversationStream()}catch(s){this.handleAudioEndOnce(n,"error"),this.currentTurnId===n&&(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()),n=t??this.currentTurnId,a=n||0===n?{turnId:n,audioStartTime:i}:{audioStartTime:i},s=()=>{try{this.avatarOrchestrator?.sendEvent("AUDIO_START",a)}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 n=()=>{this._isDisposed||(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e),this._disposers.delete(n))};return this._disposers.add(n),n}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(n){}}))}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 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`
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">
@@ -173,9 +173,9 @@ 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>`,ne=k`<span class="material-icons">mic</span>`,ae=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>`,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`
177
177
  <div class="button-container">
178
- <button @click="${t._handleStartConversationBtn}" type="button" class="btn-lg start-button" id="start_conversation_button" title="${t._t("start")}">${t._t("start")}</button>
178
+ <button @click="${t._handleStartConversationBtn}" type="button" class="btn start-button" id="start_conversation_button" title="${t._t("start")}">${t._t("start")}</button>
179
179
  </div>
180
180
  `,ye=t=>k`
181
181
  <div class="button-container">
@@ -199,7 +199,7 @@ z"/>
199
199
  <div class="conversation-buttons-overlay">
200
200
  ${(t=>k`
201
201
  <button @click="${t._handleEndConversationBtn}" type="button" title="${t._t("endConversation")}" class="secondary-button stop-button">
202
- ${ae}
202
+ ${ne}
203
203
  </button>
204
204
  `)(t)}
205
205
  ${(t=>k`
@@ -252,7 +252,7 @@ z"/>
252
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
253
  ${t._isThinking?k`<div class="lds-dual-ring small"></div>`:w}
254
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")}">${ne}</button>`:w}
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}
256
256
  </div>
257
257
  </div>
258
258
  ${t._showTyping?(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return k`
@@ -1765,6 +1765,10 @@ z"/>
1765
1765
  background: transparent;
1766
1766
  }
1767
1767
 
1768
+ .chat-input.input-blocked textarea {
1769
+ padding-left: 45px;
1770
+ }
1771
+
1768
1772
  .chat-input #chat_send_button {
1769
1773
  visibility: visible;
1770
1774
  }
@@ -1800,6 +1804,44 @@ z"/>
1800
1804
  cursor: not-allowed !important;
1801
1805
  }
1802
1806
 
1807
+ /* Loading dots animation in input */
1808
+ .chat-input .input-loading-dots {
1809
+ position: absolute;
1810
+ left: 15px;
1811
+ top: 50%;
1812
+ transform: translateY(-50%);
1813
+ display: flex;
1814
+ gap: 4px;
1815
+ pointer-events: none;
1816
+ }
1817
+
1818
+ .chat-input .input-loading-dots .dot {
1819
+ width: 6px;
1820
+ height: 6px;
1821
+ background: var(--secondary-color, #801bea);
1822
+ border-radius: 50%;
1823
+ animation: dot-bounce 1.4s infinite ease-in-out both;
1824
+ }
1825
+
1826
+ .chat-input .input-loading-dots .dot:nth-child(1) {
1827
+ animation-delay: -0.32s;
1828
+ }
1829
+
1830
+ .chat-input .input-loading-dots .dot:nth-child(2) {
1831
+ animation-delay: -0.16s;
1832
+ }
1833
+
1834
+ @keyframes dot-bounce {
1835
+ 0%, 80%, 100% {
1836
+ transform: scale(0.6);
1837
+ opacity: 0.5;
1838
+ }
1839
+ 40% {
1840
+ transform: scale(1);
1841
+ opacity: 1;
1842
+ }
1843
+ }
1844
+
1803
1845
  @media (max-width: 768px) {
1804
1846
  .chatbot .chatbox {
1805
1847
  flex-grow: 1;
@@ -2057,7 +2099,7 @@ z"/>
2057
2099
  margin-top: 0;
2058
2100
  padding-top: 0.25rem;
2059
2101
  }
2060
- `,Ae="en",Ce={en:{start:"Start",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",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",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",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,n){t.addEventListener(e,i,n);const a=()=>t.removeEventListener(e,i,n);return this._domDisposers.push(a),a}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(n){}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),n=Ce[i]?.[e];return void 0!==n?n: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],n=["ar","he","fa","ur"].includes(i)?"rtl":"ltr";this.dir!==n?(this.dir=n,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(n){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(n){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 n=!1;const a=(t,e)=>{this[t]!==e&&(this[t]=e,n=!0)};try{a("_isConversationInProgress",!!e.hasTag?.("conversation_in_progress")),a("_isConversationPaused",!!e.hasTag?.("conversation_paused")),a("_isSpeaking",!!e.hasTag?.("speaking")),a("_isListening",!!e.hasTag?.("listening")),a("_isThinking",!!e.hasTag?.("thinking")),a("_inputsBlocked",!!e.hasTag?.("inputs_blocked")),a("_isConversationResumable",!!e.matches?.("lifecycle.conversation.resumable")),a("_isInitializingConversation",!(!e.matches?.("lifecycle.conversation.initializingConversation")&&!e.matches?.("lifecycle.conversation.initializing"))),a("_isConversationTimedOut",!!e.matches?.("lifecycle.conversation.timedOut")),a("_isStartingConversation",!(!e.matches?.("lifecycle.conversation.inProgress.startingConversation")&&!e.matches?.("lifecycle.conversation.starting"))),a("_isConversationStopped",!!e.matches?.("lifecycle.conversation.stopped")),a("_isDisconnected",!!e.matches?.("connection.disconnected")),a("_isFailed",!(!e.matches?.("lifecycle.init.failed")&&!e.matches?.("lifecycle.failed")))}catch(s){}try{const t=i?.matches?.("lifecycle.conversation.resumable"),n=e.matches?.("lifecycle.conversation.resumable");!n||t||this._showConfirmationDialog||this.toggler&&!1===this._showChatbot||this._showResumeConversationDialog()}catch(s){}(n||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("uiLanguage")&&(this._applyUiLanguage(),this._applyDirectionFromUiLanguage()),t.has("barge_in")&&this.__postUpdateQueue.push((()=>this._applyBargeInPreference())),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`
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`
2061
2103
  <div id="chatbot-container" class="${(t=this)._showChatbot||!t.toggler?"show-chatbot":""}${t.toggler?"":" embedded"}">
2062
2104
  ${t.toggler?(t=>k`
2063
2105
  <button id="chatbot-toggler" @click="${t._handleToggleChatbot}" aria-label="${t._t("toggleChatbot")}">
@@ -2065,7 +2107,7 @@ z"/>
2065
2107
  ${le}
2066
2108
  </button>
2067
2109
  `)(t):w}
2068
- ${t._stateTestMode?(t=>{const e=t._actorSnapshot,i="function"==typeof t.initStatus?t.initStatus():"UNKNOWN",n=!!t._isStartingConversation,a=!!t._isInitializingConversation,s=!!t._isConversationInProgress,o=!!t._isConversationPaused,r=!!t._isConversationResumable,c=!!t._isConversationStopped,h=!!t._isFailed,l=h?"FAILED":n?"STARTING":a?"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":n?"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 n=[];for(const a of Object.keys(t))n.push(...i(t[a],e.concat(a)));return n}return[]};try{return i(e).join(" | ")}catch(n){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`
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`
2069
2111
  <div class="test-mode-states">
2070
2112
  <div><b>FSM</b>: ${x||"(no state)"}</div>
2071
2113
  <div><b>UI</b>: Chatbot Visible=${String(S)}, Mode (UI → FSM)=${A} → ${C}</div>
@@ -2108,14 +2150,14 @@ z"/>
2108
2150
  <div class="menu-icon" @click="${t._handleToggleMenu}">
2109
2151
  ${t._showMenu?le:de}
2110
2152
  </div>
2111
- ${(t=>{const e=t._isConversationInProgress,i=t._isStartingConversation||t._isInitializingConversation,n=t._isConversationStopped,a=t._isConversationResumable;return k`
2153
+ ${(t=>{const e=t._isConversationInProgress,i=t._isStartingConversation||t._isInitializingConversation,a=t._isConversationStopped,n=t._isConversationResumable;return k`
2112
2154
  ${t._showMenu?k`<div class="menu-backdrop" @click="${t._handleToggleMenu}"></div>`:null}
2113
2155
  <div id="menu" class="${t._showMenu?"show":"hide"}">
2114
2156
  <div class="menu-items" >
2115
2157
  <div class="conversation-details">
2116
2158
  <span class="conversation-status" title="${t._t("conversationStatus")}">${e?k`<small>${t._t("conversationInProgress")}</small>`:k`<small>${t._t("conversationStopped")}</small>`}</span>
2117
2159
  </div>
2118
- <div ?hidden=${!n||e||i||a}>
2160
+ <div ?hidden=${!a||e||i||n}>
2119
2161
  <a type="button" @click="${t._handleStartConversationMenuBtn}" href="#">${t._t("startConversation")}</a>
2120
2162
  </div>
2121
2163
  <div ?hidden=${!e}>
@@ -2186,7 +2228,7 @@ z"/>
2186
2228
  </div>
2187
2229
  `:w)(t)}
2188
2230
  ${ve(t)}
2189
- ${t.compact?w:(t=>{let e,i="";const n=t._isStartingConversation,a=t._isInitializingConversation,s=t._isConversationInProgress,o=t._isConversationPaused,r=t._isConversationResumable;return n||a?(e=k`
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`
2190
2232
  <div class="chat-start-container center-aligned">
2191
2233
  <div class="lds-dual-ring small"></div>
2192
2234
  </div>`,i="center-aligned"):r?(e=k`
@@ -2194,18 +2236,25 @@ z"/>
2194
2236
  <small>${t._t("previousConversationFound")}</small>
2195
2237
  </div>`,i="center-aligned"):s||o?e=k`
2196
2238
  <ul class="chatbox">
2197
- ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:n})=>{const a=Zt(i)?"rtl":"ltr";return k`
2239
+ ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:a})=>{const n=Zt(i)?"rtl":"ltr";return k`
2198
2240
  <li class="chat ${e}">
2199
2241
  ${"assistant"===e?he:""}
2200
- <div style="direction: ${a}; text-align: ${"rtl"===a?"right":"left"}" class="message-container">
2242
+ <div style="direction: ${n}; text-align: ${"rtl"===n?"right":"left"}" class="message-container">
2201
2243
  <p class="message-bubble" style="word-wrap: break-word; word-break: break-word;">${i}</p>
2202
- <small class="message-time ${"rtl"===a?"time-left":"time-right"}">${n}</small>
2244
+ <small class="message-time ${"rtl"===n?"time-left":"time-right"}">${a}</small>
2203
2245
  </div>
2204
2246
  </li>
2205
2247
  `})(0,t))):(t=>k`<h3 id="no-msgs-head">${t._t("noMessagesYet")}</h3>`)(t)}
2206
2248
  </ul>
2207
2249
  ${(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return k`
2208
2250
  <div class="chat-input ${t._inputsBlocked?"input-blocked":""}">
2251
+ ${t._inputsBlocked?k`
2252
+ <div class="input-loading-dots">
2253
+ <div class="dot"></div>
2254
+ <div class="dot"></div>
2255
+ <div class="dot"></div>
2256
+ </div>
2257
+ `:w}
2209
2258
  <textarea
2210
2259
  @keyup="${t._handleChatKeyUp}"
2211
2260
  type="text"
@@ -2247,11 +2296,11 @@ z"/>
2247
2296
  </div>
2248
2297
  `:w)(t)}
2249
2298
  </div>
2250
- ${"mobile"===t.target_app||t.compact?w:k`
2299
+ ${"mobile"===t.target_app||t.compact?w:(t=>{const e=t.brand_name||"Sentifyd",i=!!t.brand_name;return k`
2251
2300
  <footer>
2252
- <small><a href="https://sentifyd.io" target="_blank">Sentifyd</a></small>
2301
+ ${i?k`<small>${e}</small>`:k`<small><a href="https://sentifyd.io" target="_blank">Sentifyd</a></small>`}
2253
2302
  </footer>
2254
- `}
2303
+ `})(t)}
2255
2304
  ${(t=>t._showLastMessage?k`
2256
2305
  <div class="last-message" @click="${t._closeLastMessage}">
2257
2306
  <div class="last-message-content">
@@ -2360,4 +2409,4 @@ z"/>
2360
2409
  </div>`:w)(t)}
2361
2410
  </div>
2362
2411
  </div>
2363
- `;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",n=this.shadowRoot.querySelector(i);n&&!n.disabled&&this._isElementFocusable(n)&&document.activeElement!==n&&n.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:n,height:a}=i.contentRect||{};if((!this.toggler||!1!==this._showChatbot)&&n>120&&a>120&&(E.dom.canvasWidth=Math.round(n),E.dom.canvasHeight=Math.round(a),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,n=t?Math.round(t.offsetTop):0,a=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",`${n}px`)}catch(u){}}else if(this.toggler)if(a){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${n}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?.()||{},n=Math.round(t.width||this.offsetWidth||this.clientWidth||e),a=Math.round(t.height||this.offsetHeight||this.clientHeight||i),r=Math.max(120,c??n),u=Math.max(120,h??(E.dom.canvasHeight||a));s=r;const p=a>=120?a: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 nt.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"}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(n){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="",n=!1,a=!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),a?(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),n&&(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),n=this._speakingAvatar?.sessionData&&null===this._speakingAvatar.sessionData.trainingId;let a=null;a=i?e?.matches?.("lifecycle.init.initializing")?"initializing":e?.matches?.("lifecycle.init.failed")?"failed":n?"invalidConfiguration":e?.matches?.("connection.connected")?"connected":"recovering":"invalidConfiguration","initializing"!==a||"connected"!==this._statusBarStatus&&"recovering"!==this._statusBarStatus||(a=this._statusBarStatus),this._statusBarStatus!==a&&(this._statusBarStatus=a),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,nt.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(){this.isInitialized()&&(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 nt.getItem(this._consentStorageKey())}catch(t){return!1}}async _handleConsentAccept(){try{await nt.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 nt.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,n)=>{const a=(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`;n.forEach((t=>{const{speaker:n,messageText:a,time:o}=t;s+=`${"user"===n?i||"User":"assistant"===n?e:null}: ${a} [${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}-${a}.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,n,a){this._dialogMessage=t,this._confirmDialog=e,this._cancelDialog=i,this._confirmButtonLabel=n??this._t("confirm"),this._cancelButtonLabel=a??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){nt.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 n=t[e];if(null!=n&&""!==n){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();i.setAttribute(t,"boolean"==typeof n?String(n):n)}})),t.customAttributes&&Object.keys(t.customAttributes).forEach((e=>{const n=t.customAttributes[e];null!=n&&""!==n&&i.setAttribute(e,String(n))})),e.appendChild(i),i}nt.setInstance(Ee),"undefined"!=typeof window&&De();export{Me as SentifydBot,He as createSentifydBot,Pe as initializeStorage,De as registerSentifydBot};
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};