@botuyo/chat-widget-standalone 1.8.2 → 1.8.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"useChatWidget.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/hooks/useChatWidget.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,eAAe,EACf,WAAW,EAKX,cAAc,EACd,WAAW,EACX,sBAAsB,EACvB,MAAM,UAAU,CAAA;AAQjB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAiBnD,UAAU,oBAAoB;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,KAAK,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAA;IAChC,WAAW,CAAC,EAAE,eAAe,CAAC,aAAa,CAAC,CAAA;IAC5C,WAAW,CAAC,EAAE,eAAe,CAAC,aAAa,CAAC,CAAA;IAC5C,OAAO,CAAC,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IACpC,UAAU,CAAC,EAAE,eAAe,CAAC,YAAY,CAAC,CAAA;IAC1C,OAAO,CAAC,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IACpC,aAAa,CAAC,EAAE,eAAe,CAAC,eAAe,CAAC,CAAA;IAChD,YAAY,CAAC,EAAE,eAAe,CAAC,cAAc,CAAC,CAAA;IAC9C,cAAc,CAAC,EAAE,eAAe,CAAC,gBAAgB,CAAC,CAAA;IAClD,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,CAAA;CACrC;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;2BA2LhD,MAAM;iCA8DA,IAAI,QAAQ,OAAO,GAAG,OAAO,GAAG,MAAM;mCAyCxC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;gCApExC,cAAc,SAAS,MAAM,YAAY,MAAM;wCAW5C,MAAM;uCAQN,MAAM;iCApF2B,OAAO;EAmPxD"}
1
+ {"version":3,"file":"useChatWidget.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/hooks/useChatWidget.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,eAAe,EACf,WAAW,EAKX,cAAc,EACd,WAAW,EACX,sBAAsB,EACvB,MAAM,UAAU,CAAA;AAQjB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAiBnD,UAAU,oBAAoB;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,KAAK,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAA;IAChC,WAAW,CAAC,EAAE,eAAe,CAAC,aAAa,CAAC,CAAA;IAC5C,WAAW,CAAC,EAAE,eAAe,CAAC,aAAa,CAAC,CAAA;IAC5C,OAAO,CAAC,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IACpC,UAAU,CAAC,EAAE,eAAe,CAAC,YAAY,CAAC,CAAA;IAC1C,OAAO,CAAC,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IACpC,aAAa,CAAC,EAAE,eAAe,CAAC,eAAe,CAAC,CAAA;IAChD,YAAY,CAAC,EAAE,eAAe,CAAC,cAAc,CAAC,CAAA;IAC9C,cAAc,CAAC,EAAE,eAAe,CAAC,gBAAgB,CAAC,CAAA;IAClD,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,CAAA;CACrC;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;2BA2LhD,MAAM;iCAsEA,IAAI,QAAQ,OAAO,GAAG,OAAO,GAAG,MAAM;mCAyCxC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;gCA3ExC,cAAc,SAAS,MAAM,YAAY,MAAM;wCAkB5C,MAAM;uCAQN,MAAM;iCA5F2B,OAAO;EA2PxD"}
@@ -26,7 +26,7 @@ return y("div",{className:"w-full my-2 rounded-2xl border shadow-sm overflow-hid
26
26
  /* @__PURE__ */y("button",{type:"button",onClick:()=>{d||(c("cancelled"),o?.(e.proposalId))},"data-testid":"tool-proposal-cancel",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-bold transition-colors hover:bg-muted/50 active:scale-[0.98]",style:{color:"hsl(var(--muted-foreground))"},children:[
27
27
  /* @__PURE__ */b(he,{size:14,strokeWidth:2.5}),a("cancel")]}),
28
28
  /* @__PURE__ */y("button",{type:"button",onClick:()=>{p||(c("confirmed"),r?.(e.proposalId))},disabled:p,"data-testid":"tool-proposal-confirm",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-black text-white transition-all active:scale-[0.98] disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100",style:{backgroundColor:s},children:[
29
- /* @__PURE__ */b(H,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Bl=p(()=>import("./AudioPlayer-Dfh8exOu.js").then(e=>({default:e.AudioPlayer}))),Ul=p(()=>import("./Gallery-zx8VOypZ.js").then(e=>({default:e.Gallery})));function ql({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
29
+ /* @__PURE__ */b(H,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Bl=p(()=>import("./AudioPlayer-BHlSnd9m.js").then(e=>({default:e.AudioPlayer}))),Ul=p(()=>import("./Gallery-C9emIFrA.js").then(e=>({default:e.Gallery})));function ql({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
30
30
  return y("div",{className:"space-y-3",children:[
31
31
  /* @__PURE__ */b("div",{className:Ot("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(La,{remarkPlugins:[Al],rehypePlugins:[[Rl,{tagNames:["p","strong","em","br","span"],attributes:{}}]],components:{p:({children:e})=>/* @__PURE__ */b("p",{className:"mb-0 last:mb-0",children:e})},children:e.content})}),
32
32
  /* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((i,a)=>{const s=r===i.id;/* @__PURE__ */
@@ -107,7 +107,7 @@ return b("div",{"data-testid":"quiz-dock",className:"shrink-0 border-t animate-i
107
107
  /* @__PURE__ */b("p",{className:"text-sm font-semibold mb-2 text-foreground break-words leading-snug",children:e.content}),
108
108
  /* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((e,t)=>/* @__PURE__ */b("button",{type:"button",onClick:()=>n(e.label,e.id),className:"w-full text-left px-4 py-3 rounded-xl border text-sm font-semibold transition-all duration-200 cursor-pointer hover:scale-[1.02] hover:shadow-md active:scale-[0.97]",style:{backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:/* @__PURE__ */y("span",{className:"flex items-center gap-3",children:[
109
109
  /* @__PURE__ */b("span",{className:"flex items-center justify-center w-6 h-6 rounded-full text-xs font-black shrink-0",style:{backgroundColor:r,color:"white"},children:String.fromCharCode(65+t)}),
110
- /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function nc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function rc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=nc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const oc="24px",ic={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},ac=85,sc=.7,lc=200,cc=.5,uc=3e3,dc=1,pc=6,hc=7500,fc=.7,mc=-20,gc=8,bc=6,yc=.002,vc=.12,wc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},xc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...wc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function kc(e=wc,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const _c={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Sc(e){return void 0===e||"standard"===e?{..._c.standard}:"string"==typeof e?{..._c[e]??_c.standard}:{..._c.standard,...e}}class Cc{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={..._c.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const Ec="0.0.30",zc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Ec}/dist/`,Ac=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Ec}/+esm`;function Nc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Tc(){return await import(Ac)}class Ic{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Oc=p(()=>import("./Avatar3D-DPKnZFWa.js")),Mc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Pc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Lc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},Dc=24e3;function jc(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}class Rc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){O.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function Fc({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||null:t||null:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
110
+ /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function nc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function rc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=nc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const oc="24px",ic={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},ac=85,sc=.7,lc=200,cc=.5,uc=3e3,dc=1,pc=6,hc=7500,fc=.7,mc=-20,gc=8,bc=6,yc=.002,vc=.12,wc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},xc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...wc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function kc(e=wc,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const _c={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Sc(e){return void 0===e||"standard"===e?{..._c.standard}:"string"==typeof e?{..._c[e]??_c.standard}:{..._c.standard,...e}}class Cc{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={..._c.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const Ec="0.0.30",zc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Ec}/dist/`,Ac=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Ec}/+esm`;function Nc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Tc(){return await import(Ac)}class Ic{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Oc=p(()=>import("./Avatar3D-La_m2_2n.js")),Mc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Pc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Lc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},Dc=24e3;function jc(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}class Rc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){O.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function Fc({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||null:t||null:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
111
111
  return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",children:[
112
112
  /* @__PURE__ */b(Rc,{onError:()=>p(!0),children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"rounded-full flex items-center justify-center animate-pulse",style:{width:`${s.orbSize}px`,height:`${s.orbSize}px`,background:`radial-gradient(circle at 35% 35%, ${s.speakingColor}40, ${s.speakingColor}10 60%, transparent 80%)`,boxShadow:`0 0 30px ${s.speakingColor}15`}}),children:/* @__PURE__ */b(Oc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b($c,{isActive:"listening"===o||"speaking"===o,audioLevel:a,color:"speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:s.listeningColor})]}:f?{className:"relative flex flex-col items-center gap-4",children:[
113
113
  /* @__PURE__ */y("div",{className:Ot("relative rounded-full flex items-center justify-center","transition-all duration-500 ease-out"),style:{width:`${w}px`,height:`${w}px`,boxShadow:m?`0 0 0 4px ${g}40, 0 0 30px ${g}30, 0 0 60px ${g}15`:`0 0 0 2px ${g}20`,transform:`scale(${v})`},children:[
@@ -199,7 +199,7 @@ return Vh(bm,e)}const vm=/* @__PURE__ */wu("ZodBoolean",(e,t)=>{Mp.init(e,t),Wf.
199
199
  return Zh(xm)}const _m=/* @__PURE__ */wu("ZodNever",(e,t)=>{Dp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Sm=/* @__PURE__ */wu("ZodArray",(e,t)=>{Rp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(o.minItems=a),"number"==typeof s&&(o.maxItems=s),o.type="array",o.items=xf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */tf(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */tf(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */ef(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */nf(t,n)),e.unwrap=()=>e.element});function Cm(e,t){/* @__PURE__ */
200
200
  return gf(Sm,e,t)}const Em=/* @__PURE__ */wu("ZodObject",(e,t)=>{qp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const a=i.shape;for(const c in a)o.properties[c]=xf(a[c],t,{...r,path:[...r.path,"properties",c]});const s=new Set(Object.keys(a)),l=new Set([...s].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(o.required=Array.from(l)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=xf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),Iu(e,"shape",()=>t.shape),e.keyof=()=>Om(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:km()}),e.loose=()=>e.clone({...e._zod.def,catchall:km()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Jh(_m,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Ru(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Mu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ou(this,"shape",n),n}});return Uu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Ru(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Mu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ou(this,"shape",n),n}});return Uu(e,n)}(e,t),e.merge=t=>function(e,t){const n=Mu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ou(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Uu(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Uu(e,Mu(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Ou(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=Mu(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ou(this,"shape",r),r},checks:[]});return Uu(e,o)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=Mu(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Ou(this,"shape",o),o},checks:[]});return Uu(t,o)}(Pm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Mu(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return Ou(this,"shape",o),o}});return Uu(t,r)}(Bm,e,t[0])});function zm(e,t){const n={type:"object",shape:e??{},...qu(t)};return new Em(n)}const Am=/* @__PURE__ */wu("ZodUnion",(e,t)=>{Wp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,a=o.options.map((e,n)=>xf(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options}),Nm=/* @__PURE__ */wu("ZodIntersection",(e,t)=>{Hp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=xf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=xf(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,l=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=l})(e,t,n,r)}),Tm=/* @__PURE__ */wu("ZodRecord",(e,t)=>{Kp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=xf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=xf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=xf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),Im=/* @__PURE__ */wu("ZodEnum",(e,t)=>{Gp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Cu(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Im({...t,checks:[],...qu(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Im({...t,checks:[],...qu(r),entries:o})}});function Om(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Im({type:"enum",entries:n,...qu(t)})}const Mm=/* @__PURE__ */wu("ZodTransform",(e,t)=>{Yp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new ku(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Gu(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Gu(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),Pm=/* @__PURE__ */wu("ZodOptional",(e,t)=>{Xp.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Lm(e){return new Pm({type:"optional",innerType:e})}const Dm=/* @__PURE__ */wu("ZodExactOptional",(e,t)=>{eh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),jm=/* @__PURE__ */wu("ZodNullable",(e,t)=>{th.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=xf(o.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rm(e){return new jm({type:"nullable",innerType:e})}const Fm=/* @__PURE__ */wu("ZodDefault",(e,t)=>{nh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;xf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),$m=/* @__PURE__ */wu("ZodPrefault",(e,t)=>{oh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;xf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Bm=/* @__PURE__ */wu("ZodNonOptional",(e,t)=>{ih.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;xf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Um=/* @__PURE__ */wu("ZodCatch",(e,t)=>{sh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;xf(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),qm=/* @__PURE__ */wu("ZodPipe",(e,t)=>{lh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;xf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Vm(e,t){return new qm({type:"pipe",in:e,out:t})}const Wm=/* @__PURE__ */wu("ZodReadonly",(e,t)=>{uh.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;xf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Hm=/* @__PURE__ */wu("ZodCustom",(e,t)=>{ph.init(e,t),Wf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)}),Zm=/* @__PURE__ */Object.create(null);Zm.open="0",Zm.close="1",Zm.ping="2",Zm.pong="3",Zm.message="4",Zm.upgrade="5",Zm.noop="6";const Jm=/* @__PURE__ */Object.create(null);Object.keys(Zm).forEach(e=>{Jm[Zm[e]]=e});const Km={type:"error",data:"parser error"},Gm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ym="function"==typeof ArrayBuffer,Qm=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Xm=({type:e,data:t},n,r)=>Gm&&t instanceof Blob?n?r(t):eg(t,r):Ym&&(t instanceof ArrayBuffer||Qm(t))?n?r(t):eg(new Blob([t]),r):r(Zm[e]+(t||"")),eg=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function tg(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ng;const rg="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ay=0;ay<64;ay++)rg["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(ay)]=ay;const og="function"==typeof ArrayBuffer,ig=(e,t)=>{if("string"!=typeof e)return{type:"message",data:sg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:ag(e.substring(1),t)}:Jm[n]?e.length>1?{type:Jm[n],data:e.substring(1)}:{type:Jm[n]}:Km},ag=(e,t)=>{if(og){const n=(e=>{let t,n,r,o,i,a=.75*e.length,s=e.length,l=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const c=new ArrayBuffer(a),u=new Uint8Array(c);for(t=0;t<s;t+=4)n=rg[e.charCodeAt(t)],r=rg[e.charCodeAt(t+1)],o=rg[e.charCodeAt(t+2)],i=rg[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return sg(n,t)}return{base64:!0,data:e}},sg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,lg=String.fromCharCode(30);let cg;function ug(e){return e.reduce((e,t)=>e+t.length,0)}function dg(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function pg(e){if(e)return function(e){for(var t in pg.prototype)e[t]=pg.prototype[t];return e}(e)}pg.prototype.on=pg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},pg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},pg.prototype.off=pg.prototype.removeListener=pg.prototype.removeAllListeners=pg.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},pg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},pg.prototype.emitReserved=pg.prototype.emit,pg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},pg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const hg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),fg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function mg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const gg=fg.setTimeout,bg=fg.clearTimeout;function yg(e,t){t.useNativeTimers?(e.setTimeoutFn=gg.bind(fg),e.clearTimeoutFn=bg.bind(fg)):(e.setTimeoutFn=fg.setTimeout.bind(fg),e.clearTimeoutFn=fg.clearTimeout.bind(fg))}function vg(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function wg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class xg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class kg extends pg{constructor(e){super(),this.writable=!1,yg(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new xg(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ig(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class _g extends kg{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(lg),r=[];for(let o=0;o<n.length;o++){const e=ig(n[o],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{Xm(e,!1,e=>{r[i]=e,++o===n&&t(r.join(lg))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=wg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Sg=!1;try{Sg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(iy){}const Cg=Sg;function Eg(){}class zg extends _g{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Ag extends pg{constructor(e,t,n){super(),this.createRequest=e,yg(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=mg(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{n.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=Ag.requestsCount++,Ag.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Eg,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Ag.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function Ng(){for(let e in Ag.requests)Ag.requests.hasOwnProperty(e)&&Ag.requests[e].abort()}Ag.requestsCount=0,Ag.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Ng):"function"==typeof addEventListener&&addEventListener("onpagehide"in fg?"pagehide":"unload",Ng,!1));const Tg=function(){const e=Ig({xdomain:!1});return e&&null!==e.responseType}();function Ig(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Cg))return new XMLHttpRequest}catch(n){}if(!t)try{return new(fg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Og="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Mg extends kg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Og?{}:mg(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(iy){return this.emitReserved("error",iy)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;Xm(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&hg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=wg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Pg=fg.WebSocket||fg.MozWebSocket,Lg={websocket:class extends Mg{createSocket(e,t,n){return Og?new Pg(e,t,n):t?new Pg(e,t):new Pg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends kg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(iy){return this.emitReserved("error",iy)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){cg||(cg=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(a,s){for(n.push(a);;){if(0===r){if(ug(n)<1)break;const e=dg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(ug(n)<2)break;const e=dg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(ug(n)<8)break;const e=dg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(Km);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(ug(n)<o)break;const e=dg(n,o);s.enqueue(ig(i?e:cg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(Km);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){Gm&&e.data instanceof Blob?e.data.arrayBuffer().then(tg).then(t):Ym&&(e.data instanceof ArrayBuffer||Qm(e.data))?t(tg(e.data)):Xm(e,!1,e=>{ng||(ng=new TextEncoder),t(ng.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}});r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&hg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends zg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Tg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ag(Ig,this.uri(),e)}}},Dg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,jg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Rg(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=Dg.exec(e||""),i={},a=14;for(;a--;)i[jg[a]]=o[a]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const Fg="function"==typeof addEventListener&&"function"==typeof removeEventListener,$g=[];Fg&&addEventListener("offline",()=>{$g.forEach(e=>e())},!1);class Bg extends pg{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=Rg(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Rg(t.host).host);yg(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let r=0,o=n.length;r<o;r++){let e=n[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),Fg&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},$g.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Bg.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Bg.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=vg(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,hg(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Bg.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Fg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=$g.indexOf(this._offlineEventListener);-1!==e&&$g.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Bg.protocol=4;class Ug extends Bg{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Bg.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Bg.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function a(){i("transport closed")}function s(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let qg=class extends Ug{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Lg[e]).filter(e=>!!e)),super(e,n)}};const Vg="function"==typeof ArrayBuffer,Wg=Object.prototype.toString,Hg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Wg.call(Blob),Zg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Wg.call(File);function Jg(e){return Vg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Hg&&e instanceof Blob||Zg&&e instanceof File}function Kg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Kg(e[t]))return!0;return!1}if(Jg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Kg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Kg(e[n]))return!0;return!1}function Gg(e){const t=[],n=e.data,r=e;return r.data=Yg(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Yg(e,t){if(!e)return e;if(Jg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=Yg(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Yg(e[r],t));return n}return e}function Qg(e,t){return e.data=Xg(e.data,t),delete e.attachments,e}function Xg(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Xg(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Xg(e[n],t));return e}const eb=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var tb,nb;(nb=tb||(tb={}))[nb.CONNECT=0]="CONNECT",nb[nb.DISCONNECT=1]="DISCONNECT",nb[nb.EVENT=2]="EVENT",nb[nb.ACK=3]="ACK",nb[nb.CONNECT_ERROR=4]="CONNECT_ERROR",nb[nb.BINARY_EVENT=5]="BINARY_EVENT",nb[nb.BINARY_ACK=6]="BINARY_ACK";class rb extends pg{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===tb.BINARY_EVENT;n||t.type===tb.BINARY_ACK?(t.type=n?tb.EVENT:tb.ACK,this.reconstructor=new ob(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Jg(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===tb[n.type])throw new Error("unknown packet type "+n.type);if(n.type===tb.BINARY_EVENT||n.type===tb.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(o);if(!ib(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!rb.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case tb.CONNECT:return ab(t);case tb.DISCONNECT:return void 0===t;case tb.CONNECT_ERROR:return"string"==typeof t||ab(t);case tb.EVENT:case tb.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===eb.indexOf(t[0]));case tb.ACK:case tb.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ob{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Qg(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ib=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function ab(e){return"[object Object]"===Object.prototype.toString.call(e)}const sb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:rb,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==tb.EVENT&&e.type!==tb.ACK||!Kg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===tb.EVENT?tb.BINARY_EVENT:tb.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==tb.BINARY_EVENT&&e.type!==tb.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Gg(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return tb}},Symbol.toStringTag,{value:"Module"}));function lb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const cb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ub extends pg{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[lb(e,"open",this.onopen.bind(this)),lb(e,"packet",this.onpacket.bind(this)),lb(e,"error",this.onerror.bind(this)),lb(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(cb.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:tb.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:tb.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case tb.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case tb.EVENT:case tb.BINARY_EVENT:this.onevent(e);break;case tb.ACK:case tb.BINARY_ACK:this.onack(e);break;case tb.DISCONNECT:this.ondisconnect();break;case tb.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:tb.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:tb.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function db(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}db.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},db.prototype.reset=function(){this.attempts=0},db.prototype.setMin=function(e){this.ms=e},db.prototype.setMax=function(e){this.max=e},db.prototype.setJitter=function(e){this.jitter=e};class pb extends pg{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,yg(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new db({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||sb;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new qg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=lb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=lb(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(lb(e,"ping",this.onping.bind(this)),lb(e,"data",this.ondata.bind(this)),lb(e,"error",this.onerror.bind(this)),lb(e,"close",this.onclose.bind(this)),lb(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){hg(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new ub(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const hb={};function fb(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Rg(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,a=hb[o]&&i in hb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new pb(r,t):(hb[o]||(hb[o]=new pb(r,t)),s=hb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(fb,{Manager:pb,Socket:ub,io:fb,connect:fb});const mb=zm({proposalId:Jf().min(1),tool:Jf().min(1),title:Jf().optional(),summary:Jf().optional(),args:(gb=Jf(),bb=km(),new Tm({type:"record",keyType:gb,valueType:bb,...qu(void 0)})).optional(),ownerOnly:/* @__PURE__ */Wh(vm,void 0).optional()});var gb,bb;const yb=zm({proposalId:Jf().min(1),status:Om(["confirmed","cancelled","expired"]).optional()}),vb="chat_device_id";function wb(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return O.warn("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const xb=zm({id:Jf().optional(),type:Om(["text","image","audio","location","system"]).default("text"),content:Jf().optional(),imageUrl:Jf().url().optional(),audioUrl:Jf().optional(),latitude:gm().optional(),longitude:gm().optional(),timestamp:Jf().optional(),sender:Om(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Hh(wm).optional(),sources:Cm(Jf()).optional()}),kb=zm({agentId:Jf().optional(),name:Jf().optional(),label:Jf().optional(),avatarUrl:Jf().optional(),variantKey:Jf().optional()}),_b=zm({imageUrl:Jf().url(),caption:Jf().optional(),alt:Jf().optional(),attribution:Jf().optional(),sourceUrl:Jf().url().optional(),license:Jf().optional()}),Sb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;const Cb=`data:image/svg+xml,${encodeURIComponent('\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">\n <defs>\n <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">\n <stop offset="0%" style="stop-color:#10b981"/>\n <stop offset="100%" style="stop-color:#059669"/>\n </linearGradient>\n </defs>\n <circle cx="32" cy="32" r="32" fill="url(#bg)"/>\n <rect x="16" y="20" width="32" height="24" rx="4" fill="white"/>\n <circle cx="24" cy="30" r="3" fill="#10b981"/>\n <circle cx="40" cy="30" r="3" fill="#10b981"/>\n <rect x="22" y="36" width="20" height="3" rx="1.5" fill="#10b981"/>\n <rect x="28" y="12" width="8" height="8" rx="2" fill="white"/>\n</svg>\n')}`,Eb=function(){const e=Math.floor(1200),t=2*e,n=44+t,r=new ArrayBuffer(n),o=new DataView(r);zb(o,0,"RIFF"),o.setUint32(4,n-8,!0),zb(o,8,"WAVE"),zb(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,1,!0),o.setUint32(24,8e3,!0),o.setUint32(28,16e3,!0),o.setUint16(32,2,!0),o.setUint16(34,16,!0),zb(o,36,"data"),o.setUint32(40,t,!0);for(let s=0;s<e;s++){const t=s/8e3,n=1-s/e,r=Math.sin(2*Math.PI*880*t)*n*.5*32767;o.setInt16(44+2*s,r,!0)}const i=new Uint8Array(r);let a="";for(let s=0;s<i.length;s++)a+=String.fromCharCode(i[s]);return`data:audio/wav;base64,${btoa(a)}`}();function zb(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}class Ab{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(e,t){this.endpoint=e,this.apiKey=t,this.startAutoFlush()}startAutoFlush(){this.flushInterval=setInterval(()=>{!this.isDisabled&&this.queue.length>0&&this.flush()},this.FLUSH_INTERVAL_MS)}trackOpen(){this.track("chat_opened")}trackClose(){this.track("chat_closed")}trackMessageSent(e){this.track("message_sent",{type:e})}trackMessageReceived(e,t){this.track("message_received",{type:e,latency:t})}trackError(e,t){this.track("error",{error:e,context:t})}trackConnectionStatus(e){this.track("connection_status",{isConnected:e})}trackFeatureUsed(e){this.track("feature_used",{feature:e})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(e,t){this.track("attachment_sent",{type:e,size:t})}track(e,t){this.isDisabled||(this.queue.push({event:e,properties:{...t,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,url:"undefined"!=typeof window?window.location.href:void 0},timestamp:Date.now()}),this.queue.length>=this.BATCH_SIZE&&this.flush(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE),O.warn("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const e=[...this.queue];this.queue=[];try{const t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:e}),keepalive:!0});t.ok?O.debug(`Analytics: Flushed ${e.length} events`):(this.isDisabled=!0,this.queue=[],O.debug(`Analytics disabled: endpoint returned ${t.status}`))}catch(t){this.isDisabled=!0,this.queue=[],O.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Nb=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Tb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Ib=null,Ob=null;function Mb(e){Ib=e}function Pb(e){Ob=e}const Lb=r(null);function Db({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Ib?(Ib(e),O.debug("ChatWidgetProvider sendMessage:",e)):O.warn("sendMessage called but no handler registered")},[]),g=s(()=>{Ob?(Ob(),O.debug("ChatWidgetProvider clearMessages called")):O.warn("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
201
201
  return y(Lb.Provider,{value:v,children:[e,
202
- /* @__PURE__ */b(qb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function jb(){const e=o(Lb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Rb=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Fb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),C=f(!1),{t:E}=F(),z=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ab(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),A=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Cb,h=l||Eb;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return O.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),O.info("Notification permission:",e),"granted"===e}catch(e){return O.error("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){O.error("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{O.debug("Audio playback blocked:",e)})}catch(n){O.error("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),N=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:T,actions:I}=function(e,t="default"){const[r,o]=g(vu,bu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return gu.has(n)||gu.set(n,new mu(e,t)),gu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){O.warn("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){O.error("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){O.error("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){O.error("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),M=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),P=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(vb);if(e)return e;const t=wb();return localStorage.setItem(vb,t),t}catch{return O.warn("localStorage not available, using session-only device ID"),wb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=xb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=fb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Sb.test(n)||Sb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>O.error("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){O.error("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return O.debug("Error processing history message:",t),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){O.debug("Error processing history message:",t)}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("show_image"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const t=_b.safeParse(e.data);if(t.success){const e=t.data,n={id:`img-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"image",sender:"bot",timestamp:/* @__PURE__ */new Date,imageUrl:e.imageUrl,altText:e.alt||e.caption||"Imagen",...e.caption?{caption:e.caption}:{},...e.attribution?{attribution:e.attribution}:{},...e.sourceUrl?{sourceUrl:e.sourceUrl}:{}};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed show_image payload")}if("agent_switched"===e?.eventName&&e?.data){const t=kb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):O.debug("ChatSocket: dropped malformed agent_switched payload")}if("tool_proposal"===e?.eventName&&e?.data){const t=mb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed tool_proposal payload")}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=yb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else O.debug("ChatSocket: dropped malformed tool_proposal_resolved payload")}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{O.error("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),O.error("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),A=u(()=>nc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:A,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>M?{...l||{},seo:{...M||{}}}:l,[l,M]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,I.addMessage(e),z.trackMessageReceived(e.type,n),T.isOpen||"bot"!==e.sender||(_(e=>e+1),A.notifyWithSound(e))},[I,T.isOpen,z,A]),onConnected:s((e,t)=>{I.setConnected(!0),I.setSessionId(e),z.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[I,b,x,z]),onDisconnected:s(()=>{I.setConnected(!1),z.trackConnectionStatus(!1)},[I,z]),onTyping:s(e=>I.setTyping(e),[I]),onError:s(e=>{I.setError(e),z.trackError(e)},[I,z]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&I.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:E("agent_switched",{name:t})})},[x,I,E]),onHistoryLoaded:s(e=>{0!==e.length&&I.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Nb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Tb)),i=e.filter(e=>!r.has(e.id)&&Nb(e)>n&&!o.has(Tb(e)));return[...t,...i].sort((e,t)=>Nb(e)-Nb(t))}(T.messages,e))},[T.messages,I]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>I.resolveProposal(e,t),[I]),isVoiceCallActive:s(()=>C.current,[])}),L=s(e=>{C.current=e},[]),D=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(T.messages),[T.messages]),j=f(D);a(()=>{j.current=D},[D]);const R=s(()=>{O.debug("ChatWidget handleToggle called, current isOpen:",T.isOpen),T.isOpen?(I.closeWindow(),z.trackClose(),y?.(!1),O.debug("ChatWidget Closing window")):(I.openWindow(),_(0),z.trackOpen(),y?.(!0),O.debug("ChatWidget Opening window"))},[T.isOpen,I,y,z]),$=s(e=>{if(!N.isAllowed()){const e=N.getTimeUntilReset(),t=Math.ceil(e/1e3);return void I.setError(E("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};I.addMessage(t),z.trackMessageSent("text"),P.sendMessage(e,"text"),j.current&&I.answerQuiz(j.current.id)},[I,P,N,z,E]),B=s((e,t,n)=>{I.answerQuiz(e.id,n),P.sendMessage(`Answer: ${t}`,"text"),z.trackMessageSent("text")},[I,P,z]),U=s(e=>{I.resolveProposal(e,"confirmed"),P.confirmProposal(e)},[I,P]),q=s(e=>{I.resolveProposal(e,"cancelled"),P.rejectProposal(e)},[I,P]),V=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},I.addMessage(n);const r=await Rb(e);P.sendMessage(r,t)},[I,P]),W=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};I.addMessage(t),P.sendMessage(JSON.stringify(e),"location")},[I,P]);a(()=>{const e=()=>{T.isOpen||I.openWindow()},t=()=>{T.isOpen&&I.closeWindow()},n=()=>{T.isOpen?I.closeWindow():I.openWindow()},r=e=>{e.detail?.message&&$(e.detail.message)},o=()=>{T.isOpen||I.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[T.isOpen,I,$]),a(()=>(Mb($),()=>Mb(null)),[$]);const H=s(()=>{I.clearMessages(),O.info("Chat history cleared")},[I]);a(()=>(Pb(H),()=>Pb(null)),[H]);const Z=u(()=>{if(T.isTyping)return"thinking";const e=[...T.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[T.isTyping,T.messages]);return{state:T,actions:I,unreadCount:k,currentBotEmotion:Z,isConnected:P.isConnected,getSocket:P.getSocket,activeQuiz:D,handleToggle:R,handleSendText:$,handleSendAttachment:V,handleSendLocation:W,handleQuizAnswer:B,handleConfirmProposal:U,handleCancelProposal:q,setVoiceCallActive:L}}function $b({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=R.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),O.debug("ShadowDOMHost initialized"),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Bb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=rc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[A,N]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Mt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Vc,...e?.bubbleStyles?.radius},bot:{...Wc,...e?.bubbleStyles?.bot},user:{...Hc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,A);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H,setVoiceCallActive:Z}=Fb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:N}),J=f(!1);a(()=>{k&&A&&!J.current&&(J.current=!0,M.isOpen||P.openWindow())},[k,A,M.isOpen,P]);const K=u(()=>{const e={...d||{}},t=A;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,A]),G=s(()=>{P.closeWindow()},[P]),Y=s(e=>{e.stopPropagation()},[]),Q=O(M.isOpen,E,c?.position),X=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=A?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Pt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,A,c?.darkCssVariables]),ee=c?.voiceNoiseGate??A?.voiceNoiseGate,te=u(()=>({noiseGate:ee}),[ee]),[ne,re]=i(!1);return a(()=>{S&&j&&re(!0)},[S,j]),T.isHidden?null:A?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...X},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(qc,{children:/* @__PURE__ */b(Bc,{isOpen:ne,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:Lt(T),avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:te,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:Ot("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Q,...X,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
202
+ /* @__PURE__ */b(qb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function jb(){const e=o(Lb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Rb=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Fb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),C=f(!1),{t:E}=F(),z=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ab(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),A=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Cb,h=l||Eb;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return O.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),O.info("Notification permission:",e),"granted"===e}catch(e){return O.error("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){O.error("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{O.debug("Audio playback blocked:",e)})}catch(n){O.error("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),N=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:T,actions:I}=function(e,t="default"){const[r,o]=g(vu,bu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return gu.has(n)||gu.set(n,new mu(e,t)),gu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){O.warn("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){O.error("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){O.error("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){O.error("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),M=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),P=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(vb);if(e)return e;const t=wb();return localStorage.setItem(vb,t),t}catch{return O.warn("localStorage not available, using session-only device ID"),wb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=xb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=fb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Sb.test(n)||Sb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>O.error("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){O.error("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return O.debug("Error processing history message:",t),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){O.debug("Error processing history message:",t)}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("show_image"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const t=_b.safeParse(e.data);if(t.success){const e=t.data,n={id:`img-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"image",sender:"bot",timestamp:/* @__PURE__ */new Date,imageUrl:e.imageUrl,altText:e.alt||e.caption||"Imagen",...e.caption?{caption:e.caption}:{},...e.attribution?{attribution:e.attribution}:{},...e.sourceUrl?{sourceUrl:e.sourceUrl}:{}};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed show_image payload")}if("agent_switched"===e?.eventName&&e?.data){const t=kb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):O.debug("ChatSocket: dropped malformed agent_switched payload")}if("tool_proposal"===e?.eventName&&e?.data){const t=mb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed tool_proposal payload")}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=yb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else O.debug("ChatSocket: dropped malformed tool_proposal_resolved payload")}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{O.error("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),O.error("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),A=u(()=>nc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:A,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>M?{...l||{},seo:{...M||{}}}:l,[l,M]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,I.addMessage(e),z.trackMessageReceived(e.type,n),T.isOpen||"bot"!==e.sender||(_(e=>e+1),A.notifyWithSound(e))},[I,T.isOpen,z,A]),onConnected:s((e,t)=>{I.setConnected(!0),I.setSessionId(e),z.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[I,b,x,z]),onDisconnected:s(()=>{I.setConnected(!1),z.trackConnectionStatus(!1)},[I,z]),onTyping:s(e=>I.setTyping(e),[I]),onError:s(e=>{I.setError(e),z.trackError(e)},[I,z]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&I.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:E("agent_switched",{name:t})})},[x,I,E]),onHistoryLoaded:s(e=>{0!==e.length&&I.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Nb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Tb)),i=e.filter(e=>!r.has(e.id)&&Nb(e)>n&&!o.has(Tb(e)));return[...t,...i].sort((e,t)=>Nb(e)-Nb(t))}(T.messages,e))},[T.messages,I]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>I.resolveProposal(e,t),[I]),isVoiceCallActive:s(()=>C.current,[])}),L=s(e=>{C.current=e},[]),D=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(T.messages),[T.messages]),j=f(D);a(()=>{j.current=D},[D]);const R=s(()=>{O.debug("ChatWidget handleToggle called, current isOpen:",T.isOpen),T.isOpen?(I.closeWindow(),z.trackClose(),y?.(!1),O.debug("ChatWidget Closing window")):(I.openWindow(),_(0),z.trackOpen(),y?.(!0),O.debug("ChatWidget Opening window"))},[T.isOpen,I,y,z]),$=s(e=>{if(!N.isAllowed()){const e=N.getTimeUntilReset(),t=Math.ceil(e/1e3);return void I.setError(E("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};I.addMessage(t),z.trackMessageSent("text"),P.sendMessage(e,"text"),j.current&&I.answerQuiz(j.current.id)},[I,P,N,z,E]),B=s((e,t,n)=>{I.answerQuiz(e.id,n),I.addMessage({id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t}),P.sendMessage(`Answer: ${t}`,"text"),z.trackMessageSent("text")},[I,P,z]),U=s(e=>{I.resolveProposal(e,"confirmed"),P.confirmProposal(e)},[I,P]),q=s(e=>{I.resolveProposal(e,"cancelled"),P.rejectProposal(e)},[I,P]),V=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},I.addMessage(n);const r=await Rb(e);P.sendMessage(r,t)},[I,P]),W=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};I.addMessage(t),P.sendMessage(JSON.stringify(e),"location")},[I,P]);a(()=>{const e=()=>{T.isOpen||I.openWindow()},t=()=>{T.isOpen&&I.closeWindow()},n=()=>{T.isOpen?I.closeWindow():I.openWindow()},r=e=>{e.detail?.message&&$(e.detail.message)},o=()=>{T.isOpen||I.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[T.isOpen,I,$]),a(()=>(Mb($),()=>Mb(null)),[$]);const H=s(()=>{I.clearMessages(),O.info("Chat history cleared")},[I]);a(()=>(Pb(H),()=>Pb(null)),[H]);const Z=u(()=>{if(T.isTyping)return"thinking";const e=[...T.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[T.isTyping,T.messages]);return{state:T,actions:I,unreadCount:k,currentBotEmotion:Z,isConnected:P.isConnected,getSocket:P.getSocket,activeQuiz:D,handleToggle:R,handleSendText:$,handleSendAttachment:V,handleSendLocation:W,handleQuizAnswer:B,handleConfirmProposal:U,handleCancelProposal:q,setVoiceCallActive:L}}function $b({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=R.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),O.debug("ShadowDOMHost initialized"),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Bb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=rc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[A,N]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Mt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Vc,...e?.bubbleStyles?.radius},bot:{...Wc,...e?.bubbleStyles?.bot},user:{...Hc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,A);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H,setVoiceCallActive:Z}=Fb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:N}),J=f(!1);a(()=>{k&&A&&!J.current&&(J.current=!0,M.isOpen||P.openWindow())},[k,A,M.isOpen,P]);const K=u(()=>{const e={...d||{}},t=A;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,A]),G=s(()=>{P.closeWindow()},[P]),Y=s(e=>{e.stopPropagation()},[]),Q=O(M.isOpen,E,c?.position),X=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=A?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Pt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,A,c?.darkCssVariables]),ee=c?.voiceNoiseGate??A?.voiceNoiseGate,te=u(()=>({noiseGate:ee}),[ee]),[ne,re]=i(!1);return a(()=>{S&&j&&re(!0)},[S,j]),T.isHidden?null:A?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...X},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(qc,{children:/* @__PURE__ */b(Bc,{isOpen:ne,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:Lt(T),avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:te,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:Ot("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Q,...X,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
203
203
  /* @__PURE__ */b("div",{className:Ot("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",E?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",M.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:M.isOpen?"auto":"none"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(qc,{children:/* @__PURE__ */b(Uc,{isOpen:M.isOpen,isConnected:j,isTyping:M.isTyping,messages:M.messages,onClose:G,onSendMessage:F,onSendAttachment:$,onSendLocation:B,botName:T.botName,logoUrl:T.logoUrl,welcomeMessage:T.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||A?.inputPlaceholder,position:c?.position,bubbleStyles:I,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},mediaConfig:K,theme:T,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:te,getSocket:U,suggestedQuestions:A?.suggestedQuestions,activeQuiz:q,onQuizAnswer:V,onProposalAction:(e,t)=>"confirm"===t?W(e):H(e),onVoiceActiveChange:Z})})}),!_&&/* @__PURE__ */b("div",{className:Ot(M.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(Bt,{isOpen:M.isOpen,onClick:R,unreadCount:L,position:c?.position||"bottom-right",primaryColor:Lt(T),logoUrl:T.logoUrl,starterPrompt:c?.starterPrompt||A?.starterPrompt,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},emotion:D,styles:I,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??A?.avatarScale,showPromptAvatar:c?.showPromptAvatar??A?.showPromptAvatar})})]}):null}function Ub(e){/* @__PURE__ */
204
204
  return b($t,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Bb,{...e})})}function qb(e){/* @__PURE__ */
205
205
  return b(D,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b($b,{children:/* @__PURE__ */b(Ub,{...e})})})}const Vb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:qb,ChatWidgetInner:Bb,ChatWidgetWithProviders:Ub},Symbol.toStringTag,{value:"Module"}));function Wb({apiKey:e,apiBaseUrl:t="https://api.botuyo.com",sessionKey:n,locale:r="es",onReady:o}){const i=u(()=>({apiKey:e,apiBaseUrl:t,initialOpen:!0,hideLauncher:!0,theme:{position:"bottom-right",defaultLocale:r,cssVariables:{windowBorderRadius:"0px",windowHeight:"100%",windowBottom:"0px"}},onEvent:e=>{"connected"===e&&o&&o()}}),[e,t,r,o]);/* @__PURE__ */
@@ -216,4 +216,4 @@ return y("div",{className:`relative h-full w-full overflow-hidden ${t}`,children
216
216
  /* @__PURE__ */b(Kb,{url:e,autoRotate:S,hasCustomCamera:_,frameRef:v,onLoaded:w,onError:x})]},e),"loading"===g&&/* @__PURE__ */y("div",{className:"pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 text-gray-400",children:[
217
217
  /* @__PURE__ */b("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-current border-t-transparent opacity-70"}),c&&/* @__PURE__ */b("span",{className:"text-xs",children:c})]}),"error"===g&&/* @__PURE__ */y("div",{className:"absolute inset-0 z-20 flex flex-col items-center justify-center gap-1 px-3 text-center text-gray-400",children:[
218
218
  /* @__PURE__ */b(de,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const Xb="https://api.botuyo.com";class ey extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error("[BotUyoChat] Widget error:",e,t)}render(){return this.state.hasError?null:this.props.children}}const ty={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--card-foreground":"0 0% 98%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 3.7% 15.9%","--muted-foreground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},ny=p(()=>Promise.resolve().then(()=>Vb).then(e=>({default:e.ChatWidgetWithProviders})));class ry{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||Xb},this.render(),this.setupDarkModeDetection(),this}render(){if(!this.config)return void console.error("[BotUyoChat] No configuration provided");if(!this.container){this.container=document.createElement("div"),this.container.id="botuyo-chat-widget-root",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=R.replace(/:root/g,":host"),this.shadowRoot.appendChild(e),this.mountPoint=document.createElement("div"),this.mountPoint.id="botuyo-chat-widget-root",this.shadowRoot.appendChild(this.mountPoint)}if(this.config.theme?.cssVariables&&this.mountPoint){const e=this.config.theme.cssVariables;[["--background",e.background],["--foreground",e.foreground],["--card",e.card],["--card-foreground",e.cardForeground],["--primary",e.primary],["--primary-foreground",e.primaryForeground],["--muted",e.muted],["--muted-foreground",e.mutedForeground],["--border",e.border],["--destructive",e.destructive],["--radius",e.radius],["--window-border-radius",e.windowBorderRadius],["--launcher-border-radius",e.launcherBorderRadius],["--window-height",e.windowHeight],["--window-bottom",e.windowBottom],["--spacing-1",e.spacing1],["--spacing-2",e.spacing2],["--spacing-3",e.spacing3],["--spacing-4",e.spacing4],["--spacing-5",e.spacing5],["--spacing-6",e.spacing6],["--spacing-7",e.spacing7],["--spacing-8",e.spacing8]].forEach(([e,t])=>{void 0!==t&&this.mountPoint.style.setProperty(e,t)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const e=document.documentElement.getAttribute("data-theme");return"dark"===e||"light"!==e&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(ty).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(ty).forEach(([e,t])=>{this.mountPoint.style.setProperty(e,t)})),!this.root&&this.mountPoint&&(this.root=e(this.mountPoint));const t={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||Xb,agentId:this.config.agentId,theme:{botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",cssVariables:{primary:"160 84% 39%",windowBorderRadius:"24px",launcherBorderRadius:"50%"},...this.config.theme},userContext:this.config.userContext,pageContext:this.config.pageContext,includeSEOMetadata:this.config.includeSEOMetadata??!1,mediaConfig:this.config.mediaConfig,onNavigate:this.config.onNavigate,onLogin:this.config.onLogin,onEvent:this.config.onEvent,onStateChange:this.config.onStateChange},r=n.createElement(h,{fallback:n.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},n.createElement("div",{style:{width:"24px",height:"24px",border:"3px solid rgba(255, 255, 255, 0.3)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 1s linear infinite"}}))},n.createElement(ny,t));this.root.render(n.createElement(ey,null,n.createElement(D,{defaultLocale:this.config.theme?.defaultLocale,children:r}))),console.log("[BotUyoChat] Widget initialized",t)}update(e){this.config?(this.config={...this.config,...e,theme:{...this.config.theme,...e.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}startCall(){window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const oy=new ry;window.BotUyoChat=oy;export{Qb as A,ry as B,qb as C,X as L,Wb as P,he as X,q as a,Ot as b,Hb as c,Db as d,Ub as e,D as f,Lt as g,jb as h,oy as i,j,O as l,Jb as s,F as u};
219
- //# sourceMappingURL=standalone-DjJrjsUd.js.map
219
+ //# sourceMappingURL=standalone-DoKkud_c.js.map