@streamoji/avatar-widget 0.3.3 → 0.3.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.
- package/dist/avatar-widget.cjs +5 -5
- package/dist/avatar-widget.js +619 -606
- package/dist/avatar-widget.umd.js +157 -157
- package/dist/avatar-widget.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/avatar-widget.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),Ge=require("@react-three/drei"),ct=require("@react-three/fiber"),e=require("react"),qt=require("three"),Jt=require("three/examples/jsm/loaders/GLTFLoader.js");function Gt(l){const b=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const g in l)if(g!=="default"){const m=Object.getOwnPropertyDescriptor(l,g);Object.defineProperty(b,g,m.get?m:{enumerable:!0,get:()=>l[g]})}}return b.default=l,Object.freeze(b)}const Ue=Gt(qt),at="https://ai.streamoji.com",B=(...l)=>{},zt=(...l)=>{},kt=({analyser:l})=>{const b=e.useRef(null),g=e.useRef(null);return e.useEffect(()=>{const m=b.current;if(!m)return;const _=m.getContext("2d",{alpha:!0});if(!_)return;let C,W=null;l&&(l.fftSize=128,W=new Uint8Array(l.frequencyBinCount));const le=()=>{C=requestAnimationFrame(le),(m.width!==m.offsetWidth||m.height!==m.offsetHeight)&&(m.width=m.offsetWidth,m.height=m.offsetHeight);const Y=m.width,O=m.height;if(Y===0||O===0)return;const de=O/2;_.clearRect(0,0,Y,O),_.fillStyle="#1e293b";const T=2,R=T+2,A=Y*.95,F=Math.floor(A/R);(!g.current||g.current.length!==F)&&(g.current=new Float32Array(F).fill(2));const me=F*R,v=(Y-me)/2;l&&W&&l.getByteFrequencyData(W);const _e=W?W.length:0,q=Math.floor(_e*.7)/F,ie=new Float32Array(F);for(let I=0;I<F;I++){let j=0;if(W&&q>0){const ee=Math.floor(I*q),U=Math.floor((I+1)*q);for(let x=ee;x<U;x++){const y=W[x]||0;y>j&&(j=y)}}j<10&&(j=0);const V=j/255,D=j>0?Math.max(2,Math.pow(V,1.4)*O*.25):2;ie[I]=D}for(let I=0;I<F;I++){const j=F-1-I,V=Math.max(ie[I],ie[j]),D=g.current[I]+(V-g.current[I])*.3;g.current[I]=D;const ee=v+I*R,U=de-D/2;_.beginPath(),_.roundRect?_.roundRect(ee,U,T,D,4):_.fillRect(ee,U,T,D),_.fill()}};return le(),()=>{cancelAnimationFrame(C)}},[l]),a.jsx("canvas",{ref:b,style:{width:"100%",height:"100%",display:"block"}})},Yt="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",Et="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";async function Qt(l){const b=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(l));return Array.from(new Uint8Array(b)).map(g=>g.toString(16).padStart(2,"0")).join("")}function Xt(l){const[b,g]=e.useState(null);return e.useEffect(()=>{if(!l){g(null);return}let m=!1;return Qt(l).then(_=>{if(m)return;const C=`${Yt}/${_}.glb`;fetch(C,{method:"HEAD"}).then(W=>{m||g(W.ok?C:Et)}).catch(()=>{m||g(Et)})}),()=>{m=!0}},[l]),b}const Kt=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],Zt=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],en=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],tn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],nn={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},rn=[-.45,1.9,.1],sn={browInnerUp:.2},ot=.18,an=1,Lt="__branding__",Je={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.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},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},on=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],cn={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function un(l){if(!l)return[{v:"sil",w:1}];const b=l.toLowerCase();return cn[b]??[{v:"sil",w:1}]}function ln({target:l}){const{camera:b}=ct.useThree();return e.useEffect(()=>{b.lookAt(...l)},[b,l]),null}function z(l,b,g){if(!l||!l.morphTargetDictionary)return;const m=l,_=m.morphTargetDictionary,C=m.morphTargetInfluences;if(C)for(const W in _)W.toLowerCase()===b.toLowerCase()&&(C[_[W]]=g)}function At(l,b=.97){if(!l)return;const g=l;if(g.morphTargetInfluences)for(let m=0;m<g.morphTargetInfluences.length;m++)g.morphTargetInfluences[m]*=b}const dn=e.memo(({avatarUrl:l,isPlayingRef:b,visemeQueueRef:g,audioContextRef:m,responseAudioStartTimeRef:_,adjustments:C,mood:W,expression:le,agentResponse:Y,isSpeaking:O,nextStartTimeRef:de,stopPlayback:T,setIsSpeaking:S,expressionUrl:R,onExpressionFinished:A,isNudgeResponse:F,avatarGender:me})=>{const{scene:v}=Ge.useGLTF(l),_e=me==="female"?Zt:Kt,Ce=Ge.useGLTF(_e),q=e.useMemo(()=>Ce.flatMap(d=>d.animations),[Ce]),ie=Ge.useGLTF(tn),I=e.useMemo(()=>ie.flatMap(d=>d.animations),[ie]),j=e.useRef(null),V=e.useRef(null),D=e.useRef(null),ee=e.useRef([]),[U]=e.useState(()=>new Ue.AnimationMixer(v)),x=e.useRef({}),y=e.useRef(null),we=e.useRef(0),ae=e.useRef(!1),Pe=e.useRef(0),te=e.useRef(null);e.useEffect(()=>{if(!(!q||!v)){if(q.forEach((d,f)=>{const o=`idle_${f}`;if(!x.current[o]){const s=U.clipAction(d,v);s.name=o,s.setLoop(Ue.LoopOnce,1),s.clampWhenFinished=!0,x.current[o]=s}}),I.forEach((d,f)=>{const o=`talk_${f}`;if(!x.current[o]){const s=U.clipAction(d,v);s.name=o,s.setLoop(Ue.LoopOnce,1),s.clampWhenFinished=!0,x.current[o]=s}}),q.length>0){const d=x.current.idle_0,f=y.current&&U.existingAction(y.current.getClip());d&&!f&&(d.reset().fadeIn(.5).play(),y.current=d)}return()=>{U.stopAllAction(),x.current={},y.current=null}}},[q,I,v,U]);const Se=e.useRef("");e.useEffect(()=>{if(!R||!v||R===Se.current)return;Se.current=R,te.current=R,new Jt.GLTFLoader().load(R,f=>{if(f.animations&&f.animations.length>0){const o=f.animations[0],s=U.clipAction(o,v);if(s.name=`EXPR_${R}`,s.setLoop(Ue.LoopOnce,1),s.clampWhenFinished=!0,x.current[`EXPR_${R}`]=s,O&&te.current===R){const p=y.current;s.reset().fadeIn(.3).play(),p&&p!==s&&p.crossFadeTo(s,.3,!0),y.current=s,te.current=null}}},void 0,f=>{console.error(`[ANIMATION] Failed to load ${R}`,f)})},[R,v,U,O]),e.useEffect(()=>{const d=f=>{const o=f.action,s=o.name||"";if(s.startsWith("idle_")){const J=(parseInt(s.split("_")[1])+1)%q.length,Q=x.current[`idle_${J}`];Q&&(Q.reset().fadeIn(.5).play(),o.crossFadeTo(Q,.5,!0),y.current=Q)}else if(s.startsWith("EXPR_")){if(O){const p=x.current.talk_0;p&&(p.reset().fadeIn(.5).play(),o.crossFadeTo(p,.5,!0),y.current=p)}else{const p=x.current.idle_0;p&&(p.reset().fadeIn(.5).play(),o.crossFadeTo(p,.5,!0),y.current=p)}A&&A()}else if(s.startsWith("talk_"))if(O&&!F){const J=(parseInt(s.split("_")[1])+1)%I.length,Q=x.current[`talk_${J}`];Q&&(Q.reset().fadeIn(.3).play(),o.crossFadeTo(Q,.3,!0),y.current=Q)}else{const p=x.current.idle_0;p&&(p.reset().fadeIn(.5).play(),o.crossFadeTo(p,.5,!0),y.current=p)}};return U.addEventListener("finished",d),()=>U.removeEventListener("finished",d)},[U,q,I,O,F,A]),e.useEffect(()=>{if(O&&v){const d=y.current,f=d?.name||"";if(f.startsWith("idle_")||f.startsWith("talk_")||f===""){const o=te.current;if(o){const s=x.current[`EXPR_${o}`];if(s){s.reset().fadeIn(.3).play(),d&&d!==s&&d.crossFadeTo(s,.3,!0),y.current=s,te.current=null;return}}if(f.startsWith("idle_")||f===""){const s=x.current.talk_0;s&&(s.reset().fadeIn(.5).play(),d&&d.crossFadeTo(s,.5,!0),y.current=s)}}}else if(!O&&v){const d=y.current,f=d?.name||"";if(f.startsWith("talk_")||f.startsWith("EXPR_")){const o=x.current.idle_0;o&&(o.reset().fadeIn(.5).play(),d&&d.crossFadeTo(o,.5,!0),y.current=o)}}},[O,v,R]),e.useEffect(()=>{if(!v)return;v.traverse(o=>{if(o.isMesh&&o.morphTargetDictionary){const s=o.name.toLowerCase();(s.includes("head")||s.includes("avatar"))&&(V.current=o,B(`[ANIMATION] Found head mesh: ${o.name}`)),s.includes("teeth")&&(D.current=o,B(`[ANIMATION] Found teeth mesh: ${o.name}`))}});const d=V.current?.morphTargetDictionary;d&&Object.keys(d).filter(o=>o.toLowerCase().includes("brow"));const f=[];v.traverse(o=>{if(o.isMesh){const p=o.morphTargetDictionary;p&&Object.keys(p).some(J=>J.toLowerCase().includes("brow"))&&f.push(o)}}),ee.current=f,f.length>0&&B("[ANIMATION] Meshes with brow morphs:",f.length)},[v]);const ve=(d,f=1)=>{const o=`viseme_${d}`.toLowerCase(),s=on.find(p=>p.key.toLowerCase()===o);if(s)for(const p in s.mix){const J=s.mix[p]*f;z(V.current,p,J),z(D.current,p,J)}},Oe=d=>{const f=Je[d]??Je.neutral;for(const o in f)z(V.current,o,f[o]),z(D.current,o,f[o])};return ct.useFrame((d,f)=>{const o=Math.pow(.88,60*f);At(V.current,o),At(D.current,o),Oe(W);const s=d.clock.elapsedTime;let p=0;if(Math.floor(s)%5===0&&Math.floor((s-f)%5)!==0){let H=null;v.traverse(Z=>{Z.name.toLowerCase().includes("hips")&&(H=Z)});const ne=H?`Hips Y: ${H.position.y.toFixed(4)}`:"Hips not found";B(`[ANIMATION] Mixer Time: ${U.time.toFixed(2)}, ${ne}`)}if(U.update(f),s>we.current&&!ae.current&&(ae.current=!0,Pe.current=s),ae.current){const H=O?.2:.3,ne=(s-Pe.current)/H;if(ne>=1){ae.current=!1;const Z=O?1:2.5;we.current=s+Z}else{const Z=ne<.5?ne*2:(1-ne)*2;z(V.current,"eyeBlinkLeft",Z),z(V.current,"eyeBlinkRight",Z),z(D.current,"eyeBlinkLeft",Z),z(D.current,"eyeBlinkRight",Z),p=Z*sn.browInnerUp}}const J=Je[W]??Je.neutral,Q=J.browInnerUp??0,ze=J.browOuterUpLeft??0,Ye=J.browOuterUpRight??0,Ae=s*an,Qe=ot*Math.sin(Ae),xe=ot*.7*Math.sin(Ae+.7),K=ot*.7*Math.sin(Ae+1.3),ye=H=>Math.max(0,Math.min(1,H)),pe=ye(Q+Qe),ge=ye(ze+xe),Re=ye(Ye+K),De=ye(pe+p);if(z(V.current,"browInnerUp",De),z(D.current,"browInnerUp",De),z(V.current,"browOuterUpLeft",ge),z(D.current,"browOuterUpLeft",ge),z(V.current,"browOuterUpRight",Re),z(D.current,"browOuterUpRight",Re),j.current){const H=b.current?0:C.rotation[1];j.current.rotation.y=Ue.MathUtils.lerp(j.current.rotation.y,H,.1),j.current.position.set(...C.position),j.current.scale.setScalar(C.scale),j.current.rotation.x=C.rotation[0],j.current.rotation.z=C.rotation[2]}if(b.current&&m.current){const H=m.current.currentTime,Be=(H-_.current)*1e3- -150;for(let ke=0;ke<g.current.length;ke++){const G=g.current[ke];Be>=G.vtime&&Be<G.vtime+G.vduration&&ve(G.viseme,G.weight??1)}H>de.current+.5&&(T(),S(!1))}}),a.jsx("group",{ref:j,children:a.jsx("primitive",{object:v})})});function fn(l){return l?l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():""}const hn=({token:l,agentToken:b,onNavigationRequested:g,avatarGender:m,presetUserDetails:_}={})=>{const C=l??b??"",W=Xt(C||void 0),[le,Y]=e.useState(""),[O,de]=e.useState(""),[T,S]=e.useState("Ready"),[R,A]=e.useState(!1),[F,me]=e.useState(!1),[v,_e]=e.useState([]),[Ce,q]=e.useState(""),ie=e.useRef(null),[I,j]=e.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);e.useEffect(()=>{const t=window.matchMedia("(max-width: 480px)"),n=()=>j(t.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const V=I?80:600,D=e.useRef(!1),ee=e.useRef([]),U=e.useRef(0),x=e.useRef(!1),y=e.useRef([]),we=e.useRef(null),ae=e.useRef([]);e.useRef([]);const Pe=e.useRef([]),te=e.useRef(0),Se=e.useRef(0),ve=e.useRef(0),Oe=e.useRef(0),d=e.useRef(!1),[f,o]=e.useState(null),s=e.useRef(null),[p,J]=e.useState("neutral"),[Q,ze]=e.useState(""),[Ye,Ae]=e.useState(""),[Qe,xe]=e.useState("Chat with us"),[K,ye]=e.useState(null),[pe,ge]=e.useState("hidden"),[Re,De]=e.useState(""),H=e.useRef(null),ne=e.useRef(pe);ne.current=pe;const[Z,Be]=e.useState(null),ke=e.useRef(null),G=e.useRef(null),[Ne,ut]=e.useState(!1),lt=e.useRef(null),[oe,We]=e.useState("hidden"),[dt,Tt]=e.useState(""),Xe=e.useRef(oe);Xe.current=oe;const fe=e.useRef(""),Te=e.useRef(!1),Ie=e.useRef(""),ft=e.useRef(Date.now()),Ke=e.useRef([]),Fe=e.useRef(!1),[Ze,je]=e.useState(!1),[ht,mt]=e.useState(!1),be=e.useRef(null),Me=e.useMemo(()=>Ne?"Try again":T==="Busy"?"Busy":T==="Thinking..."||T==="Processing Voice..."?T:K!=null&&K!==""&&K!=="none"&&K!=="<none>"?`Enter ${fn(K)}`:oe!=="hidden"||!ht?null:Lt,[T,K,Ne,oe,ht]),pt=!Ne&&T!=="Busy"&&T!=="Thinking..."&&T!=="Processing Voice..."&&(K==null||K===""||K==="none"||K==="<none>");e.useEffect(()=>{if(oe!=="hidden"||!pt){mt(!1),be.current!=null&&(clearTimeout(be.current),be.current=null);return}return be.current=setTimeout(()=>{be.current=null,mt(!0)},400),()=>{be.current!=null&&(clearTimeout(be.current),be.current=null)}},[oe,pt]);const Ve=Me!=null&&Me!=="";e.useEffect(()=>{const t=ne.current;if(!(t==="exiting"||t==="entering")){if(t==="hidden"){Ve&&(De(Me??""),ge("entering"));return}t==="visible"&&(!Ve||Me!==Re)&&(H.current=Ve?Me:null,ge("exiting"))}},[Ve,Me,pe,Re]),e.useEffect(()=>{if(T!=="Busy"){G.current!=null&&(clearTimeout(G.current),G.current=null);return}return G.current=setTimeout(()=>{G.current=null,S("Ready"),ut(!0)},12e3),()=>{G.current!=null&&(clearTimeout(G.current),G.current=null)}},[T]),e.useEffect(()=>{if(!Ne)return;const t=setTimeout(()=>ut(!1),2500);return()=>clearTimeout(t)},[Ne]);const It=e.useCallback(()=>{const t=ne.current;if(t==="exiting"){ge("hidden");const n=H.current;H.current=null,n!=null&&n!==""&&(De(n),ge("entering"))}else t==="entering"&&ge("visible")},[]),Mt=t=>{if(!t)return;if(t.mood!=null){const r=String(t.mood).toLowerCase();J(r)}if(t.expression!=null){const r=String(t.expression).trim();ze(r);const u=en.find(h=>h.name.toLowerCase()===r.toLowerCase());B(`[STREAM] Animation match for "${r}": ${u?u.name:"NONE"}`),Ae(u?.url??"")}if(t.navigation!=null){const r=String(t.navigation).trim();r!==""&&(g?g(r):window.open(r,"_blank"))}const n=t.ask_for||t.lead_capture?.ask_for,i=n?String(n).trim().toLowerCase():"",c=i==="none"||i==="<none>";if(n&&!c){const r=i;if(_&&(r==="email"&&_.email||r==="name"&&_.name||r==="phone"&&_.phone))return;ye(r||null),xe(r==="email"?"Enter your email":r==="name"?"Enter your name":r==="phone"?"Enter your phone number":"Chat with us")}else(c||t.ask_for===null||t.lead_capture&&t.lead_capture.ask_for===null||t.ask_for==="none")&&(ye(null),Qe!=="Chat with us"&&xe("Chat with us"));t.collected,t.valid},Ct=t=>{const n=t.trim();if(!n)return null;if(n.startsWith("{"))try{return JSON.parse(n)}catch{return null}if(n.includes(":")){const i=n.split(":"),c=i[0].trim().toLowerCase(),r=i.slice(1).join(":").trim();return{[c]:r}}return null},Ot=e.useCallback(()=>{},[]),gt=t=>{if(Te.current)t==="§"?Te.current=!1:(Ie.current+=t,de(n=>n+t));else if(t==="§"){Te.current=!0;return}else for(fe.current+=t;fe.current.includes(`
|
|
2
|
-
`);){const n=
|
|
3
|
-
`),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),Ye=require("@react-three/drei"),ct=require("@react-three/fiber"),e=require("react"),Gt=require("three"),zt=require("three/examples/jsm/loaders/GLTFLoader.js");function Yt(u){const _=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(u){for(const g in u)if(g!=="default"){const m=Object.getOwnPropertyDescriptor(u,g);Object.defineProperty(_,g,m.get?m:{enumerable:!0,get:()=>u[g]})}}return _.default=u,Object.freeze(_)}const Pe=Yt(Gt),at="https://ai.streamoji.com",W=(...u)=>{},Qt=(...u)=>{},kt=({analyser:u})=>{const _=e.useRef(null),g=e.useRef(null);return e.useEffect(()=>{const m=_.current;if(!m)return;const w=m.getContext("2d",{alpha:!0});if(!w)return;let C,V=null;u&&(u.fftSize=128,V=new Uint8Array(u.frequencyBinCount));const ue=()=>{C=requestAnimationFrame(ue),(m.width!==m.offsetWidth||m.height!==m.offsetHeight)&&(m.width=m.offsetWidth,m.height=m.offsetHeight);const Y=m.width,D=m.height;if(Y===0||D===0)return;const le=D/2;w.clearRect(0,0,Y,D),w.fillStyle="#1e293b";const A=2,y=A+2,E=Y*.95,N=Math.floor(E/y);(!g.current||g.current.length!==N)&&(g.current=new Float32Array(N).fill(2));const de=N*y,x=(Y-de)/2;u&&V&&u.getByteFrequencyData(V);const ve=V?V.length:0,G=Math.floor(ve*.7)/N,fe=new Float32Array(N);for(let j=0;j<N;j++){let $=0;if(V&&G>0){const U=Math.floor(j*G),pe=Math.floor((j+1)*G);for(let I=U;I<pe;I++){const R=V[I]||0;R>$&&($=R)}}$<10&&($=0);const J=$/255,L=$>0?Math.max(2,Math.pow(J,1.4)*D*.25):2;fe[j]=L}for(let j=0;j<N;j++){const $=N-1-j,J=Math.max(fe[j],fe[$]),L=g.current[j]+(J-g.current[j])*.3;g.current[j]=L;const U=x+j*y,pe=le-L/2;w.beginPath(),w.roundRect?w.roundRect(U,pe,A,L,4):w.fillRect(U,pe,A,L),w.fill()}};return ue(),()=>{cancelAnimationFrame(C)}},[u]),i.jsx("canvas",{ref:_,style:{width:"100%",height:"100%",display:"block"}})},Kt="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",Tt="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";async function Xt(u){const _=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return Array.from(new Uint8Array(_)).map(g=>g.toString(16).padStart(2,"0")).join("")}function Zt(u){const[_,g]=e.useState(null);return e.useEffect(()=>{if(!u){g(null);return}let m=!1;return Xt(u).then(w=>{if(m)return;const C=`${Kt}/${w}.glb`;fetch(C,{method:"HEAD"}).then(V=>{m||g(V.ok?C:Tt)}).catch(()=>{m||g(Tt)})}),()=>{m=!0}},[u]),_}const en=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],tn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],nn=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],rn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"],sn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"],an={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},on=[-.45,1.9,.1],cn={browInnerUp:.2},ot=.18,un=1,Et="__branding__",ze={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.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},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},ln=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],dn={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function fn(u){if(!u)return[{v:"sil",w:1}];const _=u.toLowerCase();return dn[_]??[{v:"sil",w:1}]}function hn({target:u}){const{camera:_}=ct.useThree();return e.useEffect(()=>{_.lookAt(...u)},[_,u]),null}function z(u,_,g){if(!u||!u.morphTargetDictionary)return;const m=u,w=m.morphTargetDictionary,C=m.morphTargetInfluences;if(C)for(const V in w)V.toLowerCase()===_.toLowerCase()&&(C[w[V]]=g)}function At(u,_=.97){if(!u)return;const g=u;if(g.morphTargetInfluences)for(let m=0;m<g.morphTargetInfluences.length;m++)g.morphTargetInfluences[m]*=_}const mn=e.memo(({avatarUrl:u,isPlayingRef:_,visemeQueueRef:g,audioContextRef:m,responseAudioStartTimeRef:w,adjustments:C,mood:V,expression:ue,agentResponse:Y,isSpeaking:D,nextStartTimeRef:le,stopPlayback:A,setIsSpeaking:v,expressionUrl:y,onExpressionFinished:E,isNudgeResponse:N,avatarGender:de})=>{const{scene:x}=Ye.useGLTF(u),ve=de==="female"?tn:en,De=Ye.useGLTF(ve),G=e.useMemo(()=>De.flatMap(f=>f.animations),[De]),fe=de==="female"?sn:rn,j=Ye.useGLTF(fe),$=e.useMemo(()=>j.flatMap(f=>f.animations),[j]),J=e.useRef(null),L=e.useRef(null),U=e.useRef(null),pe=e.useRef([]),[I]=e.useState(()=>new Pe.AnimationMixer(x)),R=e.useRef({}),M=e.useRef(null),ge=e.useRef(0),Ae=e.useRef(!1),be=e.useRef(0),ie=e.useRef(null);e.useEffect(()=>{if(!(!G||!x)){if(G.forEach((f,d)=>{const a=`idle_${d}`;if(!R.current[a]){const o=I.clipAction(f,x);o.name=a,o.setLoop(Pe.LoopOnce,1),o.clampWhenFinished=!0,R.current[a]=o}}),$.forEach((f,d)=>{const a=`talk_${d}`;if(!R.current[a]){const o=I.clipAction(f,x);o.name=a,o.setLoop(Pe.LoopOnce,1),o.clampWhenFinished=!0,R.current[a]=o}}),G.length>0){const f=R.current.idle_0,d=M.current&&I.existingAction(M.current.getClip());f&&!d&&(f.reset().fadeIn(.5).play(),M.current=f)}return()=>{I.stopAllAction(),R.current={},M.current=null}}},[G,$,x,I]);const _e=e.useRef("");e.useEffect(()=>{if(!y||!x||y===_e.current)return;_e.current=y,ie.current=y,new zt.GLTFLoader().load(y,d=>{if(d.animations&&d.animations.length>0){const a=d.animations[0],o=I.clipAction(a,x);if(o.name=`EXPR_${y}`,o.setLoop(Pe.LoopOnce,1),o.clampWhenFinished=!0,R.current[`EXPR_${y}`]=o,D&&ie.current===y){const h=M.current;o.reset().fadeIn(.3).play(),h&&h!==o&&h.crossFadeTo(o,.3,!0),M.current=o,ie.current=null}}},void 0,d=>{console.error(`[ANIMATION] Failed to load ${y}`,d)})},[y,x,I,D]),e.useEffect(()=>{const f=d=>{const a=d.action,o=a.name||"";if(o.startsWith("idle_")){const B=(parseInt(o.split("_")[1])+1)%G.length,Q=R.current[`idle_${B}`];Q&&(Q.reset().fadeIn(.5).play(),a.crossFadeTo(Q,.5,!0),M.current=Q)}else if(o.startsWith("EXPR_")){if(D){const h=Math.floor(Math.random()*$.length),B=R.current[`talk_${h}`];B&&(B.reset().fadeIn(.5).play(),a.crossFadeTo(B,.5,!0),M.current=B)}else{const h=R.current.idle_0;h&&(h.reset().fadeIn(.5).play(),a.crossFadeTo(h,.5,!0),M.current=h)}E&&E()}else if(o.startsWith("talk_"))if(D&&!N){const B=(parseInt(o.split("_")[1])+1)%$.length,Q=R.current[`talk_${B}`];Q&&(Q.reset().fadeIn(.3).play(),a.crossFadeTo(Q,.3,!0),M.current=Q)}else{const h=R.current.idle_0;h&&(h.reset().fadeIn(.5).play(),a.crossFadeTo(h,.5,!0),M.current=h)}};return I.addEventListener("finished",f),()=>I.removeEventListener("finished",f)},[I,G,$,D,N,E]),e.useEffect(()=>{if(D&&x){const f=M.current,d=f?.name||"";if(d.startsWith("idle_")||d.startsWith("talk_")||d===""){const a=ie.current;if(a){const o=R.current[`EXPR_${a}`];if(o){o.reset().fadeIn(.3).play(),f&&f!==o&&f.crossFadeTo(o,.3,!0),M.current=o,ie.current=null;return}}if(d.startsWith("idle_")||d===""){const o=Math.floor(Math.random()*$.length),h=R.current[`talk_${o}`];h&&(h.reset().fadeIn(.5).play(),f&&f.crossFadeTo(h,.5,!0),M.current=h)}}}else if(!D&&x){const f=M.current,d=f?.name||"";if(d.startsWith("talk_")||d.startsWith("EXPR_")){const a=R.current.idle_0;a&&(a.reset().fadeIn(.5).play(),f&&f.crossFadeTo(a,.5,!0),M.current=a)}}},[D,x,y]),e.useEffect(()=>{if(!x)return;x.traverse(a=>{if(a.isMesh&&a.morphTargetDictionary){const o=a.name.toLowerCase();(o.includes("head")||o.includes("avatar"))&&(L.current=a,W(`[ANIMATION] Found head mesh: ${a.name}`)),o.includes("teeth")&&(U.current=a,W(`[ANIMATION] Found teeth mesh: ${a.name}`))}});const f=L.current?.morphTargetDictionary;f&&Object.keys(f).filter(a=>a.toLowerCase().includes("brow"));const d=[];x.traverse(a=>{if(a.isMesh){const h=a.morphTargetDictionary;h&&Object.keys(h).some(B=>B.toLowerCase().includes("brow"))&&d.push(a)}}),pe.current=d,d.length>0&&W("[ANIMATION] Meshes with brow morphs:",d.length)},[x]);const Fe=(f,d=1)=>{const a=`viseme_${f}`.toLowerCase(),o=ln.find(h=>h.key.toLowerCase()===a);if(o)for(const h in o.mix){const B=o.mix[h]*d;z(L.current,h,B),z(U.current,h,B)}},xe=f=>{const d=ze[f]??ze.neutral;for(const a in d)z(L.current,a,d[a]),z(U.current,a,d[a])};return ct.useFrame((f,d)=>{const a=Math.pow(.88,60*d);At(L.current,a),At(U.current,a),xe(V);const o=f.clock.elapsedTime;let h=0;if(Math.floor(o)%5===0&&Math.floor((o-d)%5)!==0){let H=null;x.traverse(K=>{K.name.toLowerCase().includes("hips")&&(H=K)});const we=H?`Hips Y: ${H.position.y.toFixed(4)}`:"Hips not found";W(`[ANIMATION] Mixer Time: ${I.time.toFixed(2)}, ${we}`)}if(I.update(d),o>ge.current&&!Ae.current&&(Ae.current=!0,be.current=o),Ae.current){const H=D?.2:.3,we=(o-be.current)/H;if(we>=1){Ae.current=!1;const K=D?1:2.5;ge.current=o+K}else{const K=we<.5?we*2:(1-we)*2;z(L.current,"eyeBlinkLeft",K),z(L.current,"eyeBlinkRight",K),z(U.current,"eyeBlinkLeft",K),z(U.current,"eyeBlinkRight",K),h=K*cn.browInnerUp}}const B=ze[V]??ze.neutral,Q=B.browInnerUp??0,Qe=B.browOuterUpLeft??0,We=B.browOuterUpRight??0,Ne=o*un,ye=ot*Math.sin(Ne),Z=ot*.7*Math.sin(Ne+.7),Ve=ot*.7*Math.sin(Ne+1.3),te=H=>Math.max(0,Math.min(1,H)),Re=te(Q+ye),ke=te(Qe+Z),je=te(We+Ve),Le=te(Re+h);if(z(L.current,"browInnerUp",Le),z(U.current,"browInnerUp",Le),z(L.current,"browOuterUpLeft",ke),z(U.current,"browOuterUpLeft",ke),z(L.current,"browOuterUpRight",je),z(U.current,"browOuterUpRight",je),J.current){const H=_.current?0:C.rotation[1];J.current.rotation.y=Pe.MathUtils.lerp(J.current.rotation.y,H,.1),J.current.position.set(...C.position),J.current.scale.setScalar(C.scale),J.current.rotation.x=C.rotation[0],J.current.rotation.z=C.rotation[2]}if(_.current&&m.current){const H=m.current.currentTime,Ie=(H-w.current)*1e3- -150;for(let ee=0;ee<g.current.length;ee++){const ne=g.current[ee];Ie>=ne.vtime&&Ie<ne.vtime+ne.vduration&&Fe(ne.viseme,ne.weight??1)}H>le.current+.5&&(A(),v(!1))}}),i.jsx("group",{ref:J,children:i.jsx("primitive",{object:x})})});function pn(u){return u?u.charAt(0).toUpperCase()+u.slice(1).toLowerCase():""}function Lt(u){return u.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const gn=({token:u,agentToken:_,onNavigationRequested:g,avatarGender:m,presetUserDetails:w}={})=>{const C=u??_??"",V=Zt(C||void 0),[ue,Y]=e.useState(""),[D,le]=e.useState(""),[A,v]=e.useState("Ready"),[y,E]=e.useState(!1),[N,de]=e.useState(!1),[x,ve]=e.useState([]),[De,G]=e.useState(""),fe=e.useRef(null),[j,$]=e.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);e.useEffect(()=>{const t=window.matchMedia("(max-width: 480px)"),n=()=>$(t.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const J=j?80:600,L=e.useRef(!1),U=e.useRef([]),pe=e.useRef(0),I=e.useRef(!1),R=e.useRef([]),M=e.useRef(null),ge=e.useRef([]);e.useRef([]);const Ae=e.useRef([]),be=e.useRef(0),ie=e.useRef(0),_e=e.useRef(0),Fe=e.useRef(0),xe=e.useRef(!1),[f,d]=e.useState(null),a=e.useRef(null),[o,h]=e.useState("neutral"),[B,Q]=e.useState(""),[Qe,We]=e.useState(""),[Ne,ye]=e.useState("Chat with us"),[Z,Ve]=e.useState(null),[te,Re]=e.useState("hidden"),[ke,je]=e.useState(""),Le=e.useRef(null),H=e.useRef(te);H.current=te;const[we,K]=e.useState(null),Ie=e.useRef(null),ee=e.useRef(null),[ne,ut]=e.useState(!1),lt=e.useRef(null),[ae,$e]=e.useState("hidden"),[dt,It]=e.useState(""),Ke=e.useRef(ae);Ke.current=ae;const he=e.useRef(""),Me=e.useRef(!1),Oe=e.useRef(""),ft=e.useRef(Date.now()),Xe=e.useRef([]),Ue=e.useRef(!1),[Ze,Be]=e.useState(!1),[ht,mt]=e.useState(!1),Se=e.useRef(null),Ce=e.useMemo(()=>ne?"Try again":A==="Busy"?"Busy":A==="Thinking..."||A==="Processing Voice..."?A:Z!=null&&Z!==""&&Z!=="none"&&Z!=="<none>"?`Enter ${pn(Z)}`:ae!=="hidden"||!ht?null:Et,[A,Z,ne,ae,ht]),pt=!ne&&A!=="Busy"&&A!=="Thinking..."&&A!=="Processing Voice..."&&(Z==null||Z===""||Z==="none"||Z==="<none>");e.useEffect(()=>{if(ae!=="hidden"||!pt){mt(!1),Se.current!=null&&(clearTimeout(Se.current),Se.current=null);return}return Se.current=setTimeout(()=>{Se.current=null,mt(!0)},400),()=>{Se.current!=null&&(clearTimeout(Se.current),Se.current=null)}},[ae,pt]);const He=Ce!=null&&Ce!=="";e.useEffect(()=>{const t=H.current;if(!(t==="exiting"||t==="entering")){if(t==="hidden"){He&&(je(Ce??""),Re("entering"));return}t==="visible"&&(!He||Ce!==ke)&&(Le.current=He?Ce:null,Re("exiting"))}},[He,Ce,te,ke]),e.useEffect(()=>{if(A!=="Busy"){ee.current!=null&&(clearTimeout(ee.current),ee.current=null);return}return ee.current=setTimeout(()=>{ee.current=null,v("Ready"),ut(!0)},12e3),()=>{ee.current!=null&&(clearTimeout(ee.current),ee.current=null)}},[A]),e.useEffect(()=>{if(!ne)return;const t=setTimeout(()=>ut(!1),2500);return()=>clearTimeout(t)},[ne]);const Mt=e.useCallback(()=>{const t=H.current;if(t==="exiting"){Re("hidden");const n=Le.current;Le.current=null,n!=null&&n!==""&&(je(n),Re("entering"))}else t==="entering"&&Re("visible")},[]),Ot=t=>{if(!t)return;if(t.mood!=null){const r=String(t.mood).toLowerCase();h(r)}if(t.expression!=null){const r=String(t.expression).trim();Q(r);const l=nn.find(p=>p.name.toLowerCase()===r.toLowerCase());W(`[STREAM] Animation match for "${r}": ${l?l.name:"NONE"}`),We(l?.url??"")}if(t.navigation!=null){const r=String(t.navigation).trim();r!==""&&(g?g(r):window.open(r,"_blank"))}const n=t.ask_for||t.lead_capture?.ask_for,s=n?String(n).trim().toLowerCase():"",c=s==="none"||s==="<none>";if(n&&!c){const r=s;if(w&&(r==="email"&&w.email||r==="name"&&w.name||r==="phone"&&w.phone))return;Ve(r||null),ye(r==="email"?"Enter your email":r==="name"?"Enter your name":r==="phone"?"Enter your phone number":"Chat with us")}else(c||t.ask_for===null||t.lead_capture&&t.lead_capture.ask_for===null||t.ask_for==="none")&&(Ve(null),Ne!=="Chat with us"&&ye("Chat with us"));t.collected,t.valid},Ct=t=>{const n=t.trim();if(!n)return null;if(n.startsWith("{"))try{return JSON.parse(n)}catch{return null}if(n.includes(":")){const s=n.split(":"),c=s[0].trim().toLowerCase(),r=s.slice(1).join(":").trim();return{[c]:r}}return null},Dt=e.useCallback(()=>{},[]),gt=t=>{if(Me.current)t==="§"?Me.current=!1:(Oe.current+=t,le(n=>n+t));else if(t==="§"){Me.current=!0;return}else for(he.current+=t;he.current.includes(`
|
|
2
|
+
`);){const n=he.current.indexOf(`
|
|
3
|
+
`),s=he.current.slice(0,n).trim();he.current=he.current.slice(n+1);const c=Ct(s);c&&Ot(c)}};e.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const r="secret",l=Math.floor(Date.now()/1e3).toString();try{const p=new TextEncoder,b=await crypto.subtle.importKey("raw",p.encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),S=await crypto.subtle.sign("HMAC",b,p.encode(l)),T=Array.from(new Uint8Array(S)).map(P=>P.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",T),W("[SESSION] New HMAC UID generated and saved:",T)}catch(p){console.error("[SESSION] HMAC generation failed:",p);const b=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",b)}}const s=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let c=[];if(s)try{c=JSON.parse(s)}catch{c=[]}c.length===0&&w&&(w.name||w.email)?(c=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${w.name||""}" , Email is "${w.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(c))):s||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[w]),e.useEffect(()=>{const t=()=>{ft.current=Date.now(),Ue.current&&(Ue.current=!1,Be(!1),ve([]),G(""),le(""),de(!1))};window.addEventListener("mousemove",t),window.addEventListener("keydown",t),window.addEventListener("mousedown",t),window.addEventListener("touchstart",t);const n=setInterval(async()=>{if(Date.now()-ft.current>=3e4&&!N&&!y&&A==="Ready"&&!Ue.current)if(Ue.current=!0,Xe.current.length>0)Be(!0),ve(Xe.current);else try{const r=`${at}/nudgeUser`,l={navigationUrl:window.location.href,token:C},p=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(p.ok){const S=(await p.json()).nudge_questions;S&&S.length>0&&(W("[NUDGE] Received nudge questions from API:",S),Xe.current=S,Be(!0),ve(S))}}catch(r){console.error("[NUDGE] Error calling /nudgeUser:",r),Ue.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",t),window.removeEventListener("keydown",t),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t),clearInterval(n)}},[C,N,y,A]),e.useEffect(()=>{if(x.length===0)return;let t=0,n=0,s=!1,c=100;const r=()=>{const l=x[t];if(s){const p=l.substring(0,n-1);G(p),n--,c=50}else{const p=l.substring(0,n+1);G(p),n++,c=100}!s&&n===l.length?(s=!0,c=3e3):s&&n===0&&(s=!1,t=(t+1)%x.length,c=500),fe.current=setTimeout(r,c)};return r(),()=>{fe.current&&clearTimeout(fe.current)}},[x]);const bt=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},Ft=t=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(t))},[et,tt]=e.useState(!1),[_t,nt]=e.useState(0),oe=e.useRef(null),qe=e.useRef([]),wt=e.useRef(0),[St,Nt]=e.useState(null),[jt,rt]=e.useState(null),me=e.useRef(null),Te=e.useRef(null),Je=e.useCallback((t=!1)=>{t&&(xe.current=!0,E(!1),v("Ready")),R.current=[],U.current=[],I.current=!1,de(!1),be.current=0,ie.current=0,_e.current=0,ge.current.forEach(n=>{try{n.stop()}catch{}}),Ie.current&&(clearTimeout(Ie.current),Ie.current=null),K(null),We(""),ge.current=[]},[]),Ut=async()=>{try{const t=await navigator.mediaDevices.getUserMedia({audio:!0}),n=window.AudioContext||window.webkitAudioContext,s=new n,c=s.createMediaStreamSource(t),r=s.createAnalyser();r.fftSize=64,c.connect(r),me.current=s,Te.current=c,rt(r);const l=new MediaRecorder(t);oe.current=l,qe.current=[],l.ondataavailable=p=>{p.data.size>0&&qe.current.push(p.data)},l.onstop=async()=>{const p=Date.now()-wt.current;if(rt(null),Te.current&&(Te.current.disconnect(),Te.current=null),me.current&&me.current.state!=="closed"&&(me.current.close(),me.current=null),p<1e3){v("Recording too short. Hold or click longer."),E(!1);return}const b=new Blob(qe.current,{type:"audio/wav"});await Vt(b)},wt.current=Date.now(),l.start(100),tt(!0),v("Listening...")}catch(t){console.error("Error accessing microphone:",t),v("Mic Access Error")}},Bt=()=>{oe.current&&oe.current.state!=="inactive"&&(oe.current.stop(),oe.current.stream.getTracks().forEach(t=>t.stop()),tt(!1))},Pt=()=>{oe.current&&oe.current.state!=="inactive"&&(oe.current.onstop=null,oe.current.stop(),oe.current.stream.getTracks().forEach(t=>t.stop()),rt(null),Te.current&&(Te.current.disconnect(),Te.current=null),me.current&&me.current.state!=="closed"&&(me.current.close(),me.current=null),tt(!1),qe.current=[],v("Ready"))};e.useEffect(()=>{if(!N)return;const t=()=>{const n=_e.current;if(n<=0)return;const s=M.current,c=be.current;if(!s)return;const r=s.currentTime-c,l=Math.min(Math.max(0,r),n),b=Lt(D).trim().length;if(b<=0)return;const S=Math.min(Math.round(l/n*b),b);d(S)};return clearInterval(a.current??void 0),a.current=setInterval(t,90),()=>clearInterval(a.current??void 0)},[N,D,_e.current]),e.useEffect(()=>{let t;return et?(nt(0),t=window.setInterval(()=>{nt(n=>n+1)},1e3)):nt(0),()=>clearInterval(t)},[et]);const Wt=t=>{const n=t.numberOfChannels,s=t.length*n*2+44,c=new ArrayBuffer(s),r=new DataView(c);let l=0;const p=T=>{r.setUint16(l,T,!0),l+=2},b=T=>{r.setUint32(l,T,!0),l+=4};b(1179011410),b(s-8),b(1163280727),b(544501094),b(16),p(1),p(n),b(t.sampleRate),b(t.sampleRate*2*n),p(n*2),p(16),b(1635017060),b(s-l-4);const S=[];for(let T=0;T<n;T++)S.push(t.getChannelData(T));let k=0;for(;l<s;){for(let T=0;T<n;T++){let P=Math.max(-1,Math.min(1,S[T][k]));P=P<0?P*32768:P*32767,r.setInt16(l,P,!0),l+=2}k++}return new Blob([c],{type:"audio/wav"})},st=async(t,n,s=!1)=>{if(!xe.current){if(L.current){U.current.push({audio:t,visemes:n,isNewSegment:s});return}L.current=!0;try{const c=window.AudioContext||window.webkitAudioContext,r=M.current??new c;r.state==="suspended"&&await r.resume(),M.current=r;const l=window.atob(t),p=new Uint8Array(l.length);for(let F=0;F<l.length;F++)p[F]=l.charCodeAt(F);const b=await r.decodeAudioData(p.buffer.slice(0));_e.current+=b.duration;const S=r.currentTime;let k=ie.current;const T=!I.current;k<S&&(k=S+.1),ie.current=k+b.duration;const P=r.createBufferSource();P.buffer=b;let q=St;if((!q||q.context!==r)&&(q=r.createAnalyser(),q.fftSize=64,q.connect(r.destination),Nt(q)),P.connect(q),ge.current.push(P),xe.current){ge.current=ge.current.filter(F=>F!==P);return}if(T){I.current=!0,de(!0),W(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${k.toFixed(3)}`),be.current=k;const F=(k-S)*1e3;pe.current=performance.now()+F,W(`[AUDIO] Response started. Initial startTime: ${k.toFixed(3)}, CT: ${S.toFixed(3)}`)}P.start(k);const X=(k-be.current)*1e3;s&&(Fe.current=X,W(`[AUDIO] New segment detected at +${X.toFixed(0)}ms. Resetting segment offset.`)),n.forEach((F,re)=>{const O=F.symbol??"";if(O){const se=fn(O),ce=Math.round(F.start*1e3),Ee=Math.round((F.duration??0)*1e3),yt=Fe.current+ce;re<3&&W(`[AUDIO] Viseme "${O}": segment_relative=${ce}ms, segment_offset=${Fe.current.toFixed(0)}ms => vtime=${yt}ms`),se.forEach(Rt=>{R.current.push({viseme:Rt.v,weight:Rt.w,vtime:yt,vduration:Ee})})}}),v("Speaking...")}finally{if(L.current=!1,U.current.length>0){const c=U.current.shift();c&&st(c.audio,c.visemes,c.isNewSegment)}}}},Vt=async t=>{try{E(!0),Be(!1),Oe.current="",le(""),v("Processing Voice...");const n=await t.arrayBuffer(),c=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(n),r=Wt(c),l=new FileReader;l.readAsDataURL(r),l.onloadend=async()=>{const p=l.result.split(",")[1];Je(),Y(""),he.current="",Me.current=!1;const b=`${at}/stt?token=${encodeURIComponent(C)}`,S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:p,audio_format:"wav"})});if(S.status===429){try{const re=await S.text(),O=JSON.parse(re);W("[STT] 429 agent at capacity:",O?.detail)}catch{}Y(""),v("Busy"),E(!1);return}if(!S.ok){const re=await S.text();let O="STT Failed";try{O=JSON.parse(re).error||O}catch{re&&(O=re.slice(0,200))}throw new Error(O)}const k=S.body;if(W("this is body"+k),!k){v("STT Failed"),E(!1);return}const T=k.getReader();xe.current=!1;const P=new TextDecoder;let q="",X=!1;const F=async(re,O)=>{switch(re){case"transcript":O.transcript!=null&&Y(String(O.transcript));break;case"text":{const se=O.delta??O.text??"";se&>(se);break}case"audio":{const se=O.chunk,ce=O.visemes??[],Ee=!!O.is_new_segment;se&&await st(se,ce,Ee);break}case"done":{X=!0,v("Ready"),E(!1);break}case"error":{X=!0,v("STT Failed"),E(!1);break}default:break}};for(;;){const{done:re,value:O}=await T.read();O&&(q+=P.decode(O,{stream:!0}));const se=q.split(`
|
|
4
4
|
|
|
5
|
-
`)
|
|
5
|
+
`);q=se.pop()??"";for(const ce of se){const Ee=Ge(ce);Ee&&await F(Ee.event,Ee.data)}if(re){if(q.trim()){const ce=Ge(q.trim());ce&&await F(ce.event,ce.data)}X||(v("Ready"),E(!1));break}}}}catch(n){console.error("Audio Submission Error:",n),v("STT Failed"),E(!1)}},$t=async t=>{t&&t.preventDefault(),Be(!1),Oe.current="",le(""),!(!ue||y)&&await Ht(ue)},Ge=t=>{const n=t.split(/\r?\n/);let s="",c="";for(const l of n)l.startsWith("event:")?s=l.slice(6).trim():l.startsWith("data:")&&(c=l.slice(5).trim());if(!s)return null;let r={};if(c)try{r=JSON.parse(c)}catch{r={raw:c}}return{event:s,data:r}},vt=(t,n)=>{switch(t){case"connected":he.current="",Me.current=!1;break;case"text":{const s=n.delta??"";s&>(s);break}case"audio":{const s=n.chunk,c=n.visemes??[];s&&st(s,c);break}case"done":{const s=bt(),c=Oe.current.trim(),r=[...s,{role:"user",content:ue||"..."},{role:"assistant",content:c}];Ft(r),Ae.current=[...R.current],v("Ready"),E(!1),Y("");break}case"error":{const s=n.message??"Unknown error";Oe.current=s,le(s),v("Agent Failed"),E(!1);break}}},Ht=async t=>{E(!0),v("Thinking..."),Oe.current="",he.current="",Me.current=!1,Je(),_e.current=0,d(0);const n=`${at}/agent/chat?token=${encodeURIComponent(C)}`;try{const s=bt();let c=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");c||(Qt("[CHAT] Session UID missing at send time! Generating emergency backup."),c="emergency-"+Math.random().toString(36).substring(7),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",c));const r={history:s,question:t,lead_id:c};W("[CHAT] Sending payload:",r);const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),cache:"default"});if(l.status===429){try{const T=await l.json();W("[CHAT] 429 agent at capacity:",T?.detail)}catch{}Y(""),v("Busy"),E(!1);return}if(!l.ok)throw new Error("Agent request failed");const p=l.body;if(!p){v("Agent Failed"),E(!1);return}const b=p.getReader();xe.current=!1;const S=new TextDecoder;let k="";for(;;){const{done:T,value:P}=await b.read();W(`[SSE] Chunk received. done=${T}, length=${P?.length||0}`),P&&(k+=S.decode(P,{stream:!0}));const q=k.split(`
|
|
6
6
|
|
|
7
|
-
`);
|
|
7
|
+
`);k=q.pop()??"";for(const X of q){W(`[SSE] Processing block: ${X.slice(0,50)}...`);const F=Ge(X);F&&(W(`[SSE] Event: ${F.event}`),vt(F.event,F.data))}if(T){if(W("[SSE] Stream finished"),k.trim()){const X=Ge(k.trim());X&&vt(X.event,X.data)}v("Ready"),E(!1),Y("");break}}}catch(s){console.error("Chat Error:",s),v("Agent Failed"),E(!1)}},qt=D.trim(),xt=Lt(qt),it=xt&&N?xt.slice(0,f!=null&&f>0?f:0):"";e.useEffect(()=>{const t=Ke.current;t!=="exiting"&&(it?(It(it),t==="hidden"&&$e("entering")):(t==="visible"||t==="entering")&&$e("exiting"))},[it,ae]);const Jt=e.useCallback(()=>{const t=Ke.current;t==="entering"?$e("visible"):t==="exiting"&&$e("hidden")},[]);return e.useLayoutEffect(()=>{const t=lt.current;t&&(t.scrollTop=t.scrollHeight)},[dt]),i.jsxs("div",{className:"avatar-widget-container",children:[i.jsxs("div",{className:"avatar-input-area",children:[te!=="hidden"?i.jsx("div",{className:`avatar-thinking-tab${te==="exiting"?" avatar-thinking-tab--exiting":te==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:Mt,children:ke===Et?i.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):ke}):null,i.jsx("div",{className:"avatar-input-container",children:i.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:et?i.jsxs("div",{className:"avatar-input-recording",children:[i.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:Pt,title:"Cancel",children:i.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:[i.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),i.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[i.jsx("div",{style:{flex:1,height:"100%"},children:i.jsx(kt,{analyser:jt})}),i.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(_t/60),":",String(_t%60).padStart(2,"0")]})]}),i.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:Bt,title:"Send",children:i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:i.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):N&&!Ze?i.jsxs("div",{className:"avatar-input-speaking",children:[i.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:i.jsx(kt,{analyser:St})}),i.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>Je(!0),title:"Stop",children:i.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):y?i.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:i.jsx("div",{className:"avatar-input-loader"})}):i.jsxs("form",{onSubmit:$t,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[i.jsx("input",{id:"avatar-text-input",type:"text",value:ue,onChange:t=>Y(t.target.value),placeholder:A==="Busy"?"Assisting another user":De||"Ask me anything",disabled:y||A==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),A==="Busy"?i.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:i.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:i.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):ue.trim()===""?i.jsx("button",{type:"button",className:"mic-button",onClick:Ut,disabled:y,style:{backgroundColor:"#1e4a5e"},children:i.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M12 14C13.66 14 15 12.66 15 11V5C15 3.34 13.66 2 12 2C10.34 2 9 3.34 9 5V11C9 12.66 10.34 14 12 14Z",fill:"white"}),i.jsx("path",{d:"M17 11C17 13.76 14.76 16 12 16C9.24 16 7 13.76 7 11H5C5 14.53 7.61 17.43 11 17.93V21H13V17.93C16.39 17.43 19 14.53 19 11H17Z",fill:"white"})]})}):i.jsx("button",{type:"submit",className:"mic-button",disabled:y,style:{backgroundColor:"#1e4a5e"},title:"Send",children:i.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:i.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),i.jsx("div",{className:"avatar-wrapper",children:i.jsxs("div",{className:"avatar-scene-wrapper",children:[ae!=="hidden"&&i.jsx("div",{className:`avatar-bubble${ae==="entering"?" avatar-bubble--entering":ae==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:Jt,children:i.jsx("div",{ref:lt,className:`avatar-bubble__content${Ze?" avatar-bubble__content--nudge":""}`,children:dt})}),i.jsx("div",{className:"avatar-canvas-layer",style:{width:J,height:J},children:i.jsxs(ct.Canvas,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1.8,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[i.jsx(hn,{target:on}),i.jsx("ambientLight",{intensity:.7}),i.jsx("directionalLight",{position:[0,2,2],intensity:1}),i.jsx(Ye.Environment,{preset:"city"}),i.jsx(e.Suspense,{fallback:null,children:V!==null&&i.jsx(mn,{avatarUrl:V,isPlayingRef:I,visemeQueueRef:R,audioContextRef:M,responseAudioStartTimeRef:be,adjustments:an,mood:o,expression:B,agentResponse:D,isSpeaking:N,nextStartTimeRef:ie,stopPlayback:Je,setIsSpeaking:de,expressionUrl:Qe,onExpressionFinished:Dt,isNudgeResponse:Ze,avatarGender:m})})]})})]})})]})},bn=({token:u,avatarGender:_,onNavigationRequested:g,presetUserDetails:m})=>i.jsx(gn,{token:u,onNavigationRequested:g,avatarGender:_,presetUserDetails:m});exports.AvatarWidget=bn;
|