@botuyo/chat-widget-standalone 1.3.5 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/README.md +1 -1
  2. package/dist/{AudioPlayer-jAcznL1N.js → AudioPlayer-CzaYLuuQ.js} +2 -2
  3. package/dist/{AudioPlayer-jAcznL1N.js.map → AudioPlayer-CzaYLuuQ.js.map} +1 -1
  4. package/dist/{Gallery-CKdV3pMT.js → Gallery-DfZMfTse.js} +2 -2
  5. package/dist/{Gallery-CKdV3pMT.js.map → Gallery-DfZMfTse.js.map} +1 -1
  6. package/dist/botuyo-chat.es.js +1 -1
  7. package/dist/botuyo-chat.umd.js +1 -1
  8. package/dist/botuyo-chat.umd.js.map +1 -1
  9. package/dist/src/chat-widget/ChatWidgetProvider.d.ts +7 -0
  10. package/dist/src/chat-widget/ChatWidgetProvider.d.ts.map +1 -1
  11. package/dist/src/chat-widget/components/ChatWindow.d.ts.map +1 -1
  12. package/dist/src/chat-widget/components/VoiceCallOverlay.d.ts +15 -0
  13. package/dist/src/chat-widget/components/VoiceCallOverlay.d.ts.map +1 -1
  14. package/dist/src/chat-widget/hooks/useChatWidget.d.ts.map +1 -1
  15. package/dist/src/chat-widget/voice/audioEnhancement.d.ts +3 -1
  16. package/dist/src/chat-widget/voice/audioEnhancement.d.ts.map +1 -1
  17. package/dist/src/chat-widget/voice/speechDetector.d.ts +78 -0
  18. package/dist/src/chat-widget/voice/speechDetector.d.ts.map +1 -0
  19. package/dist/src/chat-widget/voice/vadGate.d.ts +137 -0
  20. package/dist/src/chat-widget/voice/vadGate.d.ts.map +1 -0
  21. package/dist/{standalone-DrDCLfVL.js → standalone-DOLAS_vS.js} +60 -60
  22. package/dist/standalone-DOLAS_vS.js.map +1 -0
  23. package/dist/standalone.d.ts +7 -0
  24. package/dist/standalone.d.ts.map +1 -1
  25. package/dist/stats-umd.html +1 -1
  26. package/dist/stats.html +1 -1
  27. package/package.json +1 -1
  28. package/dist/standalone-DrDCLfVL.js.map +0 -1
@@ -15,7 +15,7 @@ return y("div",{className:Et("flex items-center w-fit transition-all duration-50
15
15
  /* @__PURE__ */b(W,{size:10}),
16
16
  /* @__PURE__ */y("span",{children:[e.length," fuente",e.length>1?"s":""]}),
17
17
  /* @__PURE__ */b("span",{className:"transition-transform duration-200",style:{transform:t?"rotate(180deg)":"rotate(0)"},children:"▾"})]}),t&&/* @__PURE__ */b("div",{className:"flex flex-wrap gap-1 mt-1 animate-in fade-in slide-in-from-top-1 duration-200",children:e.map((e,t)=>/* @__PURE__ */y("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-medium rounded-md",style:{backgroundColor:"hsl(var(--muted) / 0.4)",color:"hsl(var(--muted-foreground))"},children:[
18
- /* @__PURE__ */b(W,{size:9}),e]},`${e}-${t}`))})]}):null}),Ul=p(()=>import("./AudioPlayer-jAcznL1N.js").then(e=>({default:e.AudioPlayer}))),ql=p(()=>import("./Gallery-CKdV3pMT.js").then(e=>({default:e.Gallery})));function Vl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
18
+ /* @__PURE__ */b(W,{size:9}),e]},`${e}-${t}`))})]}):null}),Ul=p(()=>import("./AudioPlayer-CzaYLuuQ.js").then(e=>({default:e.AudioPlayer}))),ql=p(()=>import("./Gallery-DfZMfTse.js").then(e=>({default:e.Gallery})));function Vl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
19
19
  return y("div",{className:"space-y-3",children:[
20
20
  /* @__PURE__ */b("div",{className:Et("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(ja,{remarkPlugins:[Il],rehypePlugins:[[$l,{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})}),
21
21
  /* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((i,a)=>{const s=r===i.id;/* @__PURE__ */
@@ -93,50 +93,50 @@ return b("div",{"data-testid":"quiz-dock",className:"shrink-0 border-t animate-i
93
93
  /* @__PURE__ */b("p",{className:"text-sm font-semibold mb-2 text-foreground break-words leading-snug",children:e.content}),
94
94
  /* @__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:[
95
95
  /* @__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)}),
96
- /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function rc(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 oc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=rc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const ic="24px",ac={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},sc=85,lc=.7,cc=200,uc=.5,dc=3e3,pc=1,hc=6,fc=7500,mc=.7,gc=-20,bc=8,yc=6,vc=.002,wc=.12,xc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},kc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...xc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function _c(e=xc,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 a continuous stream keeps server-side VAD accurate\n this.port.postMessage(int16.buffer, [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 Sc=p(()=>import("./Avatar3D-CoXzuLgX.js")),Cc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Ec={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},zc={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"]}}},Nc=24e3;class Ac extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.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 Ic({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||$t:t||$t: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__ */
96
+ /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function rc(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 oc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=rc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const ic="24px",ac={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},sc=85,lc=.7,cc=200,uc=.5,dc=3e3,pc=1,hc=6,fc=7500,mc=.7,gc=-20,bc=8,yc=6,vc=.002,wc=.12,xc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},kc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...xc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function _c(e=xc,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 Sc={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 Cc(e){return void 0===e||"standard"===e?{...Sc.standard}:"string"==typeof e?{...Sc[e]??Sc.standard}:{...Sc.standard,...e}}class Ec{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Sc.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 zc="0.0.30",Nc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/dist/`,Ac=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/+esm`;function Ic(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 Oc{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){Dt("[VAD] error while destroying detector",e)}this._running=!1}}const Mc=p(()=>import("./Avatar3D-CoXzuLgX.js")),Pc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Lc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Dc={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"]}}},jc=24e3;function Fc(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){console.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 $c({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||$t:t||$t: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__ */
97
97
  return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",children:[
98
- /* @__PURE__ */b(Ac,{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(Sc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(Tc,{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:[
98
+ /* @__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(Mc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(Bc,{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:[
99
99
  /* @__PURE__ */y("div",{className:Et("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:[
100
- /* @__PURE__ */b("img",{src:f,alt:"Bot avatar",className:Et("h-full w-full rounded-full object-cover","transition-all duration-300","thinking"===o&&"opacity-80"),style:{boxShadow:"listening"===o?`0 0 0 2px ${s.listeningColor}80`:"speaking"===o?`0 0 0 2px ${s.speakingColor}80`:"none"}}),s.showEmotionLabel&&r&&/* @__PURE__ */y("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full bg-black/70 backdrop-blur-sm text-[10px] font-bold text-white whitespace-nowrap",children:[s.showEmojis&&(s.emotionEmojis[r]||"💬")," ",r]})]}),s.showWaveform&&/* @__PURE__ */b(Tc,{isActive:m,audioLevel:a,color:g})]}:{className:"relative flex flex-col items-center gap-6",children:[
100
+ /* @__PURE__ */b("img",{src:f,alt:"Bot avatar",className:Et("h-full w-full rounded-full object-cover","transition-all duration-300","thinking"===o&&"opacity-80"),style:{boxShadow:"listening"===o?`0 0 0 2px ${s.listeningColor}80`:"speaking"===o?`0 0 0 2px ${s.speakingColor}80`:"none"}}),s.showEmotionLabel&&r&&/* @__PURE__ */y("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full bg-black/70 backdrop-blur-sm text-[10px] font-bold text-white whitespace-nowrap",children:[s.showEmojis&&(s.emotionEmojis[r]||"💬")," ",r]})]}),s.showWaveform&&/* @__PURE__ */b(Bc,{isActive:m,audioLevel:a,color:g})]}:{className:"relative flex flex-col items-center gap-6",children:[
101
101
  /* @__PURE__ */y("div",{className:"relative",style:{width:`${w+48}px`,height:`${w+48}px`},children:[
102
102
  /* @__PURE__ */b("div",{className:"absolute inset-0 rounded-full",style:{border:`1.5px solid ${g}20`,animation:m?"spin 8s linear infinite":"none"}}),
103
103
  /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{inset:"12px",border:`1px solid ${g}15`,animation:m?"spin 12s linear infinite reverse":"none"}}),
104
- /* @__PURE__ */b("div",{className:"absolute rounded-full flex items-center justify-center",style:{inset:"24px",background:`radial-gradient(circle at 35% 35%, ${g}40, ${g}10 60%, transparent 80%)`,boxShadow:m?`0 0 60px ${g}35, 0 0 120px ${g}15, inset 0 0 40px ${g}10`:`0 0 30px ${g}15`,transform:`scale(${v})`,transition:"all 0.5s cubic-bezier(0.4, 0, 0.2, 1)"},children:/* @__PURE__ */b("div",{className:"rounded-full",style:{width:.35*w+"px",height:.35*w+"px",background:`radial-gradient(circle, ${g}90, ${g}40)`,boxShadow:`0 0 20px ${g}60`,animation:m?"pulse 2s ease-in-out infinite":"none"}})}),m&&[0,1,2].map(e=>/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"4px",height:"4px",backgroundColor:g,opacity:.6,top:"50%",left:"50%",transform:`rotate(${120*e}deg) translateX(${(w+48)/2}px)`,animation:`spin ${6+2*e}s linear infinite`,boxShadow:`0 0 6px ${g}`}},e))]}),s.showWaveform&&/* @__PURE__ */b(Tc,{isActive:m,audioLevel:a,color:g})]})}function Tc({isActive:e,audioLevel:t,color:n}){/* @__PURE__ */
104
+ /* @__PURE__ */b("div",{className:"absolute rounded-full flex items-center justify-center",style:{inset:"24px",background:`radial-gradient(circle at 35% 35%, ${g}40, ${g}10 60%, transparent 80%)`,boxShadow:m?`0 0 60px ${g}35, 0 0 120px ${g}15, inset 0 0 40px ${g}10`:`0 0 30px ${g}15`,transform:`scale(${v})`,transition:"all 0.5s cubic-bezier(0.4, 0, 0.2, 1)"},children:/* @__PURE__ */b("div",{className:"rounded-full",style:{width:.35*w+"px",height:.35*w+"px",background:`radial-gradient(circle, ${g}90, ${g}40)`,boxShadow:`0 0 20px ${g}60`,animation:m?"pulse 2s ease-in-out infinite":"none"}})}),m&&[0,1,2].map(e=>/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"4px",height:"4px",backgroundColor:g,opacity:.6,top:"50%",left:"50%",transform:`rotate(${120*e}deg) translateX(${(w+48)/2}px)`,animation:`spin ${6+2*e}s linear infinite`,boxShadow:`0 0 6px ${g}`}},e))]}),s.showWaveform&&/* @__PURE__ */b(Bc,{isActive:m,audioLevel:a,color:g})]})}function Bc({isActive:e,audioLevel:t,color:n}){/* @__PURE__ */
105
105
  return b("div",{className:"flex items-center gap-[3px] h-10",children:Array.from({length:12}).map((r,o)=>{const i=Math.abs(o-5.5)/5.5,a=e?Math.max(4,40*t*(1-.5*i)*(.5+.5*Math.sin(.8*o))):4;/* @__PURE__ */
106
- return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function Oc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onCallEnded:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...Cc,...e?.emotionEmojis},statusLabels:{...Ec,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl,voiceGate:(n=e?.noiseGate,void 0===n||!0===n||"standard"===n?{...kc.standard}:!1===n||"off"===n?{...kc.off}:"string"==typeof n?{...kc[n]??kc.standard}:{...kc.standard,...n})};var n}(d,n),[d,n]);!function(e){const t=f(null);a(()=>{const n="undefined"==typeof navigator?null:navigator.wakeLock??null;if(!e||!n)return;let r=!1;const o=async()=>{if(!t.current||t.current.released)try{const e=await n.request("screen");if(r)return void e.release();t.current=e,e.addEventListener("release",()=>{t.current===e&&(t.current=null)})}catch(e){Dt("[useWakeLock] Could not acquire screen wake lock",e)}},i=()=>{"visible"===document.visibilityState&&o()};return o(),document.addEventListener("visibilitychange",i),()=>{r=!0,document.removeEventListener("visibilitychange",i);const e=t.current;t.current=null,e&&!e.released&&e.release().catch(()=>{})}},[e])}(e);const[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[N,A]=i([]),[I,T]=i(!1),[O,M]=i(""),[P,L]=i(!1),[D,j]=i(null),[F,R]=i(void 0),[$,B]=i(void 0),[U,q]=i(void 0),[V,W]=i(!1),H=f(null),Z=f(null),K=f(null),G=f(null),Y=f(null),te=f(0),ne=f(!1),oe=f(null),ie=f(null),se=f(()=>{}),le=f(null),ce=f(0),ue=f(null),de=f([]),pe=f(!1),he=f(0),fe=f([]),me=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),ge=s(()=>{if(0===de.current.length)return;ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Nc})),"suspended"===ue.current.state&&ue.current.resume().catch(()=>{});const e=ue.current;pe.current=!0,g("speaking");const t=e.currentTime;for(he.current<t&&(he.current=t);de.current.length>0;){const t=de.current.shift(),n=e.createBuffer(1,t.length,Nc);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(he.current),fe.current.push(r),r.onended=()=>{fe.current=fe.current.filter(e=>e!==r),0===fe.current.length&&0===de.current.length&&(pe.current=!1,g(e=>"speaking"===e?"listening":e))},he.current+=t.length/Nc}},[]),be=f({}),ye=s(()=>{const e=r?.();if(!e||ne.current)return;const n=e=>{e&&(R(e.avatars||void 0),B(e.logoUrl||void 0),q(e.avatar3dUrl||void 0),W(!0))},o=e=>{g("listening"),n(e?.agentAvatar)},i=e=>{Se();const t=(e?.agentName||"").toString().trim();j(t||"Nuevo agente"),n(e?.agentAvatar),A(e=>[...e,{role:"bot",text:t?`🔄 Continuás con ${t}.`:"🔄 Te derivé con el área correspondiente.",standalone:!0}])},a=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);de.current.push(t),ge(),Se()},s=()=>{fe.current.forEach(e=>{try{e.stop()}catch{}}),fe.current=[],de.current.length=0,he.current=0,pe.current=!1,g("listening")},l=()=>{},c=e=>{console.error("[VoiceCall] Voice error:",e)},u=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},d=e=>{e?.text&&(Se(),A(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},h=e=>{e?.text&&A(t=>{const n=t.map(e=>e.quizButtons?{...e,quizButtons:void 0}:e),r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):[...n,{role:"user",text:e.text}]})},f=e=>{e?.text&&A(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},m=e=>{e?.text&&(Se(),A(t=>{const n=t[t.length-1];if(n&&"bot"===n.role&&!n.standalone){const r=[...t],o=n.text,i=o.length>0&&!o.endsWith(" ")&&!e.text.startsWith(" ");return r[r.length-1]={...n,text:o+(i?" ":"")+e.text},r}return[...t,{role:"bot",text:e.text}]}))},b=()=>{g("thinking"),Se()},y=e=>{if(!e?.items?.length)return;if(Se(),"present_quiz"===e.tool)return;if("show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?`![${e.label||""}](${e.url})`:e.label||"").filter(Boolean).join("\n");return void(t&&A(e=>[...e,{role:"bot",text:t,standalone:!0}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?`![${t.title}](${t.cover})`:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>`![](${e})`).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return`![${t.label||""}](${t.url})`;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&A(e=>[...e,{role:"bot",text:t,standalone:!0}])},v=e=>{if("quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;t&&n?.length&&(Se(),A(e=>[...e,{role:"bot",text:`📝 ${t}`,quizButtons:n,standalone:!0}]))}};be.current={voiceReady:o,voiceAudioChunk:a,voiceInterrupted:s,voiceTurnComplete:l,voiceError:c,voiceEmotion:u,voiceUserTranscript:d,voiceUserTranscriptFinal:h,voiceUserTranscriptCorrected:f,voiceModelTranscript:m,voiceModelThinking:b,voiceToolVisual:y,voiceCustomEvent:v,voiceAgentSwitched:i},e.on("voice_ready",o),e.on("voice_audio_chunk",a),e.on("voice_interrupted",s),e.on("voice_turn_complete",l),e.on("voice_error",c),e.on("voice_emotion",u),e.on("voice_user_transcript",d),e.on("voice_user_transcript_final",h),e.on("voice_user_transcript_corrected",f),e.on("voice_model_transcript",m),e.on("voice_model_thinking",b),e.on("voice_tool_visual",y),e.on("custom_event",v),e.on("voice_agent_switched",i),e.on("voice_timeout",()=>{se.current()});const w=e=>{p?.(e?.reason),A(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]);const n=r?.();n?.connected&&setTimeout(()=>{try{n.emit("request_history")}catch{}},1500),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",w),be.current.voiceCallEnded=w,ne.current=!0},[r,ge]),ve=s(()=>{const e=r?.();if(!e||!ne.current)return;const t=be.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCustomEvent&&e.off("custom_event",t.voiceCustomEvent),t.voiceAgentSwitched&&e.off("voice_agent_switched",t.voiceAgentSwitched),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),be.current={},ne.current=!1},[r]),we=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:ac});K.current=t;const n=new AudioContext({sampleRate:16e3});G.current=n,"suspended"===n.state&&await n.resume();const o=n.createMediaStreamSource(t),i=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=sc,n.Q.value=lc;const r=e.createBiquadFilter();r.type="highpass",r.frequency.value=cc,r.Q.value=uc;const o=e.createBiquadFilter();o.type="peaking",o.frequency.value=dc,o.Q.value=pc,o.gain.value=hc;const i=e.createBiquadFilter();i.type="lowpass",i.frequency.value=fc,i.Q.value=mc;const a=e.createDynamicsCompressor();return a.threshold.value=gc,a.knee.value=bc,a.ratio.value=yc,a.attack.value=vc,a.release.value=wc,t.connect(n),n.connect(r),r.connect(o),o.connect(i),i.connect(a),a}(n,o),a=n.createAnalyser();if(a.fftSize=256,i.connect(a),Z.current=a,!oe.current){const e=new Blob([_c(h.voiceGate)],{type:"application/javascript"});oe.current=URL.createObjectURL(e)}await n.audioWorklet.addModule(oe.current);const s=new AudioWorkletNode(n,"voice-pcm-processor");Y.current=s,s.port.onmessage=t=>{if(e.connected&&!k){const n=function(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(t.data);e.emit("voice_audio_chunk",{data:n})}},i.connect(s);const l=()=>{if(!Z.current)return;const e=new Uint8Array(Z.current.frequencyBinCount);Z.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),te.current=requestAnimationFrame(l)};l()},[r,k,h.voiceGate]),xe=s(()=>{cancelAnimationFrame(te.current),Y.current?.disconnect(),Y.current=null,K.current?.getTracks().forEach(e=>e.stop()),K.current=null,G.current?.close(),G.current=null,Z.current=null,C(0)},[]),ke=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),A([]),z(null),R(void 0),B(void 0),q(void 0),W(!1),de.current=[],ye(),ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Nc})),ue.current.resume().catch(()=>{});try{await we()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{language:"es-AR",voice:"Kore"}),H.current=setInterval(()=>{x(e=>e+1)},1e3),Ce()}else console.error("[VoiceCall] Socket not connected")},[r,ye,we]),_e=s(()=>{xe(),fe.current.forEach(e=>{try{e.stop()}catch{}}),fe.current=[],de.current=[],he.current=0,pe.current=!1,ue.current?.close(),ue.current=null,H.current&&(clearInterval(H.current),H.current=null),le.current&&(clearInterval(le.current),le.current=null);const e=r?.();e?.connected&&(e.emit("voice_stop"),setTimeout(()=>{try{e.emit("request_history")}catch{}},1500)),ve(),g("idle"),C(0),x(0),_(!1),A([]),L(!1),j(null),R(void 0),B(void 0),q(void 0),W(!1),t()},[r,xe,ve,t]);a(()=>{se.current=_e},[_e]);const Se=s(()=>{ce.current=0,L(!1)},[]),Ce=s(()=>{ce.current=0,le.current&&clearInterval(le.current),le.current=setInterval(()=>{ce.current+=1;const e=ce.current;e>=90&&e<120&&L(!0),e>=120&&se.current()},1e3)},[]),Ee=s(()=>{_(e=>!e)},[]),ze=s(()=>{const e=O.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),M(""),T(!1))},[O,r]);if(a(()=>{e&&"idle"===m&&ke()},[e]),a(()=>{ie.current?.scrollIntoView({behavior:"smooth"})},[N]),a(()=>()=>{xe(),H.current&&clearInterval(H.current),ve()},[]),!e)return null;const Ne="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n,Ae=V?F:o,Ie=V?$:l,Te=(V?U:c)||h.avatar3dUrl;let Oe=-1;for(let i=N.length-1;i>=0;i--)if(N[i].quizButtons&&N[i].quizButtons.length>0){Oe=i;break}const Me=Oe>=0?N[Oe]:null;/* @__PURE__ */
106
+ return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function Uc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onCallEnded:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...Pc,...e?.emotionEmojis},statusLabels:{...Lc,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl,voiceGate:(n=e?.noiseGate,void 0===n||!0===n||"standard"===n?{...kc.standard}:!1===n||"off"===n?{...kc.off}:"string"==typeof n?{...kc[n]??kc.standard}:{...kc.standard,...n}),vad:!1!==e?.vad&&Cc(e?.vad),vadAssetBaseUrl:e?.vadAssetBaseUrl};var n}(d,n),[d,n]);!function(e){const t=f(null);a(()=>{const n="undefined"==typeof navigator?null:navigator.wakeLock??null;if(!e||!n)return;let r=!1;const o=async()=>{if(!t.current||t.current.released)try{const e=await n.request("screen");if(r)return void e.release();t.current=e,e.addEventListener("release",()=>{t.current===e&&(t.current=null)})}catch(e){Dt("[useWakeLock] Could not acquire screen wake lock",e)}},i=()=>{"visible"===document.visibilityState&&o()};return o(),document.addEventListener("visibilitychange",i),()=>{r=!0,document.removeEventListener("visibilitychange",i);const e=t.current;t.current=null,e&&!e.released&&e.release().catch(()=>{})}},[e])}(e);const[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[N,A]=i([]),[I,T]=i(!1),[O,M]=i(""),[P,L]=i(!1),[D,j]=i(null),[F,R]=i(void 0),[$,B]=i(void 0),[U,q]=i(void 0),[V,W]=i(!1),H=f(null),Z=f(null),K=f(null),G=f(null),Y=f(null),te=f(0),ne=f(!1),oe=f(null),ie=f(null),se=f(()=>{}),le=f(null),ce=f(0),ue=f(null),de=f([]),pe=f(!1),he=f(0),fe=f([]),me=f(null),ge=f(null),be=f(1),ye=f(0),ve=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),we=s(()=>{if(0===de.current.length)return;ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:jc})),"suspended"===ue.current.state&&ue.current.resume().catch(()=>{});const e=ue.current;pe.current=!0,g("speaking");const t=e.currentTime;for(he.current<t&&(he.current=t);de.current.length>0;){const t=de.current.shift(),n=e.createBuffer(1,t.length,jc);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(he.current),fe.current.push(r),r.onended=()=>{fe.current=fe.current.filter(e=>e!==r),0===fe.current.length&&0===de.current.length&&(pe.current=!1,g(e=>"speaking"===e?"listening":e))},he.current+=t.length/jc}},[]),xe=s(()=>{fe.current.forEach(e=>{try{e.stop()}catch{}}),fe.current=[],de.current.length=0,he.current=0,pe.current=!1,g("listening")},[]),ke=f({}),_e=s(()=>{const e=r?.();if(!e||ne.current)return;const n=e=>{e&&(R(e.avatars||void 0),B(e.logoUrl||void 0),q(e.avatar3dUrl||void 0),W(!0))},o=e=>{g("listening"),n(e?.agentAvatar)},i=e=>{Ae();const t=(e?.agentName||"").toString().trim();j(t||"Nuevo agente"),n(e?.agentAvatar),A(e=>[...e,{role:"bot",text:t?`🔄 Continuás con ${t}.`:"🔄 Te derivé con el área correspondiente.",standalone:!0}])},a=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);de.current.push(t),we(),Ae()},s=()=>{xe()},l=()=>{},c=e=>{console.error("[VoiceCall] Voice error:",e)},u=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},d=e=>{e?.text&&(Ae(),A(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},h=e=>{e?.text&&A(t=>{const n=t.map(e=>e.quizButtons?{...e,quizButtons:void 0}:e),r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):[...n,{role:"user",text:e.text}]})},f=e=>{e?.text&&A(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},m=e=>{e?.text&&(Ae(),A(t=>{const n=t[t.length-1];if(n&&"bot"===n.role&&!n.standalone){const r=[...t],o=n.text,i=o.length>0&&!o.endsWith(" ")&&!e.text.startsWith(" ");return r[r.length-1]={...n,text:o+(i?" ":"")+e.text},r}return[...t,{role:"bot",text:e.text}]}))},b=()=>{g("thinking"),Ae()},y=e=>{if(!e?.items?.length)return;if(Ae(),"present_quiz"===e.tool)return;if("show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?`![${e.label||""}](${e.url})`:e.label||"").filter(Boolean).join("\n");return void(t&&A(e=>[...e,{role:"bot",text:t,standalone:!0}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?`![${t.title}](${t.cover})`:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>`![](${e})`).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return`![${t.label||""}](${t.url})`;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&A(e=>[...e,{role:"bot",text:t,standalone:!0}])},v=e=>{if("quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;t&&n?.length&&(Ae(),A(e=>[...e,{role:"bot",text:`📝 ${t}`,quizButtons:n,standalone:!0}]))}};ke.current={voiceReady:o,voiceAudioChunk:a,voiceInterrupted:s,voiceTurnComplete:l,voiceError:c,voiceEmotion:u,voiceUserTranscript:d,voiceUserTranscriptFinal:h,voiceUserTranscriptCorrected:f,voiceModelTranscript:m,voiceModelThinking:b,voiceToolVisual:y,voiceCustomEvent:v,voiceAgentSwitched:i},e.on("voice_ready",o),e.on("voice_audio_chunk",a),e.on("voice_interrupted",s),e.on("voice_turn_complete",l),e.on("voice_error",c),e.on("voice_emotion",u),e.on("voice_user_transcript",d),e.on("voice_user_transcript_final",h),e.on("voice_user_transcript_corrected",f),e.on("voice_model_transcript",m),e.on("voice_model_thinking",b),e.on("voice_tool_visual",y),e.on("custom_event",v),e.on("voice_agent_switched",i),e.on("voice_timeout",()=>{se.current()});const w=e=>{p?.(e?.reason),A(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]);const n=r?.();n?.connected&&setTimeout(()=>{try{n.emit("request_history")}catch{}},1500),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",w),ke.current.voiceCallEnded=w,ne.current=!0},[r,we,xe]),Se=s(()=>{const e=r?.();if(!e||!ne.current)return;const t=ke.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCustomEvent&&e.off("custom_event",t.voiceCustomEvent),t.voiceAgentSwitched&&e.off("voice_agent_switched",t.voiceAgentSwitched),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),ke.current={},ne.current=!1},[r]),Ce=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:ac});K.current=t;const n=!1!==h.vad;me.current=new Ec(n?h.vad:{energyOnly:!0}),be.current=1,ye.current=0,n&&async function(e){const t=e.loadVad??Tc;try{const n=await t(),r=(t,n)=>{e.onFrame({speechProb:t?.isSpeech??0,rms:Ic(n)})},o=await n.MicVAD.new(function(e,t){const n={model:e.model??"v5",baseAssetPath:e.assetBaseUrl??Nc,onnxWASMBasePath:e.onnxWasmBaseUrl??"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",startOnLoad:!1,onFrameProcessed:t};if(e.audioContext&&(n.audioContext=e.audioContext),e.stream){const t=e.stream;n.getStream=async()=>t,n.pauseStream=async()=>{},n.resumeStream=async()=>{}}return n}(e,r));return Rt("[VAD] Silero speech detector ready"),new Oc(o)}catch(n){return Dt("[VAD] Silero unavailable — falling back to energy gate",n),null}}({stream:t,assetBaseUrl:h.vadAssetBaseUrl,onFrame:({speechProb:e})=>{be.current=e,ye.current=performance.now()}}).then(e=>{if(e){if(K.current)return ge.current=e,e.start();e.destroy()}}).catch(()=>{});const o=new AudioContext({sampleRate:16e3});G.current=o,"suspended"===o.state&&await o.resume();const i=o.createMediaStreamSource(t),a=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=sc,n.Q.value=lc;const r=e.createBiquadFilter();r.type="highpass",r.frequency.value=cc,r.Q.value=uc;const o=e.createBiquadFilter();o.type="peaking",o.frequency.value=dc,o.Q.value=pc,o.gain.value=hc;const i=e.createBiquadFilter();i.type="lowpass",i.frequency.value=fc,i.Q.value=mc;const a=e.createDynamicsCompressor();return a.threshold.value=gc,a.knee.value=bc,a.ratio.value=yc,a.attack.value=vc,a.release.value=wc,t.connect(n),n.connect(r),r.connect(o),o.connect(i),i.connect(a),a}(o,i),s=o.createAnalyser();if(s.fftSize=256,a.connect(s),Z.current=s,!oe.current){const e=new Blob([_c(h.voiceGate)],{type:"application/javascript"});oe.current=URL.createObjectURL(e)}await o.audioWorklet.addModule(oe.current);const l=new AudioWorkletNode(o,"voice-pcm-processor");Y.current=l,l.port.onmessage=t=>{const n=me.current;if(!n)return;const r=performance.now()-ye.current<600,{frame:o,confirmedSpeech:i}=function(e){return e.botSpeaking&&!e.vadFresh?{frame:{speechProb:0,rms:0,botSpeaking:!0},confirmedSpeech:!1}:{frame:{speechProb:e.vadFresh?e.speechProb:1,rms:e.rms,botSpeaking:e.botSpeaking},confirmedSpeech:e.vadFresh}}({botSpeaking:pe.current,vadFresh:r,speechProb:be.current,rms:t.data.rms}),{shouldStream:a,event:s}=n.process(o);if("barge_in"===s&&xe(),a&&e.connected&&!k){const n=function(e){return e.confirmedSpeech||!e.vadFresh}({confirmedSpeech:i,vadFresh:r});e.emit("voice_audio_chunk",{data:Fc(t.data.pcm),speech:n})}},a.connect(l);const c=()=>{if(!Z.current)return;const e=new Uint8Array(Z.current.frequencyBinCount);Z.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),te.current=requestAnimationFrame(c)};c()},[r,k,h.voiceGate,h.vad,h.vadAssetBaseUrl,xe]),Ee=s(()=>{cancelAnimationFrame(te.current),ge.current?.destroy(),ge.current=null,me.current=null,be.current=1,ye.current=0,Y.current?.disconnect(),Y.current=null,K.current?.getTracks().forEach(e=>e.stop()),K.current=null,G.current?.close(),G.current=null,Z.current=null,C(0)},[]),ze=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),A([]),z(null),R(void 0),B(void 0),q(void 0),W(!1),de.current=[],_e(),ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:jc})),ue.current.resume().catch(()=>{});try{await Ce()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{language:"es-AR",voice:"Kore"}),H.current=setInterval(()=>{x(e=>e+1)},1e3),Ie()}else console.error("[VoiceCall] Socket not connected")},[r,_e,Ce]),Ne=s(()=>{Ee(),fe.current.forEach(e=>{try{e.stop()}catch{}}),fe.current=[],de.current=[],he.current=0,pe.current=!1,ue.current?.close(),ue.current=null,H.current&&(clearInterval(H.current),H.current=null),le.current&&(clearInterval(le.current),le.current=null);const e=r?.();e?.connected&&(e.emit("voice_stop"),setTimeout(()=>{try{e.emit("request_history")}catch{}},1500)),Se(),g("idle"),C(0),x(0),_(!1),A([]),L(!1),j(null),R(void 0),B(void 0),q(void 0),W(!1),t()},[r,Ee,Se,t]);a(()=>{se.current=Ne},[Ne]);const Ae=s(()=>{ce.current=0,L(!1)},[]),Ie=s(()=>{ce.current=0,le.current&&clearInterval(le.current),le.current=setInterval(()=>{ce.current+=1;const e=ce.current;e>=90&&e<120&&L(!0),e>=120&&se.current()},1e3)},[]),Te=s(()=>{_(e=>!e)},[]),Oe=s(()=>{const e=O.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),M(""),T(!1))},[O,r]);if(a(()=>{e&&"idle"===m&&ze()},[e]),a(()=>{ie.current?.scrollIntoView({behavior:"smooth"})},[N]),a(()=>()=>{Ee(),H.current&&clearInterval(H.current),Se()},[]),!e)return null;const Me="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n,Pe=V?F:o,Le=V?$:l,De=(V?U:c)||h.avatar3dUrl;let je=-1;for(let i=N.length-1;i>=0;i--)if(N[i].quizButtons&&N[i].quizButtons.length>0){je=i;break}const Fe=je>=0?N[je]:null;/* @__PURE__ */
107
107
  return y("div",{className:Et("absolute inset-0 z-50 flex flex-col overflow-hidden","animate-in fade-in duration-300"),style:{backgroundColor:"#0a0a0f",borderRadius:"inherit"},children:[
108
108
  /* @__PURE__ */y("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"hidden"},children:[
109
- /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"300px",height:"300px",top:"-80px",right:"-60px",background:`radial-gradient(circle, ${Ne}18 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(40px)"}}),
109
+ /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"300px",height:"300px",top:"-80px",right:"-60px",background:`radial-gradient(circle, ${Me}18 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(40px)"}}),
110
110
  /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"250px",height:"250px",bottom:"-40px",left:"-50px",background:`radial-gradient(circle, ${h.thinkingColor}12 0%, transparent 70%)`,filter:"blur(50px)"}}),
111
- /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"200px",height:"200px",top:"40%",left:"50%",transform:"translateX(-50%)",background:`radial-gradient(circle, ${Ne}10 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(60px)"}})]}),
111
+ /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"200px",height:"200px",top:"40%",left:"50%",transform:"translateX(-50%)",background:`radial-gradient(circle, ${Me}10 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(60px)"}})]}),
112
112
  /* @__PURE__ */y("div",{className:"relative flex items-center justify-between",style:{background:"rgba(255,255,255,0.03)",borderBottom:"1px solid rgba(255,255,255,0.06)",padding:"16px 24px",paddingTop:"20px"},children:[
113
113
  /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[
114
- /* @__PURE__ */b("div",{className:"relative",children:/* @__PURE__ */b("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Ne,boxShadow:`0 0 8px ${Ne}80`,animation:"idle"!==m?"pulse 2s ease-in-out infinite":"none"}})}),
114
+ /* @__PURE__ */b("div",{className:"relative",children:/* @__PURE__ */b("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Me,boxShadow:`0 0 8px ${Me}80`,animation:"idle"!==m?"pulse 2s ease-in-out infinite":"none"}})}),
115
115
  /* @__PURE__ */b("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"13px",fontWeight:500,letterSpacing:"-0.01em"},children:h.statusLabels[m]||m})]}),
116
- /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[h.showEmotionLabel&&E&&/* @__PURE__ */y("span",{style:{fontSize:"11px",padding:"2px 10px",borderRadius:"20px",background:`${Ne}15`,border:`1px solid ${Ne}25`,color:Ne,fontWeight:600},children:[h.showEmojis&&(h.emotionEmojis[E]||"💬")," ",E]}),D&&/* @__PURE__ */y("span",{style:{fontSize:"11px",padding:"2px 10px",borderRadius:"20px",background:`${n}22`,border:`1px solid ${n}44`,color:"#fff",fontWeight:600},children:["🔄 ",D]}),
117
- /* @__PURE__ */b("span",{style:{fontSize:"13px",fontFamily:"ui-monospace, monospace",color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums"},children:me(w)}),P&&(()=>{const e=120-ce.current,t=e<=15;/* @__PURE__ */
116
+ /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[h.showEmotionLabel&&E&&/* @__PURE__ */y("span",{style:{fontSize:"11px",padding:"2px 10px",borderRadius:"20px",background:`${Me}15`,border:`1px solid ${Me}25`,color:Me,fontWeight:600},children:[h.showEmojis&&(h.emotionEmojis[E]||"💬")," ",E]}),D&&/* @__PURE__ */y("span",{style:{fontSize:"11px",padding:"2px 10px",borderRadius:"20px",background:`${n}22`,border:`1px solid ${n}44`,color:"#fff",fontWeight:600},children:["🔄 ",D]}),
117
+ /* @__PURE__ */b("span",{style:{fontSize:"13px",fontFamily:"ui-monospace, monospace",color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums"},children:ve(w)}),P&&(()=>{const e=120-ce.current,t=e<=15;/* @__PURE__ */
118
118
  return y("span",{style:{fontSize:"10px",padding:"2px 8px",borderRadius:"12px",backgroundColor:t?"rgba(239,68,68,0.2)":"rgba(245,158,11,0.15)",color:t?"#ef4444":"#f59e0b",fontWeight:700,fontVariantNumeric:"tabular-nums",animation:t?"pulse 1s ease-in-out infinite":"none"},children:["⏸ Inactivo — ",e>0?e:0,"s"]})})()]})]}),h.showBadge&&h.badgeText&&/* @__PURE__ */b("div",{style:{display:"flex",justifyContent:"center",padding:"8px 0"},children:/* @__PURE__ */b("span",{style:{padding:"4px 14px",borderRadius:"20px",fontSize:"11px",fontWeight:700,background:`linear-gradient(135deg, ${n}, ${h.thinkingColor})`,color:"white"},children:h.badgeText})}),
119
- /* @__PURE__ */b("div",{className:"relative shrink-0 flex justify-center",style:{padding:"16px 20px 8px"},children:/* @__PURE__ */b(Ic,{avatars:Ae,logoUrl:Ie,avatar3dUrl:Te,emotion:E,callState:m,audioLevel:S,config:h})}),
120
- /* @__PURE__ */b("div",{className:"relative flex-1 overflow-y-auto px-5 pb-4",style:{scrollbarWidth:"none"},children:/* @__PURE__ */b("div",{className:"flex flex-col gap-4 w-full",children:N.length>0&&/* @__PURE__ */y("div",{style:{display:"flex",flexDirection:"column",gap:"12px",width:"100%"},children:[N.map((e,t)=>t===Oe?null:/* @__PURE__ */b("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"user"===e.role?"16px 16px 4px 16px":"16px 16px 16px 4px",fontSize:"13.5px",lineHeight:1.5,color:"white",marginLeft:"user"===e.role?"auto":"0",marginRight:"user"===e.role?"0":"auto",backgroundColor:"user"===e.role?"rgba(255,255,255,0.08)":`${n}25`,backdropFilter:"blur(8px)",border:"user"===e.role?"1px solid rgba(255,255,255,0.08)":`1px solid ${n}20`},children:/* @__PURE__ */b("div",{className:"prose prose-sm prose-invert max-w-none break-words leading-relaxed",style:{fontSize:"13.5px"},children:/* @__PURE__ */b(ja,{remarkPlugins:[Il],rehypePlugins:[[$l,zc]],components:{p:({children:e})=>/* @__PURE__ */b("p",{style:{margin:"0 0 4px"},children:e}),a:({href:e,children:t})=>{if(!e)return null;const r=String(t).toLowerCase(),o=r.includes("reservar")||r.includes("ver")||r.includes("pagar");return e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps")?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",margin:"6px 0",borderRadius:"10px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:n,textDecoration:"none",fontSize:"12px",fontWeight:700},children:"📍 Ver ubicación"}):o?/* @__PURE__ */y("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",padding:"8px 16px",margin:"6px 0",borderRadius:"10px",background:n,color:"white",textDecoration:"none",fontSize:"11px",fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",width:"100%",textAlign:"center"},children:[t," →"]}):/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:n,textDecoration:"underline",fontWeight:600},children:t})},strong:({children:e})=>/* @__PURE__ */b("strong",{style:{fontWeight:700,color:"rgba(255,255,255,0.95)"},children:e}),em:({children:e})=>/* @__PURE__ */b("em",{style:{color:"rgba(255,255,255,0.8)"},children:e}),ul:({children:e})=>/* @__PURE__ */b("ul",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),ol:({children:e})=>/* @__PURE__ */b("ol",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),li:({children:e})=>/* @__PURE__ */b("li",{style:{marginBottom:"2px"},children:e}),hr:()=>/* @__PURE__ */b("hr",{style:{border:"none",borderTop:"1px solid rgba(255,255,255,0.1)",margin:"8px 0"}}),img:({src:e,alt:t})=>/* @__PURE__ */b("img",{src:e,alt:t||"",style:{maxWidth:"100%",borderRadius:"8px",margin:"6px 0"}}),code:({children:e})=>/* @__PURE__ */b("code",{style:{background:"rgba(255,255,255,0.1)",padding:"1px 5px",borderRadius:"4px",fontSize:"12px"},children:e})},children:e.text})})},t)),
121
- /* @__PURE__ */b("div",{ref:ie})]})})}),Me&&Me.quizButtons&&Me.quizButtons.length>0&&/* @__PURE__ */b("div",{"data-testid":"voice-quiz-dock",style:{flexShrink:0,padding:"0 20px 10px"},children:/* @__PURE__ */y("div",{style:{borderRadius:"18px",padding:"14px 16px",background:"rgba(255,255,255,0.06)",border:`1px solid ${n}55`,backdropFilter:"blur(12px)",boxShadow:"0 6px 24px rgba(0,0,0,0.35)",maxHeight:"42vh",overflowY:"auto"},children:[
122
- /* @__PURE__ */b("div",{style:{color:"white",fontSize:"14px",fontWeight:600,lineHeight:1.4,marginBottom:"12px"},children:Me.text}),
123
- /* @__PURE__ */b("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:Me.quizButtons.map((e,t)=>/* @__PURE__ */y("button",{onClick:()=>((e,t)=>{const n=r?.();n?.connected&&n.emit("voice_text_input",{text:`Answer: ${t.label}`}),A(n=>[...n.map((t,n)=>n===e?{...t,quizButtons:void 0}:t),{role:"user",text:t.label}])})(Oe,e),style:{display:"flex",alignItems:"center",gap:"12px",width:"100%",padding:"14px 16px",borderRadius:"14px",border:"1px solid rgba(255,255,255,0.18)",background:`linear-gradient(135deg, ${n}, ${n}cc)`,color:"white",fontSize:"14px",fontWeight:700,cursor:"pointer",textAlign:"left",boxShadow:`0 4px 14px ${n}55, inset 0 1px 0 rgba(255,255,255,0.25)`,transition:"all 150ms ease"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-2px)",e.currentTarget.style.boxShadow=`0 8px 22px ${n}77, inset 0 1px 0 rgba(255,255,255,0.3)`},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow=`0 4px 14px ${n}55, inset 0 1px 0 rgba(255,255,255,0.25)`},children:[
119
+ /* @__PURE__ */b("div",{className:"relative shrink-0 flex justify-center",style:{padding:"16px 20px 8px"},children:/* @__PURE__ */b($c,{avatars:Pe,logoUrl:Le,avatar3dUrl:De,emotion:E,callState:m,audioLevel:S,config:h})}),
120
+ /* @__PURE__ */b("div",{className:"relative flex-1 overflow-y-auto px-5 pb-4",style:{scrollbarWidth:"none"},children:/* @__PURE__ */b("div",{className:"flex flex-col gap-4 w-full",children:N.length>0&&/* @__PURE__ */y("div",{style:{display:"flex",flexDirection:"column",gap:"12px",width:"100%"},children:[N.map((e,t)=>t===je?null:/* @__PURE__ */b("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"user"===e.role?"16px 16px 4px 16px":"16px 16px 16px 4px",fontSize:"13.5px",lineHeight:1.5,color:"white",marginLeft:"user"===e.role?"auto":"0",marginRight:"user"===e.role?"0":"auto",backgroundColor:"user"===e.role?"rgba(255,255,255,0.08)":`${n}25`,backdropFilter:"blur(8px)",border:"user"===e.role?"1px solid rgba(255,255,255,0.08)":`1px solid ${n}20`},children:/* @__PURE__ */b("div",{className:"prose prose-sm prose-invert max-w-none break-words leading-relaxed",style:{fontSize:"13.5px"},children:/* @__PURE__ */b(ja,{remarkPlugins:[Il],rehypePlugins:[[$l,Dc]],components:{p:({children:e})=>/* @__PURE__ */b("p",{style:{margin:"0 0 4px"},children:e}),a:({href:e,children:t})=>{if(!e)return null;const r=String(t).toLowerCase(),o=r.includes("reservar")||r.includes("ver")||r.includes("pagar");return e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps")?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",margin:"6px 0",borderRadius:"10px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:n,textDecoration:"none",fontSize:"12px",fontWeight:700},children:"📍 Ver ubicación"}):o?/* @__PURE__ */y("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",padding:"8px 16px",margin:"6px 0",borderRadius:"10px",background:n,color:"white",textDecoration:"none",fontSize:"11px",fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",width:"100%",textAlign:"center"},children:[t," →"]}):/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:n,textDecoration:"underline",fontWeight:600},children:t})},strong:({children:e})=>/* @__PURE__ */b("strong",{style:{fontWeight:700,color:"rgba(255,255,255,0.95)"},children:e}),em:({children:e})=>/* @__PURE__ */b("em",{style:{color:"rgba(255,255,255,0.8)"},children:e}),ul:({children:e})=>/* @__PURE__ */b("ul",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),ol:({children:e})=>/* @__PURE__ */b("ol",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),li:({children:e})=>/* @__PURE__ */b("li",{style:{marginBottom:"2px"},children:e}),hr:()=>/* @__PURE__ */b("hr",{style:{border:"none",borderTop:"1px solid rgba(255,255,255,0.1)",margin:"8px 0"}}),img:({src:e,alt:t})=>/* @__PURE__ */b("img",{src:e,alt:t||"",style:{maxWidth:"100%",borderRadius:"8px",margin:"6px 0"}}),code:({children:e})=>/* @__PURE__ */b("code",{style:{background:"rgba(255,255,255,0.1)",padding:"1px 5px",borderRadius:"4px",fontSize:"12px"},children:e})},children:e.text})})},t)),
121
+ /* @__PURE__ */b("div",{ref:ie})]})})}),Fe&&Fe.quizButtons&&Fe.quizButtons.length>0&&/* @__PURE__ */b("div",{"data-testid":"voice-quiz-dock",style:{flexShrink:0,padding:"0 20px 10px"},children:/* @__PURE__ */y("div",{style:{borderRadius:"18px",padding:"14px 16px",background:"rgba(255,255,255,0.06)",border:`1px solid ${n}55`,backdropFilter:"blur(12px)",boxShadow:"0 6px 24px rgba(0,0,0,0.35)",maxHeight:"42vh",overflowY:"auto"},children:[
122
+ /* @__PURE__ */b("div",{style:{color:"white",fontSize:"14px",fontWeight:600,lineHeight:1.4,marginBottom:"12px"},children:Fe.text}),
123
+ /* @__PURE__ */b("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:Fe.quizButtons.map((e,t)=>/* @__PURE__ */y("button",{onClick:()=>((e,t)=>{const n=r?.();n?.connected&&n.emit("voice_text_input",{text:`Answer: ${t.label}`}),A(n=>[...n.map((t,n)=>n===e?{...t,quizButtons:void 0}:t),{role:"user",text:t.label}])})(je,e),style:{display:"flex",alignItems:"center",gap:"12px",width:"100%",padding:"14px 16px",borderRadius:"14px",border:"1px solid rgba(255,255,255,0.18)",background:`linear-gradient(135deg, ${n}, ${n}cc)`,color:"white",fontSize:"14px",fontWeight:700,cursor:"pointer",textAlign:"left",boxShadow:`0 4px 14px ${n}55, inset 0 1px 0 rgba(255,255,255,0.25)`,transition:"all 150ms ease"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-2px)",e.currentTarget.style.boxShadow=`0 8px 22px ${n}77, inset 0 1px 0 rgba(255,255,255,0.3)`},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow=`0 4px 14px ${n}55, inset 0 1px 0 rgba(255,255,255,0.25)`},children:[
124
124
  /* @__PURE__ */b("span",{style:{flexShrink:0,width:"22px",height:"22px",borderRadius:"50%",background:"#ffffff",color:n,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700},children:t+1}),
125
125
  /* @__PURE__ */b("span",{style:{flex:1},children:e.label})]},e.id))})]})}),
126
126
  /* @__PURE__ */b("div",{style:{textAlign:"center",paddingBottom:"12px"},children:/* @__PURE__ */b("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 16px",borderRadius:"20px",fontSize:"11px",fontWeight:500,color:"rgba(255,255,255,0.35)",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.06)",letterSpacing:"0.02em"},children:k?/* @__PURE__ */y(v,{children:[
127
127
  /* @__PURE__ */b(Q,{style:{width:"12px",height:"12px"}})," Micrófono silenciado"]}):"thinking"===m?"Procesando...":"speaking"===m?/* @__PURE__ */y(v,{children:[
128
128
  /* @__PURE__ */b(ae,{style:{width:"12px",height:"12px"}})," Respuesta de voz"]}):"Habla cuando quieras"})}),
129
129
  /* @__PURE__ */y("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"20px",paddingBottom:"28px",paddingTop:"8px"},children:[
130
- /* @__PURE__ */b("button",{onClick:Ee,style:{width:"52px",height:"52px",borderRadius:"50%",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.2s",backgroundColor:k?"rgba(239,68,68,0.15)":"rgba(255,255,255,0.08)",color:k?"#f87171":"rgba(255,255,255,0.7)",backdropFilter:"blur(12px)",border:"1px solid "+(k?"rgba(239,68,68,0.2)":"rgba(255,255,255,0.08)")},"aria-label":k?"Activar micrófono":"Silenciar micrófono",children:/* @__PURE__ */b(k?Q:X,{style:{width:"22px",height:"22px"}})}),
131
- /* @__PURE__ */b("button",{onClick:_e,style:{width:"64px",height:"64px",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#ef4444",color:"white",boxShadow:"0 4px 24px rgba(239,68,68,0.4), 0 0 0 4px rgba(239,68,68,0.1)",transition:"all 0.2s"},"aria-label":"Finalizar llamada",children:/* @__PURE__ */b(ee,{style:{width:"26px",height:"26px"}})}),
130
+ /* @__PURE__ */b("button",{onClick:Te,style:{width:"52px",height:"52px",borderRadius:"50%",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.2s",backgroundColor:k?"rgba(239,68,68,0.15)":"rgba(255,255,255,0.08)",color:k?"#f87171":"rgba(255,255,255,0.7)",backdropFilter:"blur(12px)",border:"1px solid "+(k?"rgba(239,68,68,0.2)":"rgba(255,255,255,0.08)")},"aria-label":k?"Activar micrófono":"Silenciar micrófono",children:/* @__PURE__ */b(k?Q:X,{style:{width:"22px",height:"22px"}})}),
131
+ /* @__PURE__ */b("button",{onClick:Ne,style:{width:"64px",height:"64px",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#ef4444",color:"white",boxShadow:"0 4px 24px rgba(239,68,68,0.4), 0 0 0 4px rgba(239,68,68,0.1)",transition:"all 0.2s"},"aria-label":"Finalizar llamada",children:/* @__PURE__ */b(ee,{style:{width:"26px",height:"26px"}})}),
132
132
  /* @__PURE__ */b("div",{style:{width:"52px",height:"52px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"speaking"===m?`${h.listeningColor}15`:"rgba(255,255,255,0.08)",color:"speaking"===m?h.listeningColor:"rgba(255,255,255,0.5)",border:"1px solid "+("speaking"===m?`${h.listeningColor}25`:"rgba(255,255,255,0.08)"),transition:"all 0.3s"},children:/* @__PURE__ */b(ae,{style:{width:"22px",height:"22px"}})}),
133
133
  /* @__PURE__ */b("button",{onClick:()=>T(e=>!e),style:{width:"52px",height:"52px",borderRadius:"50%",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.2s",backgroundColor:I?`${n}20`:"rgba(255,255,255,0.08)",color:I?n:"rgba(255,255,255,0.5)",border:"1px solid "+(I?`${n}30`:"rgba(255,255,255,0.08)")},"aria-label":"Escribir texto",children:/* @__PURE__ */b(J,{style:{width:"20px",height:"20px"}})})]}),I&&/* @__PURE__ */y("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 20px 20px"},children:[
134
- /* @__PURE__ */b("input",{type:"text",value:O,onChange:e=>M(e.target.value),onKeyDown:e=>"Enter"===e.key&&ze(),placeholder:"Escribí email, teléfono, etc.",autoFocus:!0,style:{flex:1,padding:"10px 14px",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.12)",background:"rgba(255,255,255,0.06)",color:"white",fontSize:"13px",outline:"none",backdropFilter:"blur(8px)"}}),
135
- /* @__PURE__ */b("button",{onClick:ze,disabled:!O.trim(),style:{width:"40px",height:"40px",borderRadius:"50%",border:"none",cursor:O.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:O.trim()?n:"rgba(255,255,255,0.06)",color:O.trim()?"white":"rgba(255,255,255,0.2)",transition:"all 0.2s"},"aria-label":"Enviar texto",children:/* @__PURE__ */b(re,{style:{width:"16px",height:"16px"}})})]}),
136
- /* @__PURE__ */b("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(0.95); }\n }\n "})]})}function Mc({isOpen:e,isConnected:t,isTyping:n,messages:r,botName:o="BotUyo",logoUrl:l,welcomeMessage:c,inputPlaceholder:u,mediaConfig:d,onClose:p,onSendMessage:h,bubbleStyles:m,avatars:g,onSendAttachment:w,onSendLocation:x,getSocket:k,avatar3dUrl:_,voiceConfig:S,theme:C,suggestedQuestions:E,activeQuiz:z,onQuizAnswer:N}){const[A,I]=i(!1),[T,O]=i(!1),[M,P]=i(!1),{t:L}=D(),j=oc(),F=At({cssVariables:C?.cssVariables}),R=function({isOpen:e,height:t,bottom:n}){const r=oc(),[o,l]=i({}),c=s(()=>{if(r){const e=()=>{window.visualViewport?l({height:`${window.visualViewport.height}px`,transform:`translateY(${window.visualViewport.offsetTop}px)`}):l({height:"100dvh",transform:"none"})};return e(),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e),()=>{window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}}{const e=parseFloat(n||ic)||24,r=window.innerHeight-64-e;if(t){const e=parseFloat(t)||700,o=Math.min(e,r);l({height:`${o}px`,maxHeight:`${r}px`,bottom:n||ic})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||ic})}}},[r,t,n]);return a(()=>{if(!e)return;const t=c();return window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c),t&&t()}},[e,c]),o}({isOpen:e,height:C?.cssVariables?.windowHeight,bottom:C?.cssVariables?.windowBottom}),$=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null),i=f(n);i.current=n;const l=s(e=>{const t=r.current;if(t)if("Escape"!==e.key){if("Tab"===e.key){const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}else i.current?.()},[]);return a(()=>{if(!e)return;o.current=document.activeElement;const n=t?.current,i=r.current;if(!i)return;const a=setTimeout(()=>{const e=i.querySelector('textarea, input[type="text"]');if(e)e.focus();else{const e=i.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():i.focus()}},100);return document.addEventListener("keydown",l),()=>{clearTimeout(a),document.removeEventListener("keydown",l);const e=n||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,t,l]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return j&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,j]),!e)return null;const B="bottom-left"===C?.position,U=z?r.filter(e=>e.id!==z.id):r;/* @__PURE__ */
134
+ /* @__PURE__ */b("input",{type:"text",value:O,onChange:e=>M(e.target.value),onKeyDown:e=>"Enter"===e.key&&Oe(),placeholder:"Escribí email, teléfono, etc.",autoFocus:!0,style:{flex:1,padding:"10px 14px",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.12)",background:"rgba(255,255,255,0.06)",color:"white",fontSize:"13px",outline:"none",backdropFilter:"blur(8px)"}}),
135
+ /* @__PURE__ */b("button",{onClick:Oe,disabled:!O.trim(),style:{width:"40px",height:"40px",borderRadius:"50%",border:"none",cursor:O.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:O.trim()?n:"rgba(255,255,255,0.06)",color:O.trim()?"white":"rgba(255,255,255,0.2)",transition:"all 0.2s"},"aria-label":"Enviar texto",children:/* @__PURE__ */b(re,{style:{width:"16px",height:"16px"}})})]}),
136
+ /* @__PURE__ */b("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(0.95); }\n }\n "})]})}function qc({isOpen:e,isConnected:t,isTyping:n,messages:r,botName:o="BotUyo",logoUrl:l,welcomeMessage:c,inputPlaceholder:u,mediaConfig:d,onClose:p,onSendMessage:h,bubbleStyles:m,avatars:g,onSendAttachment:w,onSendLocation:x,getSocket:k,avatar3dUrl:_,voiceConfig:S,theme:C,suggestedQuestions:E,activeQuiz:z,onQuizAnswer:N}){const[A,I]=i(!1),[T,O]=i(!1),[M,P]=i(!1),[L,j]=i(!1),{t:F}=D(),R=oc(),$=At({cssVariables:C?.cssVariables}),B=function({isOpen:e,height:t,bottom:n}){const r=oc(),[o,l]=i({}),c=s(()=>{if(r){const e=()=>{window.visualViewport?l({height:`${window.visualViewport.height}px`,transform:`translateY(${window.visualViewport.offsetTop}px)`}):l({height:"100dvh",transform:"none"})};return e(),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e),()=>{window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}}{const e=parseFloat(n||ic)||24,r=window.innerHeight-64-e;if(t){const e=parseFloat(t)||700,o=Math.min(e,r);l({height:`${o}px`,maxHeight:`${r}px`,bottom:n||ic})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||ic})}}},[r,t,n]);return a(()=>{if(!e)return;const t=c();return window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c),t&&t()}},[e,c]),o}({isOpen:e,height:C?.cssVariables?.windowHeight,bottom:C?.cssVariables?.windowBottom}),U=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null),i=f(n);i.current=n;const l=s(e=>{const t=r.current;if(t)if("Escape"!==e.key){if("Tab"===e.key){const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}else i.current?.()},[]);return a(()=>{if(!e)return;o.current=document.activeElement;const n=t?.current,i=r.current;if(!i)return;const a=setTimeout(()=>{const e=i.querySelector('textarea, input[type="text"]');if(e)e.focus();else{const e=i.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():i.focus()}},100);return document.addEventListener("keydown",l),()=>{clearTimeout(a),document.removeEventListener("keydown",l);const e=n||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,t,l]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return R&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,R]),a(()=>{const e=()=>j(!0);return window.addEventListener("botuyo-chat:start-call",e),()=>window.removeEventListener("botuyo-chat:start-call",e)},[]),a(()=>{L&&t&&d?.enableVoice&&!T&&(j(!1),O(!0))},[L,t,d?.enableVoice,T]),!e)return null;const q="bottom-left"===C?.position,V=z?r.filter(e=>e.id!==z.id):r;/* @__PURE__ */
137
137
  return y(v,{children:[
138
- /* @__PURE__ */b("div",{id:"chat-dialog-description",className:"sr-only",children:L("accessibility.dialogDescription",{botName:o??"BotUyo"})}),
139
- /* @__PURE__ */y("div",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:Et("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!j&&["fixed",B?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],j&&["fixed inset-0 w-full"]),style:{...R,...j?{}:{width:"350px",minWidth:"350px",maxWidth:"350px",borderRadius:"32px",boxShadow:"0 25px 65px -5px rgba(0, 0, 0, 0.15), 0 8px 20px -8px rgba(0, 0, 0, 0.1)"},backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:[
138
+ /* @__PURE__ */b("div",{id:"chat-dialog-description",className:"sr-only",children:F("accessibility.dialogDescription",{botName:o??"BotUyo"})}),
139
+ /* @__PURE__ */y("div",{ref:U,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:Et("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!R&&["fixed",q?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],R&&["fixed inset-0 w-full"]),style:{...B,...R?{}:{width:"350px",minWidth:"350px",maxWidth:"350px",borderRadius:"32px",boxShadow:"0 25px 65px -5px rgba(0, 0, 0, 0.15), 0 8px 20px -8px rgba(0, 0, 0, 0.1)"},backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:[
140
140
  /* @__PURE__ */b("header",{className:"relative shrink-0 border-b z-20",style:{padding:"var(--spacing-5)",backgroundColor:"hsl(var(--background) / 0.9)",borderColor:"hsl(var(--border))",backdropFilter:"blur(24px)"},children:/* @__PURE__ */y("div",{className:"flex items-center justify-between",children:[
141
141
  /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[
142
142
  /* @__PURE__ */y("div",{className:"relative",children:[
@@ -148,52 +148,52 @@ return y(v,{children:[
148
148
  /* @__PURE__ */b(oe,{className:"h-3 w-3 text-primary fill-primary/10"})]}),
149
149
  /* @__PURE__ */y("div",{id:"chat-window-description",className:"flex items-center gap-1.5 mt-0.5",children:[
150
150
  /* @__PURE__ */b("span",{className:"flex h-1 w-1 rounded-full bg-emerald-500"}),
151
- /* @__PURE__ */b("span",{className:"text-[9px] font-black text-muted-foreground uppercase tracking-[0.1em]",children:L(t?"online":"offline")})]})]})]}),
151
+ /* @__PURE__ */b("span",{className:"text-[9px] font-black text-muted-foreground uppercase tracking-[0.1em]",children:F(t?"online":"offline")})]})]})]}),
152
152
  /* @__PURE__ */y("div",{className:"flex items-center gap-2",children:[d?.enableVoice&&/* @__PURE__ */y("div",{className:"relative",children:[
153
153
  /* @__PURE__ */b("button",{onClick:()=>P(!M),"aria-label":"Iniciar llamada de voz",title:"Llamar",className:"h-8 w-8 flex items-center justify-center rounded-full bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 transition-all active:scale-90 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2",children:/* @__PURE__ */b(te,{className:"h-4 w-4","aria-hidden":"true"})}),M&&/* @__PURE__ */y("div",{className:"absolute top-full right-0 mt-2 rounded-2xl border shadow-soft-2xl animate-in fade-in zoom-in-95 duration-200 z-50",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))",padding:"var(--spacing-4)",minWidth:"180px"},children:[
154
- /* @__PURE__ */b("p",{className:"text-xs font-bold text-center",style:{color:"hsl(var(--foreground))",marginBottom:"var(--spacing-3)"},children:L("call_confirm")||"¿Iniciar llamada de voz?"}),
154
+ /* @__PURE__ */b("p",{className:"text-xs font-bold text-center",style:{color:"hsl(var(--foreground))",marginBottom:"var(--spacing-3)"},children:F("call_confirm")||"¿Iniciar llamada de voz?"}),
155
155
  /* @__PURE__ */y("div",{className:"flex items-center justify-center",style:{gap:"var(--spacing-2)"},children:[
156
- /* @__PURE__ */b("button",{onClick:()=>P(!1),className:"h-8 rounded-xl text-[10px] font-black uppercase tracking-wider transition-all active:scale-95",style:{padding:"0 var(--spacing-4)",backgroundColor:"hsl(var(--muted))",color:"hsl(var(--muted-foreground))"},children:L("cancel")||"Cancelar"}),
157
- /* @__PURE__ */b("button",{onClick:()=>{P(!1),O(!0)},className:"h-8 rounded-xl text-[10px] font-black uppercase tracking-wider text-white transition-all active:scale-95 shadow-md",style:{padding:"0 var(--spacing-4)",backgroundColor:"#10b981"},children:L("call")||"Llamar"})]})]})]}),
158
- /* @__PURE__ */b("button",{onClick:p,"aria-label":L("accessibility.closeChat"),title:"Esc",className:"h-8 w-8 flex items-center justify-center rounded-full bg-muted/60 hover:bg-muted text-foreground transition-all active:scale-90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2",children:/* @__PURE__ */b(se,{className:"h-4 w-4","aria-hidden":"true"})})]})]})}),
159
- /* @__PURE__ */y("main",{role:"region","aria-label":L("accessibility.chatMessages"),className:"flex-1 min-h-0 relative flex flex-col",style:{padding:"var(--spacing-5)",backgroundColor:"hsl(var(--muted))"},children:[
160
- /* @__PURE__ */b(Kl,{messages:U,isTyping:n,welcomeMessage:c,primaryColor:F,logoUrl:l,botName:o,bubbleStyles:m,avatars:g,onButtonClick:e=>h(`Answer: ${e}`)}),
161
- /* @__PURE__ */b("div",{className:"absolute top-0 left-0 right-0 h-6 bg-gradient-to-b from-background/10 to-transparent pointer-events-none"})]}),z&&/* @__PURE__ */b(nc,{quiz:z,primaryColor:F,onAnswer:(e,t)=>N?.(z,e,t)}),E&&E.length>0&&!r.some(e=>"user"===e.sender)&&/* @__PURE__ */b(tc,{questions:E,onSelect:h}),
162
- /* @__PURE__ */y("footer",{className:"border-t",style:{paddingTop:"var(--spacing-5)",paddingLeft:"var(--spacing-5)",paddingRight:"var(--spacing-5)",paddingBottom:j?"max(var(--spacing-3), env(safe-area-inset-bottom))":"var(--spacing-3)",backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))"},children:[
163
- /* @__PURE__ */b(ec,{isConnected:t,placeholder:u,primaryColor:F,mediaConfig:d,onSendMessage:h,onSendAttachment:w,onSendLocation:x,onVoiceCall:d?.enableVoice?()=>O(!0):void 0}),
156
+ /* @__PURE__ */b("button",{onClick:()=>P(!1),className:"h-8 rounded-xl text-[10px] font-black uppercase tracking-wider transition-all active:scale-95",style:{padding:"0 var(--spacing-4)",backgroundColor:"hsl(var(--muted))",color:"hsl(var(--muted-foreground))"},children:F("cancel")||"Cancelar"}),
157
+ /* @__PURE__ */b("button",{onClick:()=>{P(!1),O(!0)},className:"h-8 rounded-xl text-[10px] font-black uppercase tracking-wider text-white transition-all active:scale-95 shadow-md",style:{padding:"0 var(--spacing-4)",backgroundColor:"#10b981"},children:F("call")||"Llamar"})]})]})]}),
158
+ /* @__PURE__ */b("button",{onClick:p,"aria-label":F("accessibility.closeChat"),title:"Esc",className:"h-8 w-8 flex items-center justify-center rounded-full bg-muted/60 hover:bg-muted text-foreground transition-all active:scale-90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2",children:/* @__PURE__ */b(se,{className:"h-4 w-4","aria-hidden":"true"})})]})]})}),
159
+ /* @__PURE__ */y("main",{role:"region","aria-label":F("accessibility.chatMessages"),className:"flex-1 min-h-0 relative flex flex-col",style:{padding:"var(--spacing-5)",backgroundColor:"hsl(var(--muted))"},children:[
160
+ /* @__PURE__ */b(Kl,{messages:V,isTyping:n,welcomeMessage:c,primaryColor:$,logoUrl:l,botName:o,bubbleStyles:m,avatars:g,onButtonClick:e=>h(`Answer: ${e}`)}),
161
+ /* @__PURE__ */b("div",{className:"absolute top-0 left-0 right-0 h-6 bg-gradient-to-b from-background/10 to-transparent pointer-events-none"})]}),z&&/* @__PURE__ */b(nc,{quiz:z,primaryColor:$,onAnswer:(e,t)=>N?.(z,e,t)}),E&&E.length>0&&!r.some(e=>"user"===e.sender)&&/* @__PURE__ */b(tc,{questions:E,onSelect:h}),
162
+ /* @__PURE__ */y("footer",{className:"border-t",style:{paddingTop:"var(--spacing-5)",paddingLeft:"var(--spacing-5)",paddingRight:"var(--spacing-5)",paddingBottom:R?"max(var(--spacing-3), env(safe-area-inset-bottom))":"var(--spacing-3)",backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))"},children:[
163
+ /* @__PURE__ */b(ec,{isConnected:t,placeholder:u,primaryColor:$,mediaConfig:d,onSendMessage:h,onSendAttachment:w,onSendLocation:x,onVoiceCall:d?.enableVoice?()=>O(!0):void 0}),
164
164
  /* @__PURE__ */y("div",{className:"flex items-center justify-center gap-1 opacity-25 select-none",style:{marginTop:"var(--spacing-2)",paddingBottom:"var(--spacing-1)"},children:[
165
165
  /* @__PURE__ */b(H,{className:"h-2 w-2 text-primary fill-primary"}),
166
- /* @__PURE__ */b("span",{className:"text-[7px] font-bold uppercase tracking-[0.2em]",children:L("con_amor_paseo_libre")})]})]}),
167
- /* @__PURE__ */b(Oc,{isOpen:T,onClose:()=>O(!1),primaryColor:F,avatars:g,logoUrl:l,avatar3dUrl:_,voiceConfig:S,getSocket:k})]})]})}class Pc extends m{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){jt("ErrorBoundary caught error:",e,t),this.props.onError?.(e,t)}handleReset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:/* @__PURE__ */y("div",{className:"flex flex-col items-center justify-center p-8 bg-background text-center",children:[
166
+ /* @__PURE__ */b("span",{className:"text-[7px] font-bold uppercase tracking-[0.2em]",children:F("con_amor_paseo_libre")})]})]}),
167
+ /* @__PURE__ */b(Uc,{isOpen:T,onClose:()=>O(!1),primaryColor:$,avatars:g,logoUrl:l,avatar3dUrl:_,voiceConfig:S,getSocket:k})]})]})}class Vc extends m{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){jt("ErrorBoundary caught error:",e,t),this.props.onError?.(e,t)}handleReset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:/* @__PURE__ */y("div",{className:"flex flex-col items-center justify-center p-8 bg-background text-center",children:[
168
168
  /* @__PURE__ */b("div",{className:"text-6xl mb-4",children:"⚠️"}),
169
169
  /* @__PURE__ */b("h2",{className:"text-xl font-bold text-foreground mb-2",children:"Algo salió mal"}),
170
170
  /* @__PURE__ */b("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:this.state.error?.message||"Ocurrió un error inesperado"}),
171
- /* @__PURE__ */b("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const Lc={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Dc={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},jc={text:"text-primary-foreground"};const Fc=(e,t)=>t.some(t=>e instanceof t);let Rc,$c;const Bc=/* @__PURE__ */new WeakMap,Uc=/* @__PURE__ */new WeakMap,qc=/* @__PURE__ */new WeakMap;let Vc={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Bc.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Zc(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Wc(e){Vc=e(Vc)}function Hc(e){return"function"==typeof e?(t=e,($c||($c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(Jc(this),e),Zc(this.request)}:function(...e){return Zc(t.apply(Jc(this),e))}):(e instanceof IDBTransaction&&function(e){if(Bc.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});Bc.set(e,t)}(e),Fc(e,Rc||(Rc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Vc):e);var t}function Zc(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(Zc(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return qc.set(t,e),t}(e);if(Uc.has(e))return Uc.get(e);const t=Hc(e);return t!==e&&(Uc.set(e,t),qc.set(t,e)),t}const Jc=e=>qc.get(e),Kc=["get","getKey","getAll","getAllKeys","count"],Gc=["put","add","delete","clear"],Yc=/* @__PURE__ */new Map;function Qc(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Yc.get(t))return Yc.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=Gc.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!Kc.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return Yc.set(t,i),i}Wc(e=>({...e,get:(t,n,r)=>Qc(t,n)||e.get(t,n,r),has:(t,n)=>!!Qc(t,n)||e.has(t,n)}));const Xc=["continue","continuePrimaryKey","advance"],eu={},tu=/* @__PURE__ */new WeakMap,nu=/* @__PURE__ */new WeakMap,ru={get(e,t){if(!Xc.includes(t))return e[t];let n=eu[t];return n||(n=eu[t]=function(...e){tu.set(this,nu.get(this)[t](...e))}),n}};async function*ou(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,ru);for(nu.set(n,t),qc.set(n,Jc(t));t;)yield n,t=await(tu.get(n)||t.continue()),tu.delete(n)}function iu(e,t){return t===Symbol.asyncIterator&&Fc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Fc(e,[IDBIndex,IDBObjectStore])}Wc(e=>({...e,get:(t,n,r)=>iu(t,n)?ou:e.get(t,n,r),has:(t,n)=>iu(t,n)||e.has(t,n)}));class au{db=null;DB_NAME;DB_VERSION=1;constructor(e,t="default"){this.DB_NAME=`botuyo-chat-${e}-${t}`}async init(){try{this.db=await function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=Zc(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Zc(a.result),e.oldVersion,e.newVersion,Zc(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(e){e.objectStoreNames.contains("messages")||e.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata")}}),Rt("IndexedDB initialized")}catch(e){throw jt("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){jt("Failed to save message:",t)}}async saveMessages(e){this.db||await this.init();try{const t=this.db.transaction("messages","readwrite");await Promise.all([...e.map(e=>t.store.put(e)),t.done])}catch(t){jt("Failed to save messages:",t)}}async getMessages(e=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-e)}catch(t){return jt("Failed to get messages:",t),[]}}async getMessage(e){this.db||await this.init();try{return await this.db.get("messages",e)}catch(t){return void jt("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){jt("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Rt("Messages cleared from IndexedDB")}catch(e){jt("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){jt("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return jt("Failed to get metadata:",e),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),Rt("All data cleared from IndexedDB")}catch(e){jt("Failed to clear all data:",e)}}async migrateFromLocalStorage(e,t="default"){try{const n=`botuyo_chat_v1_${e}_${t}`,r=localStorage.getItem(n);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const e=o.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}));await this.saveMessages(e),Rt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Rt("Migration from localStorage completed")}catch(n){jt("Failed to migrate from localStorage:",n)}}}const su=/* @__PURE__ */new Map,lu={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function cu(e,t){switch(t.type){case"TOGGLE_WINDOW":return{...e,isOpen:!e.isOpen};case"OPEN_WINDOW":return{...e,isOpen:!0};case"CLOSE_WINDOW":return{...e,isOpen:!1};case"SET_CONNECTED":return{...e,isConnected:t.payload};case"SET_TYPING":return{...e,isTyping:t.payload};case"ADD_MESSAGE":{if(e.messages.some(e=>e.id===t.payload.id))return e;if(t.payload.id.startsWith("msg-")&&"text"===t.payload.type){const n=/* @__PURE__ */(new Date).getTime();if(e.messages.slice(-10).some(e=>"text"===e.type&&e.sender===t.payload.sender&&"content"in e&&"content"in t.payload&&e.content===t.payload.content&&Math.abs(n-new Date(e.timestamp).getTime())<3e4))return e}const n=[...e.messages,t.payload],r="bot"===t.payload.sender;return{...e,messages:n,isTyping:!r&&e.isTyping}}case"SET_MESSAGES":return{...e,messages:[...t.payload]};case"SET_ERROR":return{...e,error:t.payload};case"SET_SESSION_ID":return{...e,sessionId:t.payload};case"ANSWER_QUIZ":{const{messageId:n,buttonId:r}=t.payload;return{...e,messages:e.messages.map(e=>e.id===n&&"buttons"===e.type?{...e,answered:!0,...r?{selectedId:r}:{}}:e)}}case"CLEAR_CHAT":return{...lu,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,isConnected:!1,isTyping:!1,error:null};default:return e}}function uu(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=a.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function a(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class du extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class pu extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const hu={};function fu(e){return hu}function mu(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function gu(e,t){return"bigint"==typeof t?t.toString():t}function bu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function yu(e){return null==e}function vu(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const wu=/* @__PURE__ */Symbol("evaluating");function xu(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==wu)return void 0===r&&(r=wu,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ku(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function _u(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Su(e){return JSON.stringify(e)}const Cu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Eu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const zu=bu(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Nu(e){if(!1===Eu(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Eu(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Au(e){return Nu(e)?{...e}:Array.isArray(e)?[...e]:e}const Iu=/* @__PURE__ */new Set(["string","number","symbol"]);function Tu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ou(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Mu(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Pu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Lu(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Du(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ju(e){return"string"==typeof e?e:e?.message}function Fu(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=ju(e.inst?._zod.def?.error?.(e))??ju(t?.error?.(e))??ju(n.customError?.(e))??ju(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Ru(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function $u(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Bu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,gu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Uu=uu("$ZodError",Bu),qu=uu("$ZodError",Bu,{Parent:Error}),Vu=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new du;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Fu(e,i,fu())));throw Cu(t,o?.callee),t}return a.value},Wu=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Fu(e,i,fu())));throw Cu(t,o?.callee),t}return a.value},Hu=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new du;return i.issues.length?{success:!1,error:new(e??Uu)(i.issues.map(e=>Fu(e,o,fu())))}:{success:!0,data:i.value}},Zu=/* @__PURE__ */Hu(qu),Ju=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>Fu(e,o,fu())))}:{success:!0,data:i.value}},Ku=/* @__PURE__ */Ju(qu),Gu=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Vu(e)(t,n,o)},Yu=e=>(t,n,r)=>Vu(e)(t,n,r),Qu=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Wu(e)(t,n,o)},Xu=e=>async(t,n,r)=>Wu(e)(t,n,r),ed=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Hu(e)(t,n,o)},td=e=>(t,n,r)=>Hu(e)(t,n,r),nd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ju(e)(t,n,o)},rd=e=>async(t,n,r)=>Ju(e)(t,n,r),od=/^[cC][^\s-]{8,}$/,id=/^[0-9a-z]+$/,ad=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,sd=/^[0-9a-vA-V]{20}$/,ld=/^[A-Za-z0-9]{27}$/,cd=/^[a-zA-Z0-9_-]{21}$/,ud=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,pd=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,hd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,fd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,md=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,gd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,yd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,vd=/^[A-Za-z0-9_-]*$/,wd=/^\+[1-9]\d{6,14}$/,xd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",kd=/* @__PURE__ */new RegExp(`^${xd}$`);function _d(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Sd=/^-?\d+$/,Cd=/^-?\d+(?:\.\d+)?$/,Ed=/^[^A-Z]*$/,zd=/^[^a-z]*$/,Nd=/* @__PURE__ */uu("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ad={number:"number",bigint:"bigint",object:"date"},Id=/* @__PURE__ */uu("$ZodCheckLessThan",(e,t)=>{Nd.init(e,t);const n=Ad[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Td=/* @__PURE__ */uu("$ZodCheckGreaterThan",(e,t)=>{Nd.init(e,t);const n=Ad[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Od=/* @__PURE__ */uu("$ZodCheckMultipleOf",(e,t)=>{Nd.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Md=/* @__PURE__ */uu("$ZodCheckNumberFormat",(e,t)=>{Nd.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Pu[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=o,r.maximum=i,n&&(r.pattern=Sd)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Pd=/* @__PURE__ */uu("$ZodCheckMaxLength",(e,t)=>{var n;Nd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!yu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=Ru(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ld=/* @__PURE__ */uu("$ZodCheckMinLength",(e,t)=>{var n;Nd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!yu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=Ru(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dd=/* @__PURE__ */uu("$ZodCheckLengthEquals",(e,t)=>{var n;Nd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!yu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=Ru(r),a=o>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),jd=/* @__PURE__ */uu("$ZodCheckStringFormat",(e,t)=>{var n,r;Nd.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Fd=/* @__PURE__ */uu("$ZodCheckRegex",(e,t)=>{jd.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Rd=/* @__PURE__ */uu("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ed),jd.init(e,t)}),$d=/* @__PURE__ */uu("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zd),jd.init(e,t)}),Bd=/* @__PURE__ */uu("$ZodCheckIncludes",(e,t)=>{Nd.init(e,t);const n=Tu(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ud=/* @__PURE__ */uu("$ZodCheckStartsWith",(e,t)=>{Nd.init(e,t);const n=new RegExp(`^${Tu(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),qd=/* @__PURE__ */uu("$ZodCheckEndsWith",(e,t)=>{Nd.init(e,t);const n=new RegExp(`.*${Tu(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Vd=/* @__PURE__ */uu("$ZodCheckOverwrite",(e,t)=>{Nd.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Wd{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const o of r)this.content.push(o)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Hd={major:4,minor:3,patch:6},Zd=/* @__PURE__ */uu("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Hd;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const t of o._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=Lu(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new du;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Lu(e,t)))});else{if(e.issues.length===t)continue;o||(o=Lu(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Lu(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new du;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new du;return a.then(e=>t(e,r,i))}return t(a,r,i)}}xu(e,"~standard",()=>({validate:t=>{try{const n=Zu(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Ku(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Jd=/* @__PURE__ */uu("$ZodString",(e,t)=>{var n;Zd.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Kd=/* @__PURE__ */uu("$ZodStringFormat",(e,t)=>{jd.init(e,t),Jd.init(e,t)}),Gd=/* @__PURE__ */uu("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=dd),Kd.init(e,t)}),Yd=/* @__PURE__ */uu("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=pd(e))}else t.pattern??(t.pattern=pd());Kd.init(e,t)}),Qd=/* @__PURE__ */uu("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=hd),Kd.init(e,t)}),Xd=/* @__PURE__ */uu("$ZodURL",(e,t)=>{Kd.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ep=/* @__PURE__ */uu("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Kd.init(e,t)}),tp=/* @__PURE__ */uu("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=cd),Kd.init(e,t)}),np=/* @__PURE__ */uu("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=od),Kd.init(e,t)}),rp=/* @__PURE__ */uu("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=id),Kd.init(e,t)}),op=/* @__PURE__ */uu("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ad),Kd.init(e,t)}),ip=/* @__PURE__ */uu("$ZodXID",(e,t)=>{t.pattern??(t.pattern=sd),Kd.init(e,t)}),ap=/* @__PURE__ */uu("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ld),Kd.init(e,t)}),sp=/* @__PURE__ */uu("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=_d({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${xd}T(?:${r})$`)}(t)),Kd.init(e,t)}),lp=/* @__PURE__ */uu("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=kd),Kd.init(e,t)}),cp=/* @__PURE__ */uu("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${_d(t)}$`)),Kd.init(e,t)}),up=/* @__PURE__ */uu("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ud),Kd.init(e,t)}),dp=/* @__PURE__ */uu("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=fd),Kd.init(e,t),e._zod.bag.format="ipv4"}),pp=/* @__PURE__ */uu("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=md),Kd.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),hp=/* @__PURE__ */uu("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=gd),Kd.init(e,t)}),fp=/* @__PURE__ */uu("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bd),Kd.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function mp(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const gp=/* @__PURE__ */uu("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yd),Kd.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{mp(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),bp=/* @__PURE__ */uu("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=vd),Kd.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!vd.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return mp(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),yp=/* @__PURE__ */uu("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wd),Kd.init(e,t)}),vp=/* @__PURE__ */uu("$ZodJWT",(e,t)=>{Kd.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),wp=/* @__PURE__ */uu("$ZodNumber",(e,t)=>{Zd.init(e,t),e._zod.pattern=e._zod.bag.pattern??Cd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),xp=/* @__PURE__ */uu("$ZodNumberFormat",(e,t)=>{Md.init(e,t),wp.init(e,t)}),kp=/* @__PURE__ */uu("$ZodAny",(e,t)=>{Zd.init(e,t),e._zod.parse=e=>e}),_p=/* @__PURE__ */uu("$ZodUnknown",(e,t)=>{Zd.init(e,t),e._zod.parse=e=>e}),Sp=/* @__PURE__ */uu("$ZodNever",(e,t)=>{Zd.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Cp(e,t,n){e.issues.length&&t.issues.push(...Du(n,e.issues)),t.value[n]=e.value}const Ep=/* @__PURE__ */uu("$ZodArray",(e,t)=>{Zd.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const a=o[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?i.push(s.then(t=>Cp(t,n,e))):Cp(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function zp(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Du(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Np(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ap(e,t,n,r,o,i){const a=[],s=o.keySet,l=o.catchall._zod,c=l.def.type,u="optional"===l.optout;for(const d in t){if(s.has(d))continue;if("never"===c){a.push(d);continue}const o=l.run({value:t[d],issues:[]},r);o instanceof Promise?e.push(o.then(e=>zp(e,n,d,t,u))):zp(o,n,d,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Ip=/* @__PURE__ */uu("$ZodObject",(e,t)=>{Zd.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=bu(()=>Np(t));xu(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const o=Eu,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const s=t.value;if(!o(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=a.shape;for(const e of a.keys){const r=c[e],o="optional"===r._zod.optout,i=r._zod.run({value:s[e],issues:[]},n);i instanceof Promise?l.push(i.then(n=>zp(n,t,e,s,o))):zp(i,t,e,s,o)}return i?Ap(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),Tp=/* @__PURE__ */uu("$ZodObjectJIT",(e,t)=>{Ip.init(e,t);const n=e._zod.parse,r=bu(()=>Np(t));let o;const i=Eu,a=!hu.jitless,s=a&&zu.value,l=t.catchall;let c;e._zod.parse=(u,d)=>{c??(c=r.value);const p=u.value;return i(p)?a&&s&&!1===d?.async&&!0!==d.jitless?(o||(o=(e=>{const t=new Wd(["shape","payload","ctx"]),n=r.value,o=e=>{const t=Su(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=/* @__PURE__ */Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=Su(r),s=e[r],l="optional"===s?._zod?.optout;t.write(`const ${n} = ${o(r)};`),l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),u=o(u,d),l?Ap([],p,u,d,c,e):u):n(u,d):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Op(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter(e=>!Lu(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fu(e,r,fu())))}),t)}const Mp=/* @__PURE__ */uu("$ZodUnion",(e,t)=>{Zd.init(e,t),xu(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),xu(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),xu(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),xu(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>vu(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Op(t,o,e,i)):Op(s,o,e,i)}}),Pp=/* @__PURE__ */uu("$ZodIntersection",(e,t)=>{Zd.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>Dp(e,t,n)):Dp(e,o,i)}});function Lp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Nu(e)&&Nu(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const i of r){const n=Lp(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=Lp(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Dp(e,t,n){const r=/* @__PURE__ */new Map;let o;for(const s of t.issues)if("unrecognized_keys"===s.code){o??(o=s);for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(s);for(const s of n.issues)if("unrecognized_keys"===s.code)for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(s);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),Lu(e))return e;const a=Lp(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const jp=/* @__PURE__ */uu("$ZodEnum",(e,t)=>{Zd.init(e,t);const n=mu(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Iu.has(typeof e)).map(e=>"string"==typeof e?Tu(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Fp=/* @__PURE__ */uu("$ZodTransform",(e,t)=>{Zd.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new pu(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n));if(o instanceof Promise)throw new du;return n.value=o,n}});function Rp(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $p=/* @__PURE__ */uu("$ZodOptional",(e,t)=>{Zd.init(e,t),e._zod.optin="optional",e._zod.optout="optional",xu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),xu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${vu(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Rp(t,e.value)):Rp(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Bp=/* @__PURE__ */uu("$ZodExactOptional",(e,t)=>{$p.init(e,t),xu(e._zod,"values",()=>t.innerType._zod.values),xu(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Up=/* @__PURE__ */uu("$ZodNullable",(e,t)=>{Zd.init(e,t),xu(e._zod,"optin",()=>t.innerType._zod.optin),xu(e._zod,"optout",()=>t.innerType._zod.optout),xu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${vu(e.source)}|null)$`):void 0}),xu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),qp=/* @__PURE__ */uu("$ZodDefault",(e,t)=>{Zd.init(e,t),e._zod.optin="optional",xu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Vp(e,t)):Vp(r,t)}});function Vp(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Wp=/* @__PURE__ */uu("$ZodPrefault",(e,t)=>{Zd.init(e,t),e._zod.optin="optional",xu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Hp=/* @__PURE__ */uu("$ZodNonOptional",(e,t)=>{Zd.init(e,t),xu(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>Zp(t,e)):Zp(o,e)}});function Zp(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Jp=/* @__PURE__ */uu("$ZodCatch",(e,t)=>{Zd.init(e,t),xu(e._zod,"optin",()=>t.innerType._zod.optin),xu(e._zod,"optout",()=>t.innerType._zod.optout),xu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fu(e,n,fu()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Fu(e,n,fu()))},input:e.value}),e.issues=[]),e)}}),Kp=/* @__PURE__ */uu("$ZodPipe",(e,t)=>{Zd.init(e,t),xu(e._zod,"values",()=>t.in._zod.values),xu(e._zod,"optin",()=>t.in._zod.optin),xu(e._zod,"optout",()=>t.out._zod.optout),xu(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Gp(e,t.in,n)):Gp(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Gp(e,t.out,n)):Gp(r,t.out,n)}});function Gp(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Yp=/* @__PURE__ */uu("$ZodReadonly",(e,t)=>{Zd.init(e,t),xu(e._zod,"propValues",()=>t.innerType._zod.propValues),xu(e._zod,"values",()=>t.innerType._zod.values),xu(e._zod,"optin",()=>t.innerType?._zod?.optin),xu(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Qp):Qp(r)}});function Qp(e){return e.value=Object.freeze(e.value),e}const Xp=/* @__PURE__ */uu("$ZodCustom",(e,t)=>{Nd.init(e,t),Zd.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>eh(t,n,r,e));eh(o,n,r,e)}});function eh(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push($u(e))}}var th;(th=globalThis).__zod_globalRegistry??(th.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const nh=globalThis.__zod_globalRegistry;function rh(e,t){return new e({type:"string",...Mu(t)})}function oh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Mu(t)})}function ih(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Mu(t)})}function ah(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Mu(t)})}function sh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Mu(t)})}function lh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Mu(t)})}function ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Mu(t)})}function uh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Mu(t)})}function dh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Mu(t)})}function ph(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Mu(t)})}function hh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Mu(t)})}function fh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Mu(t)})}function mh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Mu(t)})}function gh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Mu(t)})}function bh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Mu(t)})}function yh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Mu(t)})}function vh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Mu(t)})}function wh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Mu(t)})}function xh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Mu(t)})}function kh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Mu(t)})}function _h(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Mu(t)})}function Sh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Mu(t)})}function Ch(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Mu(t)})}function Eh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Mu(t)})}function zh(e,t){return new e({type:"string",format:"date",check:"string_format",...Mu(t)})}function Nh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Mu(t)})}function Ah(e,t){return new e({type:"string",format:"duration",check:"string_format",...Mu(t)})}function Ih(e,t){return new e({type:"number",checks:[],...Mu(t)})}function Th(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Mu(t)})}function Oh(e){return new e({type:"any"})}function Mh(e){return new e({type:"unknown"})}function Ph(e,t){return new e({type:"never",...Mu(t)})}function Lh(e,t){return new Id({check:"less_than",...Mu(t),value:e,inclusive:!1})}function Dh(e,t){return new Id({check:"less_than",...Mu(t),value:e,inclusive:!0})}function jh(e,t){return new Td({check:"greater_than",...Mu(t),value:e,inclusive:!1})}function Fh(e,t){return new Td({check:"greater_than",...Mu(t),value:e,inclusive:!0})}function Rh(e,t){return new Od({check:"multiple_of",...Mu(t),value:e})}function $h(e,t){return new Pd({check:"max_length",...Mu(t),maximum:e})}function Bh(e,t){return new Ld({check:"min_length",...Mu(t),minimum:e})}function Uh(e,t){return new Dd({check:"length_equals",...Mu(t),length:e})}function qh(e,t){return new Fd({check:"string_format",format:"regex",...Mu(t),pattern:e})}function Vh(e){return new Rd({check:"string_format",format:"lowercase",...Mu(e)})}function Wh(e){return new $d({check:"string_format",format:"uppercase",...Mu(e)})}function Hh(e,t){return new Bd({check:"string_format",format:"includes",...Mu(t),includes:e})}function Zh(e,t){return new Ud({check:"string_format",format:"starts_with",...Mu(t),prefix:e})}function Jh(e,t){return new qd({check:"string_format",format:"ends_with",...Mu(t),suffix:e})}function Kh(e){return new Vd({check:"overwrite",tx:e})}function Gh(e){/* @__PURE__ */
172
- return Kh(t=>t.normalize(e))}function Yh(){/* @__PURE__ */
173
- return Kh(e=>e.trim())}function Qh(){/* @__PURE__ */
174
- return Kh(e=>e.toLowerCase())}function Xh(){/* @__PURE__ */
175
- return Kh(e=>e.toUpperCase())}function ef(){/* @__PURE__ */
176
- return Kh(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function tf(e,t,n){return new e({type:"array",element:t,...Mu(n)})}function nf(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Mu(n)})}function rf(e){const t=/* @__PURE__ */of(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push($u(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push($u(r))}},e(n.value,n)));return t}function of(e,t){const n=new Nd({check:"custom",...Mu(t)});return n._zod.check=e,n}function af(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??nh,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function sf(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(a.ref||(a.ref=i),sf(i,t,r),t.seen.get(i).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),"input"===t.io&&uf(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function lf(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=/* @__PURE__ */new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,i[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const o=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+i}})(t);r.def={...r.schema},i&&(r.defId=i);const a=r.schema;for(const e in a)delete a[e];a.$ref=o};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t===i[0]){o(i);continue}if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){o(i);continue}}const r=e.metadataRegistry.get(i[0])?.id;(r||n.cycle||n.count>1&&"ref"===e.reused)&&o(i)}}function cf(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const o=n.def??n.schema,i={...o},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),s=n.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(o,s):(o.allOf=o.allOf??[],o.allOf.push(s)),Object.assign(o,i),t._zod.parent===a)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(s.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const s=t._zod.parent;if(s&&s!==a){r(s);const t=e.seen.get(s);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const s of[...e.seen.entries()].reverse())r(s[0]);const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const e=s[1];e.def&&e.defId&&(i[e.defId]=e.def)}e.external||Object.keys(i).length>0&&("draft-2020-12"===e.target?o.$defs=i:o.definitions=i);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:df(t,"input",e.processors),output:df(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function uf(e,t){const n=t??{seen:/* @__PURE__ */new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return uf(r.element,n);if("set"===r.type)return uf(r.valueType,n);if("lazy"===r.type)return uf(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return uf(r.innerType,n);if("intersection"===r.type)return uf(r.left,n)||uf(r.right,n);if("record"===r.type||"map"===r.type)return uf(r.keyType,n)||uf(r.valueType,n);if("pipe"===r.type)return uf(r.in,n)||uf(r.out,n);if("object"===r.type){for(const e in r.shape)if(uf(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(uf(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(uf(e,n))return!0;return!(!r.rest||!uf(r.rest,n))}return!1}const df=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},a=af({...o??{},target:i,io:t,processors:n});return sf(e,a),lf(a,e),cf(a,e)},pf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hf=(e,t,n,r)=>{const o=e._zod.def;sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType},ff=/* @__PURE__ */uu("ZodISODateTime",(e,t)=>{sp.init(e,t),Lf.init(e,t)}),mf=/* @__PURE__ */uu("ZodISODate",(e,t)=>{lp.init(e,t),Lf.init(e,t)}),gf=/* @__PURE__ */uu("ZodISOTime",(e,t)=>{cp.init(e,t),Lf.init(e,t)}),bf=/* @__PURE__ */uu("ZodISODuration",(e,t)=>{up.init(e,t),Lf.init(e,t)}),yf=uu("ZodError",(e,t)=>{Uu.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e}));else if("invalid_key"===o.code)r({issues:o.issues});else if("invalid_element"===o.code)r({issues:o.issues});else if(0===o.path.length)n._errors.push(t(o));else{let e=n,r=0;for(;r<o.path.length;){const n=o.path[r];r===o.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(o))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,gu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,gu,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),vf=/* @__PURE__ */Vu(yf),wf=/* @__PURE__ */Wu(yf),xf=/* @__PURE__ */Hu(yf),kf=/* @__PURE__ */Ju(yf),_f=/* @__PURE__ */Gu(yf),Sf=/* @__PURE__ */Yu(yf),Cf=/* @__PURE__ */Qu(yf),Ef=/* @__PURE__ */Xu(yf),zf=/* @__PURE__ */ed(yf),Nf=/* @__PURE__ */td(yf),Af=/* @__PURE__ */nd(yf),If=/* @__PURE__ */rd(yf),Tf=/* @__PURE__ */uu("ZodType",(e,t)=>(Zd.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:df(e,"input"),output:df(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=af({...n,processors:t});return sf(e,r),lf(r,e),cf(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(_u(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Ou(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>vf(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>xf(e,t,n),e.parseAsync=async(t,n)=>wf(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>kf(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>_f(e,t,n),e.decode=(t,n)=>Sf(e,t,n),e.encodeAsync=async(t,n)=>Cf(e,t,n),e.decodeAsync=async(t,n)=>Ef(e,t,n),e.safeEncode=(t,n)=>zf(e,t,n),e.safeDecode=(t,n)=>Nf(e,t,n),e.safeEncodeAsync=async(t,n)=>Af(e,t,n),e.safeDecodeAsync=async(t,n)=>If(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){/* @__PURE__ */
177
- return nf(Im,e,t)}(t,n)),e.superRefine=t=>e.check(/* @__PURE__ */rf(t)),e.overwrite=t=>e.check(/* @__PURE__ */Kh(t)),e.optional=()=>vm(e),e.exactOptional=()=>new wm({type:"optional",innerType:e}),e.nullable=()=>km(e),e.nullish=()=>vm(km(e)),e.nonoptional=t=>function(e,t){return new Cm({type:"nonoptional",innerType:e,...Mu(t)})}(e,t),e.array=()=>um(e),e.or=t=>new hm({type:"union",options:[e,t],...Mu(void 0)}),e.and=t=>new fm({type:"intersection",left:e,right:t}),e.transform=t=>Nm(e,new bm({type:"transform",transform:t})),e.default=t=>{return n=t,new _m({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Au(n)}});var n},e.prefault=t=>{return n=t,new Sm({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Au(n)}});var n},e.catch=t=>{return new Em({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Nm(e,t),e.readonly=()=>new Am({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return nh.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>nh.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return nh.get(e);const n=e.clone();return nh.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Of=/* @__PURE__ */uu("_ZodString",(e,t)=>{Jd.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:a,patterns:s,contentEncoding:l}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),a&&(r.format=pf[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),l&&(r.contentEncoding=l),s&&s.size>0){const e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(/* @__PURE__ */qh(...t)),e.includes=(...t)=>e.check(/* @__PURE__ */Hh(...t)),e.startsWith=(...t)=>e.check(/* @__PURE__ */Zh(...t)),e.endsWith=(...t)=>e.check(/* @__PURE__ */Jh(...t)),e.min=(...t)=>e.check(/* @__PURE__ */Bh(...t)),e.max=(...t)=>e.check(/* @__PURE__ */$h(...t)),e.length=(...t)=>e.check(/* @__PURE__ */Uh(...t)),e.nonempty=(...t)=>e.check(/* @__PURE__ */Bh(1,...t)),e.lowercase=t=>e.check(/* @__PURE__ */Vh(t)),e.uppercase=t=>e.check(/* @__PURE__ */Wh(t)),e.trim=()=>e.check(/* @__PURE__ */Yh()),e.normalize=(...t)=>e.check(/* @__PURE__ */Gh(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */Qh()),e.toUpperCase=()=>e.check(/* @__PURE__ */Xh()),e.slugify=()=>e.check(/* @__PURE__ */ef())}),Mf=/* @__PURE__ */uu("ZodString",(e,t)=>{Jd.init(e,t),Of.init(e,t),e.email=t=>e.check(/* @__PURE__ */oh(Df,t)),e.url=t=>e.check(/* @__PURE__ */uh(Rf,t)),e.jwt=t=>e.check(/* @__PURE__ */Ch(em,t)),e.emoji=t=>e.check(/* @__PURE__ */dh($f,t)),e.guid=t=>e.check(/* @__PURE__ */ih(jf,t)),e.uuid=t=>e.check(/* @__PURE__ */ah(Ff,t)),e.uuidv4=t=>e.check(/* @__PURE__ */sh(Ff,t)),e.uuidv6=t=>e.check(/* @__PURE__ */lh(Ff,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ch(Ff,t)),e.nanoid=t=>e.check(/* @__PURE__ */ph(Bf,t)),e.guid=t=>e.check(/* @__PURE__ */ih(jf,t)),e.cuid=t=>e.check(/* @__PURE__ */hh(Uf,t)),e.cuid2=t=>e.check(/* @__PURE__ */fh(qf,t)),e.ulid=t=>e.check(/* @__PURE__ */mh(Vf,t)),e.base64=t=>e.check(/* @__PURE__ */kh(Yf,t)),e.base64url=t=>e.check(/* @__PURE__ */_h(Qf,t)),e.xid=t=>e.check(/* @__PURE__ */gh(Wf,t)),e.ksuid=t=>e.check(/* @__PURE__ */bh(Hf,t)),e.ipv4=t=>e.check(/* @__PURE__ */yh(Zf,t)),e.ipv6=t=>e.check(/* @__PURE__ */vh(Jf,t)),e.cidrv4=t=>e.check(/* @__PURE__ */wh(Kf,t)),e.cidrv6=t=>e.check(/* @__PURE__ */xh(Gf,t)),e.e164=t=>e.check(/* @__PURE__ */Sh(Xf,t)),e.datetime=t=>e.check(function(e){/* @__PURE__ */
178
- return Eh(ff,e)}(t)),e.date=t=>e.check(function(e){/* @__PURE__ */
179
- return zh(mf,e)}(t)),e.time=t=>e.check(function(e){/* @__PURE__ */
180
- return Nh(gf,e)}(t)),e.duration=t=>e.check(function(e){/* @__PURE__ */
181
- return Ah(bf,e)}(t))});function Pf(e){/* @__PURE__ */
182
- return rh(Mf,e)}const Lf=/* @__PURE__ */uu("ZodStringFormat",(e,t)=>{Kd.init(e,t),Of.init(e,t)}),Df=/* @__PURE__ */uu("ZodEmail",(e,t)=>{Qd.init(e,t),Lf.init(e,t)}),jf=/* @__PURE__ */uu("ZodGUID",(e,t)=>{Gd.init(e,t),Lf.init(e,t)}),Ff=/* @__PURE__ */uu("ZodUUID",(e,t)=>{Yd.init(e,t),Lf.init(e,t)}),Rf=/* @__PURE__ */uu("ZodURL",(e,t)=>{Xd.init(e,t),Lf.init(e,t)}),$f=/* @__PURE__ */uu("ZodEmoji",(e,t)=>{ep.init(e,t),Lf.init(e,t)}),Bf=/* @__PURE__ */uu("ZodNanoID",(e,t)=>{tp.init(e,t),Lf.init(e,t)}),Uf=/* @__PURE__ */uu("ZodCUID",(e,t)=>{np.init(e,t),Lf.init(e,t)}),qf=/* @__PURE__ */uu("ZodCUID2",(e,t)=>{rp.init(e,t),Lf.init(e,t)}),Vf=/* @__PURE__ */uu("ZodULID",(e,t)=>{op.init(e,t),Lf.init(e,t)}),Wf=/* @__PURE__ */uu("ZodXID",(e,t)=>{ip.init(e,t),Lf.init(e,t)}),Hf=/* @__PURE__ */uu("ZodKSUID",(e,t)=>{ap.init(e,t),Lf.init(e,t)}),Zf=/* @__PURE__ */uu("ZodIPv4",(e,t)=>{dp.init(e,t),Lf.init(e,t)}),Jf=/* @__PURE__ */uu("ZodIPv6",(e,t)=>{pp.init(e,t),Lf.init(e,t)}),Kf=/* @__PURE__ */uu("ZodCIDRv4",(e,t)=>{hp.init(e,t),Lf.init(e,t)}),Gf=/* @__PURE__ */uu("ZodCIDRv6",(e,t)=>{fp.init(e,t),Lf.init(e,t)}),Yf=/* @__PURE__ */uu("ZodBase64",(e,t)=>{gp.init(e,t),Lf.init(e,t)}),Qf=/* @__PURE__ */uu("ZodBase64URL",(e,t)=>{bp.init(e,t),Lf.init(e,t)}),Xf=/* @__PURE__ */uu("ZodE164",(e,t)=>{yp.init(e,t),Lf.init(e,t)}),em=/* @__PURE__ */uu("ZodJWT",(e,t)=>{vp.init(e,t),Lf.init(e,t)}),tm=/* @__PURE__ */uu("ZodNumber",(e,t)=>{wp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:o,maximum:i,format:a,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof o&&(r.minimum=o,"number"==typeof c&&"draft-04"!==t.target&&(c>=o?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof l&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),"number"==typeof i&&(r.maximum=i,"number"==typeof l&&"draft-04"!==t.target&&(l<=i?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s)})(e,t,n),e.gt=(t,n)=>e.check(/* @__PURE__ */jh(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */Fh(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */Fh(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */Lh(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */Dh(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */Dh(t,n)),e.int=t=>e.check(om(t)),e.safe=t=>e.check(om(t)),e.positive=t=>e.check(/* @__PURE__ */jh(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */Fh(0,t)),e.negative=t=>e.check(/* @__PURE__ */Lh(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */Dh(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */Rh(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */Rh(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function nm(e){/* @__PURE__ */
183
- return Ih(tm,e)}const rm=/* @__PURE__ */uu("ZodNumberFormat",(e,t)=>{xp.init(e,t),tm.init(e,t)});function om(e){/* @__PURE__ */
184
- return Th(rm,e)}const im=/* @__PURE__ */uu("ZodAny",(e,t)=>{kp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),am=/* @__PURE__ */uu("ZodUnknown",(e,t)=>{_p.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function sm(){/* @__PURE__ */
185
- return Mh(am)}const lm=/* @__PURE__ */uu("ZodNever",(e,t)=>{Sp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),cm=/* @__PURE__ */uu("ZodArray",(e,t)=>{Ep.init(e,t),Tf.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=sf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Bh(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Bh(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */$h(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Uh(t,n)),e.unwrap=()=>e.element});function um(e,t){/* @__PURE__ */
186
- return tf(cm,e,t)}const dm=/* @__PURE__ */uu("ZodObject",(e,t)=>{Tp.init(e,t),Tf.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]=sf(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=sf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),xu(e,"shape",()=>t.shape),e.keyof=()=>gm(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:sm()}),e.loose=()=>e.clone({...e._zod.def,catchall:sm()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Ph(lm,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Nu(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=_u(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ku(this,"shape",n),n}});return Ou(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Nu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=_u(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ku(this,"shape",n),n}});return Ou(e,n)}(e,t),e.merge=t=>function(e,t){const n=_u(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ku(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ou(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 Ou(e,_u(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 ku(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=_u(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 ku(this,"shape",r),r},checks:[]});return Ou(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=_u(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 ku(this,"shape",o),o},checks:[]});return Ou(t,o)}(ym,e,t[0]),e.required=(...t)=>function(e,t,n){const r=_u(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 ku(this,"shape",o),o}});return Ou(t,r)}(Cm,e,t[0])});function pm(e,t){const n={type:"object",shape:e??{},...Mu(t)};return new dm(n)}const hm=/* @__PURE__ */uu("ZodUnion",(e,t)=>{Mp.init(e,t),Tf.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)=>sf(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}),fm=/* @__PURE__ */uu("ZodIntersection",(e,t)=>{Pp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=sf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=sf(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)}),mm=/* @__PURE__ */uu("ZodEnum",(e,t)=>{jp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=mu(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 mm({...t,checks:[],...Mu(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 mm({...t,checks:[],...Mu(r),entries:o})}});function gm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new mm({type:"enum",entries:n,...Mu(t)})}const bm=/* @__PURE__ */uu("ZodTransform",(e,t)=>{Fp.init(e,t),Tf.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 pu(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push($u(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($u(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),ym=/* @__PURE__ */uu("ZodOptional",(e,t)=>{$p.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function vm(e){return new ym({type:"optional",innerType:e})}const wm=/* @__PURE__ */uu("ZodExactOptional",(e,t)=>{Bp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),xm=/* @__PURE__ */uu("ZodNullable",(e,t)=>{Up.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=sf(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 km(e){return new xm({type:"nullable",innerType:e})}const _m=/* @__PURE__ */uu("ZodDefault",(e,t)=>{qp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;sf(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}),Sm=/* @__PURE__ */uu("ZodPrefault",(e,t)=>{Wp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;sf(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}),Cm=/* @__PURE__ */uu("ZodNonOptional",(e,t)=>{Hp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Em=/* @__PURE__ */uu("ZodCatch",(e,t)=>{Jp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;sf(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}),zm=/* @__PURE__ */uu("ZodPipe",(e,t)=>{Kp.init(e,t),Tf.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;sf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Nm(e,t){return new zm({type:"pipe",in:e,out:t})}const Am=/* @__PURE__ */uu("ZodReadonly",(e,t)=>{Yp.init(e,t),Tf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Im=/* @__PURE__ */uu("ZodCustom",(e,t)=>{Xp.init(e,t),Tf.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)}),Tm=/* @__PURE__ */Object.create(null);Tm.open="0",Tm.close="1",Tm.ping="2",Tm.pong="3",Tm.message="4",Tm.upgrade="5",Tm.noop="6";const Om=/* @__PURE__ */Object.create(null);Object.keys(Tm).forEach(e=>{Om[Tm[e]]=e});const Mm={type:"error",data:"parser error"},Pm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Lm="function"==typeof ArrayBuffer,Dm=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,jm=({type:e,data:t},n,r)=>Pm&&t instanceof Blob?n?r(t):Fm(t,r):Lm&&(t instanceof ArrayBuffer||Dm(t))?n?r(t):Fm(new Blob([t]),r):r(Tm[e]+(t||"")),Fm=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function Rm(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let $m;const Bm="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Tb=0;Tb<64;Tb++)Bm["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(Tb)]=Tb;const Um="function"==typeof ArrayBuffer,qm=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Wm(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:Vm(e.substring(1),t)}:Om[n]?e.length>1?{type:Om[n],data:e.substring(1)}:{type:Om[n]}:Mm},Vm=(e,t)=>{if(Um){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=Bm[e.charCodeAt(t)],r=Bm[e.charCodeAt(t+1)],o=Bm[e.charCodeAt(t+2)],i=Bm[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 Wm(n,t)}return{base64:!0,data:e}},Wm=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Hm=String.fromCharCode(30);let Zm;function Jm(e){return e.reduce((e,t)=>e+t.length,0)}function Km(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 Gm(e){if(e)return function(e){for(var t in Gm.prototype)e[t]=Gm.prototype[t];return e}(e)}Gm.prototype.on=Gm.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Gm.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},Gm.prototype.off=Gm.prototype.removeListener=Gm.prototype.removeAllListeners=Gm.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},Gm.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},Gm.prototype.emitReserved=Gm.prototype.emit,Gm.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Gm.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Ym="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Qm="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Xm(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const eg=Qm.setTimeout,tg=Qm.clearTimeout;function ng(e,t){t.useNativeTimers?(e.setTimeoutFn=eg.bind(Qm),e.clearTimeoutFn=tg.bind(Qm)):(e.setTimeoutFn=Qm.setTimeout.bind(Qm),e.clearTimeoutFn=Qm.clearTimeout.bind(Qm))}function rg(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 og(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class ig extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class ag extends Gm{constructor(e){super(),this.writable=!1,ng(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 ig(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=qm(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 sg extends ag{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(Hm),r=[];for(let o=0;o<n.length;o++){const e=qm(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)=>{jm(e,!1,e=>{r[i]=e,++o===n&&t(r.join(Hm))})})})(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]=og()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let lg=!1;try{lg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Ib){}const cg=lg;function ug(){}class dg extends sg{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 pg extends Gm{constructor(e,t,n){super(),this.createRequest=e,ng(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=Xm(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=pg.requestsCount++,pg.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=ug,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete pg.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 hg(){for(let e in pg.requests)pg.requests.hasOwnProperty(e)&&pg.requests[e].abort()}pg.requestsCount=0,pg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",hg):"function"==typeof addEventListener&&addEventListener("onpagehide"in Qm?"pagehide":"unload",hg,!1));const fg=function(){const e=mg({xdomain:!1});return e&&null!==e.responseType}();function mg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||cg))return new XMLHttpRequest}catch(n){}if(!t)try{return new(Qm[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const gg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class bg extends ag{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=gg?{}:Xm(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(Ib){return this.emitReserved("error",Ib)}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;jm(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&Ym(()=>{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]=og()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const yg=Qm.WebSocket||Qm.MozWebSocket,vg={websocket:class extends bg{createSocket(e,t,n){return gg?new yg(e,t,n):t?new yg(e,t):new yg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends ag{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Ib){return this.emitReserved("error",Ib)}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){Zm||(Zm=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(Jm(n)<1)break;const e=Km(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(Jm(n)<2)break;const e=Km(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(Jm(n)<8)break;const e=Km(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(Mm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(Jm(n)<o)break;const e=Km(n,o);s.enqueue(qm(i?e:Zm.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(Mm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){Pm&&e.data instanceof Blob?e.data.arrayBuffer().then(Rm).then(t):Lm&&(e.data instanceof ArrayBuffer||Dm(e.data))?t(Rm(e.data)):jm(e,!1,e=>{$m||($m=new TextEncoder),t($m.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&&Ym(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends dg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=fg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new pg(mg,this.uri(),e)}}},wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,xg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function kg(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=wg.exec(e||""),i={},a=14;for(;a--;)i[xg[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 _g="function"==typeof addEventListener&&"function"==typeof removeEventListener,Sg=[];_g&&addEventListener("offline",()=>{Sg.forEach(e=>e())},!1);class Cg extends Gm{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=kg(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=kg(t.host).host);ng(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)),_g&&(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"})},Sg.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&&Cg.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",Cg.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+=rg(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,Ym(()=>{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(Cg.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(),_g&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Sg.indexOf(this._offlineEventListener);-1!==e&&Sg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Cg.protocol=4;class Eg extends Cg{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;Cg.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;Cg.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 zg=class extends Eg{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=>vg[e]).filter(e=>!!e)),super(e,n)}};const Ng="function"==typeof ArrayBuffer,Ag=Object.prototype.toString,Ig="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ag.call(Blob),Tg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ag.call(File);function Og(e){return Ng&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Ig&&e instanceof Blob||Tg&&e instanceof File}function Mg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Mg(e[t]))return!0;return!1}if(Og(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Mg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Mg(e[n]))return!0;return!1}function Pg(e){const t=[],n=e.data,r=e;return r.data=Lg(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Lg(e,t){if(!e)return e;if(Og(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]=Lg(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]=Lg(e[r],t));return n}return e}function Dg(e,t){return e.data=jg(e.data,t),delete e.attachments,e}function jg(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]=jg(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=jg(e[n],t));return e}const Fg=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Rg,$g;($g=Rg||(Rg={}))[$g.CONNECT=0]="CONNECT",$g[$g.DISCONNECT=1]="DISCONNECT",$g[$g.EVENT=2]="EVENT",$g[$g.ACK=3]="ACK",$g[$g.CONNECT_ERROR=4]="CONNECT_ERROR",$g[$g.BINARY_EVENT=5]="BINARY_EVENT",$g[$g.BINARY_ACK=6]="BINARY_ACK";class Bg extends Gm{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===Rg.BINARY_EVENT;n||t.type===Rg.BINARY_ACK?(t.type=n?Rg.EVENT:Rg.ACK,this.reconstructor=new Ug(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Og(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===Rg[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Rg.BINARY_EVENT||n.type===Rg.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(!qg(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(!Bg.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 Rg.CONNECT:return Vg(t);case Rg.DISCONNECT:return void 0===t;case Rg.CONNECT_ERROR:return"string"==typeof t||Vg(t);case Rg.EVENT:case Rg.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Fg.indexOf(t[0]));case Rg.ACK:case Rg.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ug{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=Dg(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const qg=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function Vg(e){return"[object Object]"===Object.prototype.toString.call(e)}const Wg=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:Bg,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Rg.EVENT&&e.type!==Rg.ACK||!Mg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Rg.EVENT?Rg.BINARY_EVENT:Rg.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Rg.BINARY_EVENT&&e.type!==Rg.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=Pg(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return Rg}},Symbol.toStringTag,{value:"Module"}));function Hg(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Zg=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Jg extends Gm{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=[Hg(e,"open",this.onopen.bind(this)),Hg(e,"packet",this.onpacket.bind(this)),Hg(e,"error",this.onerror.bind(this)),Hg(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(Zg.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:Rg.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:Rg.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 Rg.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 Rg.EVENT:case Rg.BINARY_EVENT:this.onevent(e);break;case Rg.ACK:case Rg.BINARY_ACK:this.onack(e);break;case Rg.DISCONNECT:this.ondisconnect();break;case Rg.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:Rg.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:Rg.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 Kg(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}Kg.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)},Kg.prototype.reset=function(){this.attempts=0},Kg.prototype.setMin=function(e){this.ms=e},Kg.prototype.setMax=function(e){this.max=e},Kg.prototype.setJitter=function(e){this.jitter=e};class Gg extends Gm{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,ng(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 Kg({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||Wg;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 zg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Hg(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Hg(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(Hg(e,"ping",this.onping.bind(this)),Hg(e,"data",this.ondata.bind(this)),Hg(e,"error",this.onerror.bind(this)),Hg(e,"close",this.onclose.bind(this)),Hg(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){Ym(()=>{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 Jg(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 Yg={};function Qg(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=kg(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=Yg[o]&&i in Yg[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new Gg(r,t):(Yg[o]||(Yg[o]=new Gg(r,t)),s=Yg[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(Qg,{Manager:Gg,Socket:Jg,io:Qg,connect:Qg});const Xg="chat_device_id";function eb(){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 Dt("[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 tb=pm({id:Pf().optional(),type:gm(["text","image","audio","location","system"]).default("text"),content:Pf().optional(),imageUrl:Pf().url().optional(),audioUrl:Pf().optional(),latitude:nm().optional(),longitude:nm().optional(),timestamp:Pf().optional(),sender:gm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Oh(im).optional(),sources:um(Pf()).optional()}),nb=pm({agentId:Pf().optional(),name:Pf().optional(),label:Pf().optional(),avatarUrl:Pf().optional(),variantKey:Pf().optional()});class rb{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),Dt("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?Ft():(this.isDisabled=!0,this.queue=[],Ft(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ft()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const ob=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},ib=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let ab=null,sb=null;function lb(e){ab=e}function cb(e){sb=e}const ub=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(e=>{ab?(ab(e),Ft(0)):Dt("sendMessage called but no handler registered")},[]),m=s(()=>{sb?(sb(),Ft()):Dt("clearMessages called but no handler registered")},[]),g={isOpen:a,open:d,close:p,toggle:h,sendMessage:f,clearMessages:m,unreadCount:c},v=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
187
- return y(ub.Provider,{value:g,children:[e,
188
- /* @__PURE__ */b(yb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:v})]})}function pb(){const e=o(ub);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const hb=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,onThemeUpdate:v}=e,[w,x]=i(0),k=f(0),{t:_}=D(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new rb(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),C=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||$t,h=l||Bt;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 Dt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Rt("Notification permission:",e),"granted"===e}catch(e){return jt("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){jt("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=>{Ft(0)})}catch(n){jt("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}),E=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:z,actions:N}=function(e,t="default"){const[r,o]=g(cu,lu),[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 su.has(n)||su.set(n,new au(e,t)),su.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){Dt("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){jt("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){jt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){jt("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}}),[]);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}}}(t,o),A=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),I=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(Xg);if(e)return e;const t=eb();return localStorage.setItem(Xg,t),t}catch{return Dt("localStorage not available, using session-only device ID"),eb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=tb.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=Qg(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:l?.token,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),e.on("connect_error",e=>{h(!1),c.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){jt("ChatSocket Error processing bot_message:",t)}}),e.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 Ft(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){Ft()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e));const o=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};e.on("onboarding:command",e=>o(e)),e.on("form:command",e=>o(e)),e.on("request_form_state",()=>{o({type:"botuyo-request-form-state"})}),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),e.on("custom_event",e=>{if(o({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data){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("agent_switched"===e?.eventName&&e?.data){const t=nb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):Ft()}});const i=t=>{const{type:n}=t.data||{};"botuyo-onboarding-state"!==n&&"botuyo-form-state"!==n||e.emit("form_state",t.data)};window.addEventListener("message",i),d.current=e,e.__formCleanup=()=>window.removeEventListener("message",i)},[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}),jt("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]),N=u(()=>rc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>A?{...l||{},seo:{...A||{}}}:l,[l,A]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=k.current>0?t-k.current:void 0;k.current=t,N.addMessage(e),S.trackMessageReceived(e.type,n),z.isOpen||"bot"!==e.sender||(x(e=>e+1),C.notifyWithSound(e))},[N,z.isOpen,S,C]),onConnected:s((e,t)=>{N.setConnected(!0),N.setSessionId(e),S.trackConnectionStatus(!0),t&&v&&v(t),t&&b&&b("backend_config",t)},[N,b,v,S]),onDisconnected:s(()=>{N.setConnected(!1),S.trackConnectionStatus(!1)},[N,S]),onTyping:s(e=>N.setTyping(e),[N]),onError:s(e=>{N.setError(e),S.trackError(e)},[N,S]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:v,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);v&&v(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&N.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:_("agent_switched",{name:t})})},[v,N,_]),onHistoryLoaded:s(e=>{0!==e.length&&N.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,ob(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(ib)),i=e.filter(e=>!r.has(e.id)&&ob(e)>n&&!o.has(ib(e)));return[...t,...i]}(z.messages,e))},[z.messages,N])}),T=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}(z.messages),[z.messages]),O=f(T);a(()=>{O.current=T},[T]);const M=s(()=>{Ft(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),Ft()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),Ft())},[z.isOpen,N,y,S]),P=s(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void N.setError(_("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};N.addMessage(t),S.trackMessageSent("text"),I.sendMessage(e,"text"),O.current&&N.answerQuiz(O.current.id)},[N,I,E,S,_]),L=s((e,t,n)=>{N.answerQuiz(e.id,n),I.sendMessage(`Answer: ${t}`,"text"),S.trackMessageSent("text")},[N,I,S]),j=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}`},N.addMessage(n);const r=await hb(e);I.sendMessage(r,t)},[N,I]),F=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"};N.addMessage(t),I.sendMessage(JSON.stringify(e),"location")},[N,I]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&P(e.detail.message)};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),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:send-message",r)}},[z.isOpen,N,P]),a(()=>(lb(P),()=>lb(null)),[P]);const R=s(()=>{N.clearMessages(),Rt("Chat history cleared")},[N]);a(()=>(cb(R),()=>cb(null)),[R]);const $=u(()=>{if(z.isTyping)return"thinking";const e=[...z.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[z.isTyping,z.messages]);return{state:z,actions:N,unreadCount:w,currentBotEmotion:$,isConnected:I.isConnected,getSocket:I.getSocket,activeQuiz:T,handleToggle:M,handleSendText:P,handleSendAttachment:j,handleSendLocation:F,handleQuizAnswer:L}}function mb({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=L.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),Ft(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function gb(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,initialOpen:w=!1,hideLauncher:x=!1,voiceFirst:k=!1}=e,_=f(null),S=oc(),C=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}(_),[E,z]=i(),{mergedTheme:N,mergedStyles:A,getContainerStyle:I}=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={...zt,...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:{...Lc,...e?.bubbleStyles?.radius},bot:{...Dc,...e?.bubbleStyles?.bot},user:{...jc,...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,E);a(()=>{N.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.')},[N.isHidden]);const{state:T,actions:O,unreadCount:M,currentBotEmotion:P,isConnected:L,handleToggle:D,handleSendText:j,handleSendAttachment:F,handleSendLocation:R,getSocket:$,activeQuiz:B,handleQuizAnswer:U}=fb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:z}),q=f(!1);a(()=>{w&&E&&!q.current&&(q.current=!0,T.isOpen||O.openWindow())},[w,E,T.isOpen,O]);const V=u(()=>{const e={...d||{}},t=E;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,E]),W=s(()=>{O.closeWindow()},[O]),H=s(e=>{e.stopPropagation()},[]),Z=I(T.isOpen,S,c?.position),J=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(!N.cssVariables)return e;let t={...N.cssVariables};if(C){const e=E?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Nt,...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},[N.cssVariables,C,E,c?.darkCssVariables]),K=c?.voiceNoiseGate??E?.voiceNoiseGate,G=u(()=>({noiseGate:K}),[K]),[Y,Q]=i(!1);return a(()=>{k&&L&&Q(!0)},[k,L]),N.isHidden?null:E?k?/* @__PURE__ */b("div",{ref:_,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...J},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Pc,{children:/* @__PURE__ */b(Oc,{isOpen:Y,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:At(N),avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},logoUrl:N.logoUrl,avatar3dUrl:c?.avatar3dUrl||E?.avatar3dUrl,voiceConfig:G,getSocket:$})})}):/* @__PURE__ */y("div",{ref:_,id:"botuyo-chat-widget-root",className:Et("botuyo-chat-widget flex flex-col",!S&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Z,...J,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:[
189
- /* @__PURE__ */b("div",{className:Et("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",S?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",T.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:T.isOpen?"auto":"none"},onMouseDown:H,onTouchStart:H,children:/* @__PURE__ */b(Pc,{children:/* @__PURE__ */b(Mc,{isOpen:T.isOpen,isConnected:L,isTyping:T.isTyping,messages:T.messages,onClose:W,onSendMessage:j,onSendAttachment:F,onSendLocation:R,botName:N.botName,logoUrl:N.logoUrl,welcomeMessage:N.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||E?.inputPlaceholder,position:c?.position,bubbleStyles:A,avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},mediaConfig:V,theme:N,avatar3dUrl:c?.avatar3dUrl||E?.avatar3dUrl,voiceConfig:G,getSocket:$,suggestedQuestions:E?.suggestedQuestions,activeQuiz:B,onQuizAnswer:U})})}),!x&&/* @__PURE__ */b("div",{className:Et(T.isOpen?"hidden":"block",!S&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:H,onTouchStart:H,children:/* @__PURE__ */b(qt,{isOpen:T.isOpen,onClick:D,unreadCount:M,position:c?.position||"bottom-right",primaryColor:At(N),logoUrl:N.logoUrl,starterPrompt:c?.starterPrompt||E?.starterPrompt,avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},emotion:P,styles:A,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??E?.avatarScale,showPromptAvatar:c?.showPromptAvatar??E?.showPromptAvatar})})]}):null}function bb(e){/* @__PURE__ */
190
- return b(Pt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(gb,{...e})})}function yb(e){/* @__PURE__ */
191
- return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(mb,{children:/* @__PURE__ */b(bb,{...e})})})}const vb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:yb,ChatWidgetInner:gb,ChatWidgetWithProviders:bb},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__ */
192
- return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(bb,{...i})})},n)}function xb({url:e,autoRotate:t,hasCustomCamera:n}){const r=f(null),o=f(null),i=f(null),s=f(0),l=f(0),c=f(0),{scene:u,camera:d}=_();return a(()=>{const t=new z;return t.register(e=>new C(e)),t.load(e,e=>{const t=e.userData?.vrm;if(t){r.current=t,t.scene.rotation.y=Math.PI;const e=(new E.Box3).setFromObject(t.scene).getSize(new E.Vector3);if(c.current=0,l.current=Math.PI,u.add(t.scene),!n){const t=.75*e.y,n=d.fov*(Math.PI/180),r=.55*e.y*.5/Math.tan(n/2)*1.3;d.position.set(0,t,r),d.lookAt(0,t,0)}t.lookAt&&(t.lookAt.target=d)}else{const t=e.scene;t.updateMatrixWorld(!0);const r=(new E.Box3).setFromObject(t),a=r.getCenter(new E.Vector3),s=r.getSize(new E.Vector3),p=new E.Group;if(t.position.sub(a),p.add(t),o.current=p,c.current=0,l.current=0,u.add(p),!n){const e=d.fov*(Math.PI/180),t=.3*s.y,n=.5*s.y/Math.tan(e/2)*1.2;d.position.set(0,t,n),d.lookAt(0,t,0)}if(e.animations.length>0){const n=new E.AnimationMixer(t);i.current=n,e.animations.forEach(e=>{n.clipAction(e).play()})}}},void 0,e=>{console.error("[Avatar3DPreview] Failed to load model:",e)}),()=>{r.current&&(u.remove(r.current.scene),r.current=null),o.current&&(u.remove(o.current),o.current=null),i.current&&(i.current.stopAllAction(),i.current=null)}},[e,u,d,t]),S((e,n)=>{const a=Math.min(n,.1);s.current+=1.2*a;const u=t?.5*a:0;if(o.current){i.current&&i.current.update(a);const e=o.current,n=.003*Math.sin(s.current);e.position.y=c.current+n,t&&(l.current-=u);const r=.02*Math.sin(.3*s.current);return void(e.rotation.y=l.current+r)}const d=r.current;if(d){const e=.003*Math.sin(s.current);if(d.scene.position.y=c.current+e,t&&(l.current-=u,d.scene.rotation.y=l.current),d.humanoid){const e=d.humanoid.getNormalizedBoneNode("spine");if(e){const t=.008*Math.sin(.4*s.current),n=.005*Math.cos(.25*s.current);e.rotation.z=E.MathUtils.lerp(e.rotation.z,t,2*a),e.rotation.x=E.MathUtils.lerp(e.rotation.x,n,2*a)}}d.update(a)}}),null}function kb({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function _b({url:e,className:t="",cameraPosition:n,targetPosition:r,autoRotate:o=!0}){return e?/* @__PURE__ */b("div",{className:`relative w-full h-full ${t}`,children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"w-full h-full flex items-center justify-center text-gray-400 text-xs",children:"Loading 3D Model..."}),children:/* @__PURE__ */y(k,{style:{width:"100%",height:"100%",background:"transparent"},gl:{alpha:!0,antialias:!0,preserveDrawingBuffer:!1},camera:{fov:30,near:.01,far:10},dpr:[1,2],children:[
193
- /* @__PURE__ */b(kb,{position:n,target:r}),
171
+ /* @__PURE__ */b("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const Wc={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Hc={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},Zc={text:"text-primary-foreground"};const Jc=(e,t)=>t.some(t=>e instanceof t);let Kc,Gc;const Yc=/* @__PURE__ */new WeakMap,Qc=/* @__PURE__ */new WeakMap,Xc=/* @__PURE__ */new WeakMap;let eu={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Yc.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ru(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function tu(e){eu=e(eu)}function nu(e){return"function"==typeof e?(t=e,(Gc||(Gc=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(ou(this),e),ru(this.request)}:function(...e){return ru(t.apply(ou(this),e))}):(e instanceof IDBTransaction&&function(e){if(Yc.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});Yc.set(e,t)}(e),Jc(e,Kc||(Kc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,eu):e);var t}function ru(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(ru(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return Xc.set(t,e),t}(e);if(Qc.has(e))return Qc.get(e);const t=nu(e);return t!==e&&(Qc.set(e,t),Xc.set(t,e)),t}const ou=e=>Xc.get(e),iu=["get","getKey","getAll","getAllKeys","count"],au=["put","add","delete","clear"],su=/* @__PURE__ */new Map;function lu(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(su.get(t))return su.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=au.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!iu.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return su.set(t,i),i}tu(e=>({...e,get:(t,n,r)=>lu(t,n)||e.get(t,n,r),has:(t,n)=>!!lu(t,n)||e.has(t,n)}));const cu=["continue","continuePrimaryKey","advance"],uu={},du=/* @__PURE__ */new WeakMap,pu=/* @__PURE__ */new WeakMap,hu={get(e,t){if(!cu.includes(t))return e[t];let n=uu[t];return n||(n=uu[t]=function(...e){du.set(this,pu.get(this)[t](...e))}),n}};async function*fu(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,hu);for(pu.set(n,t),Xc.set(n,ou(t));t;)yield n,t=await(du.get(n)||t.continue()),du.delete(n)}function mu(e,t){return t===Symbol.asyncIterator&&Jc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Jc(e,[IDBIndex,IDBObjectStore])}tu(e=>({...e,get:(t,n,r)=>mu(t,n)?fu:e.get(t,n,r),has:(t,n)=>mu(t,n)||e.has(t,n)}));class gu{db=null;DB_NAME;DB_VERSION=1;constructor(e,t="default"){this.DB_NAME=`botuyo-chat-${e}-${t}`}async init(){try{this.db=await function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=ru(a);return r&&a.addEventListener("upgradeneeded",e=>{r(ru(a.result),e.oldVersion,e.newVersion,ru(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(e){e.objectStoreNames.contains("messages")||e.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata")}}),Rt("IndexedDB initialized")}catch(e){throw jt("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){jt("Failed to save message:",t)}}async saveMessages(e){this.db||await this.init();try{const t=this.db.transaction("messages","readwrite");await Promise.all([...e.map(e=>t.store.put(e)),t.done])}catch(t){jt("Failed to save messages:",t)}}async getMessages(e=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-e)}catch(t){return jt("Failed to get messages:",t),[]}}async getMessage(e){this.db||await this.init();try{return await this.db.get("messages",e)}catch(t){return void jt("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){jt("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Rt("Messages cleared from IndexedDB")}catch(e){jt("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){jt("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return jt("Failed to get metadata:",e),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),Rt("All data cleared from IndexedDB")}catch(e){jt("Failed to clear all data:",e)}}async migrateFromLocalStorage(e,t="default"){try{const n=`botuyo_chat_v1_${e}_${t}`,r=localStorage.getItem(n);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const e=o.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}));await this.saveMessages(e),Rt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Rt("Migration from localStorage completed")}catch(n){jt("Failed to migrate from localStorage:",n)}}}const bu=/* @__PURE__ */new Map,yu={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function vu(e,t){switch(t.type){case"TOGGLE_WINDOW":return{...e,isOpen:!e.isOpen};case"OPEN_WINDOW":return{...e,isOpen:!0};case"CLOSE_WINDOW":return{...e,isOpen:!1};case"SET_CONNECTED":return{...e,isConnected:t.payload};case"SET_TYPING":return{...e,isTyping:t.payload};case"ADD_MESSAGE":{if(e.messages.some(e=>e.id===t.payload.id))return e;if(t.payload.id.startsWith("msg-")&&"text"===t.payload.type){const n=/* @__PURE__ */(new Date).getTime();if(e.messages.slice(-10).some(e=>"text"===e.type&&e.sender===t.payload.sender&&"content"in e&&"content"in t.payload&&e.content===t.payload.content&&Math.abs(n-new Date(e.timestamp).getTime())<3e4))return e}const n=[...e.messages,t.payload],r="bot"===t.payload.sender;return{...e,messages:n,isTyping:!r&&e.isTyping}}case"SET_MESSAGES":return{...e,messages:[...t.payload]};case"SET_ERROR":return{...e,error:t.payload};case"SET_SESSION_ID":return{...e,sessionId:t.payload};case"ANSWER_QUIZ":{const{messageId:n,buttonId:r}=t.payload;return{...e,messages:e.messages.map(e=>e.id===n&&"buttons"===e.type?{...e,answered:!0,...r?{selectedId:r}:{}}:e)}}case"CLEAR_CHAT":return{...yu,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,isConnected:!1,isTyping:!1,error:null};default:return e}}function wu(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=a.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function a(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class xu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ku extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const _u={};function Su(e){return _u}function Cu(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Eu(e,t){return"bigint"==typeof t?t.toString():t}function zu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Nu(e){return null==e}function Au(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Iu=/* @__PURE__ */Symbol("evaluating");function Tu(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Iu)return void 0===r&&(r=Iu,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ou(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Mu(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Pu(e){return JSON.stringify(e)}const Lu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Du(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const ju=zu(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Fu(e){if(!1===Du(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Du(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Ru(e){return Fu(e)?{...e}:Array.isArray(e)?[...e]:e}const $u=/* @__PURE__ */new Set(["string","number","symbol"]);function Bu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Uu(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function qu(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Vu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Wu(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Hu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Zu(e){return"string"==typeof e?e:e?.message}function Ju(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Ku(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Gu(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Yu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Eu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Qu=wu("$ZodError",Yu),Xu=wu("$ZodError",Yu,{Parent:Error}),ed=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new xu;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Ju(e,i,Su())));throw Lu(t,o?.callee),t}return a.value},td=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Ju(e,i,Su())));throw Lu(t,o?.callee),t}return a.value},nd=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new xu;return i.issues.length?{success:!1,error:new(e??Qu)(i.issues.map(e=>Ju(e,o,Su())))}:{success:!0,data:i.value}},rd=/* @__PURE__ */nd(Xu),od=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>Ju(e,o,Su())))}:{success:!0,data:i.value}},id=/* @__PURE__ */od(Xu),ad=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ed(e)(t,n,o)},sd=e=>(t,n,r)=>ed(e)(t,n,r),ld=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return td(e)(t,n,o)},cd=e=>async(t,n,r)=>td(e)(t,n,r),ud=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return nd(e)(t,n,o)},dd=e=>(t,n,r)=>nd(e)(t,n,r),pd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return od(e)(t,n,o)},hd=e=>async(t,n,r)=>od(e)(t,n,r),fd=/^[cC][^\s-]{8,}$/,md=/^[0-9a-z]+$/,gd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bd=/^[0-9a-vA-V]{20}$/,yd=/^[A-Za-z0-9]{27}$/,vd=/^[a-zA-Z0-9_-]{21}$/,wd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,kd=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,_d=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Cd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ed=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,zd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ad=/^[A-Za-z0-9_-]*$/,Id=/^\+[1-9]\d{6,14}$/,Td="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Od=/* @__PURE__ */new RegExp(`^${Td}$`);function Md(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Pd=/^-?\d+$/,Ld=/^-?\d+(?:\.\d+)?$/,Dd=/^[^A-Z]*$/,jd=/^[^a-z]*$/,Fd=/* @__PURE__ */wu("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Rd={number:"number",bigint:"bigint",object:"date"},$d=/* @__PURE__ */wu("$ZodCheckLessThan",(e,t)=>{Fd.init(e,t);const n=Rd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bd=/* @__PURE__ */wu("$ZodCheckGreaterThan",(e,t)=>{Fd.init(e,t);const n=Rd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ud=/* @__PURE__ */wu("$ZodCheckMultipleOf",(e,t)=>{Fd.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),qd=/* @__PURE__ */wu("$ZodCheckNumberFormat",(e,t)=>{Fd.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Vu[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=o,r.maximum=i,n&&(r.pattern=Pd)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Vd=/* @__PURE__ */wu("$ZodCheckMaxLength",(e,t)=>{var n;Fd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Nu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=Ku(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wd=/* @__PURE__ */wu("$ZodCheckMinLength",(e,t)=>{var n;Fd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Nu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=Ku(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Hd=/* @__PURE__ */wu("$ZodCheckLengthEquals",(e,t)=>{var n;Fd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Nu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=Ku(r),a=o>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Zd=/* @__PURE__ */wu("$ZodCheckStringFormat",(e,t)=>{var n,r;Fd.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Jd=/* @__PURE__ */wu("$ZodCheckRegex",(e,t)=>{Zd.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Kd=/* @__PURE__ */wu("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dd),Zd.init(e,t)}),Gd=/* @__PURE__ */wu("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jd),Zd.init(e,t)}),Yd=/* @__PURE__ */wu("$ZodCheckIncludes",(e,t)=>{Fd.init(e,t);const n=Bu(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Qd=/* @__PURE__ */wu("$ZodCheckStartsWith",(e,t)=>{Fd.init(e,t);const n=new RegExp(`^${Bu(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Xd=/* @__PURE__ */wu("$ZodCheckEndsWith",(e,t)=>{Fd.init(e,t);const n=new RegExp(`.*${Bu(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ep=/* @__PURE__ */wu("$ZodCheckOverwrite",(e,t)=>{Fd.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class tp{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const o of r)this.content.push(o)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const np={major:4,minor:3,patch:6},rp=/* @__PURE__ */wu("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=np;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const t of o._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=Wu(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new xu;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Wu(e,t)))});else{if(e.issues.length===t)continue;o||(o=Wu(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Wu(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new xu;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new xu;return a.then(e=>t(e,r,i))}return t(a,r,i)}}Tu(e,"~standard",()=>({validate:t=>{try{const n=rd(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return id(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),op=/* @__PURE__ */wu("$ZodString",(e,t)=>{var n;rp.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ip=/* @__PURE__ */wu("$ZodStringFormat",(e,t)=>{Zd.init(e,t),op.init(e,t)}),ap=/* @__PURE__ */wu("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=xd),ip.init(e,t)}),sp=/* @__PURE__ */wu("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=kd(e))}else t.pattern??(t.pattern=kd());ip.init(e,t)}),lp=/* @__PURE__ */wu("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=_d),ip.init(e,t)}),cp=/* @__PURE__ */wu("$ZodURL",(e,t)=>{ip.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),up=/* @__PURE__ */wu("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ip.init(e,t)}),dp=/* @__PURE__ */wu("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=vd),ip.init(e,t)}),pp=/* @__PURE__ */wu("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=fd),ip.init(e,t)}),hp=/* @__PURE__ */wu("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=md),ip.init(e,t)}),fp=/* @__PURE__ */wu("$ZodULID",(e,t)=>{t.pattern??(t.pattern=gd),ip.init(e,t)}),mp=/* @__PURE__ */wu("$ZodXID",(e,t)=>{t.pattern??(t.pattern=bd),ip.init(e,t)}),gp=/* @__PURE__ */wu("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=yd),ip.init(e,t)}),bp=/* @__PURE__ */wu("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Md({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Td}T(?:${r})$`)}(t)),ip.init(e,t)}),yp=/* @__PURE__ */wu("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Od),ip.init(e,t)}),vp=/* @__PURE__ */wu("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Md(t)}$`)),ip.init(e,t)}),wp=/* @__PURE__ */wu("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=wd),ip.init(e,t)}),xp=/* @__PURE__ */wu("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sd),ip.init(e,t),e._zod.bag.format="ipv4"}),kp=/* @__PURE__ */wu("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Cd),ip.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),_p=/* @__PURE__ */wu("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ed),ip.init(e,t)}),Sp=/* @__PURE__ */wu("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=zd),ip.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Cp(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Ep=/* @__PURE__ */wu("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Nd),ip.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Cp(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),zp=/* @__PURE__ */wu("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ad),ip.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Ad.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Cp(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Np=/* @__PURE__ */wu("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Id),ip.init(e,t)}),Ap=/* @__PURE__ */wu("$ZodJWT",(e,t)=>{ip.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ip=/* @__PURE__ */wu("$ZodNumber",(e,t)=>{rp.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ld,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Tp=/* @__PURE__ */wu("$ZodNumberFormat",(e,t)=>{qd.init(e,t),Ip.init(e,t)}),Op=/* @__PURE__ */wu("$ZodAny",(e,t)=>{rp.init(e,t),e._zod.parse=e=>e}),Mp=/* @__PURE__ */wu("$ZodUnknown",(e,t)=>{rp.init(e,t),e._zod.parse=e=>e}),Pp=/* @__PURE__ */wu("$ZodNever",(e,t)=>{rp.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Lp(e,t,n){e.issues.length&&t.issues.push(...Hu(n,e.issues)),t.value[n]=e.value}const Dp=/* @__PURE__ */wu("$ZodArray",(e,t)=>{rp.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const a=o[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?i.push(s.then(t=>Lp(t,n,e))):Lp(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function jp(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Hu(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Fp(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Rp(e,t,n,r,o,i){const a=[],s=o.keySet,l=o.catchall._zod,c=l.def.type,u="optional"===l.optout;for(const d in t){if(s.has(d))continue;if("never"===c){a.push(d);continue}const o=l.run({value:t[d],issues:[]},r);o instanceof Promise?e.push(o.then(e=>jp(e,n,d,t,u))):jp(o,n,d,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const $p=/* @__PURE__ */wu("$ZodObject",(e,t)=>{rp.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=zu(()=>Fp(t));Tu(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const o=Du,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const s=t.value;if(!o(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=a.shape;for(const e of a.keys){const r=c[e],o="optional"===r._zod.optout,i=r._zod.run({value:s[e],issues:[]},n);i instanceof Promise?l.push(i.then(n=>jp(n,t,e,s,o))):jp(i,t,e,s,o)}return i?Rp(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),Bp=/* @__PURE__ */wu("$ZodObjectJIT",(e,t)=>{$p.init(e,t);const n=e._zod.parse,r=zu(()=>Fp(t));let o;const i=Du,a=!_u.jitless,s=a&&ju.value,l=t.catchall;let c;e._zod.parse=(u,d)=>{c??(c=r.value);const p=u.value;return i(p)?a&&s&&!1===d?.async&&!0!==d.jitless?(o||(o=(e=>{const t=new tp(["shape","payload","ctx"]),n=r.value,o=e=>{const t=Pu(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=/* @__PURE__ */Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=Pu(r),s=e[r],l="optional"===s?._zod?.optout;t.write(`const ${n} = ${o(r)};`),l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),u=o(u,d),l?Rp([],p,u,d,c,e):u):n(u,d):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Up(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter(e=>!Wu(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Ju(e,r,Su())))}),t)}const qp=/* @__PURE__ */wu("$ZodUnion",(e,t)=>{rp.init(e,t),Tu(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Tu(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Tu(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Tu(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Au(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Up(t,o,e,i)):Up(s,o,e,i)}}),Vp=/* @__PURE__ */wu("$ZodIntersection",(e,t)=>{rp.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>Hp(e,t,n)):Hp(e,o,i)}});function Wp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Fu(e)&&Fu(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const i of r){const n=Wp(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=Wp(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Hp(e,t,n){const r=/* @__PURE__ */new Map;let o;for(const s of t.issues)if("unrecognized_keys"===s.code){o??(o=s);for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(s);for(const s of n.issues)if("unrecognized_keys"===s.code)for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(s);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),Wu(e))return e;const a=Wp(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const Zp=/* @__PURE__ */wu("$ZodEnum",(e,t)=>{rp.init(e,t);const n=Cu(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>$u.has(typeof e)).map(e=>"string"==typeof e?Bu(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Jp=/* @__PURE__ */wu("$ZodTransform",(e,t)=>{rp.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new ku(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n));if(o instanceof Promise)throw new xu;return n.value=o,n}});function Kp(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Gp=/* @__PURE__ */wu("$ZodOptional",(e,t)=>{rp.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Tu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),Tu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Au(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Kp(t,e.value)):Kp(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Yp=/* @__PURE__ */wu("$ZodExactOptional",(e,t)=>{Gp.init(e,t),Tu(e._zod,"values",()=>t.innerType._zod.values),Tu(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Qp=/* @__PURE__ */wu("$ZodNullable",(e,t)=>{rp.init(e,t),Tu(e._zod,"optin",()=>t.innerType._zod.optin),Tu(e._zod,"optout",()=>t.innerType._zod.optout),Tu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Au(e.source)}|null)$`):void 0}),Tu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Xp=/* @__PURE__ */wu("$ZodDefault",(e,t)=>{rp.init(e,t),e._zod.optin="optional",Tu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>eh(e,t)):eh(r,t)}});function eh(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const th=/* @__PURE__ */wu("$ZodPrefault",(e,t)=>{rp.init(e,t),e._zod.optin="optional",Tu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),nh=/* @__PURE__ */wu("$ZodNonOptional",(e,t)=>{rp.init(e,t),Tu(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>rh(t,e)):rh(o,e)}});function rh(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const oh=/* @__PURE__ */wu("$ZodCatch",(e,t)=>{rp.init(e,t),Tu(e._zod,"optin",()=>t.innerType._zod.optin),Tu(e._zod,"optout",()=>t.innerType._zod.optout),Tu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ju(e,n,Su()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Ju(e,n,Su()))},input:e.value}),e.issues=[]),e)}}),ih=/* @__PURE__ */wu("$ZodPipe",(e,t)=>{rp.init(e,t),Tu(e._zod,"values",()=>t.in._zod.values),Tu(e._zod,"optin",()=>t.in._zod.optin),Tu(e._zod,"optout",()=>t.out._zod.optout),Tu(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ah(e,t.in,n)):ah(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ah(e,t.out,n)):ah(r,t.out,n)}});function ah(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const sh=/* @__PURE__ */wu("$ZodReadonly",(e,t)=>{rp.init(e,t),Tu(e._zod,"propValues",()=>t.innerType._zod.propValues),Tu(e._zod,"values",()=>t.innerType._zod.values),Tu(e._zod,"optin",()=>t.innerType?._zod?.optin),Tu(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(lh):lh(r)}});function lh(e){return e.value=Object.freeze(e.value),e}const ch=/* @__PURE__ */wu("$ZodCustom",(e,t)=>{Fd.init(e,t),rp.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>uh(t,n,r,e));uh(o,n,r,e)}});function uh(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Gu(e))}}var dh;(dh=globalThis).__zod_globalRegistry??(dh.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const ph=globalThis.__zod_globalRegistry;function hh(e,t){return new e({type:"string",...qu(t)})}function fh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qu(t)})}function mh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qu(t)})}function gh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qu(t)})}function bh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qu(t)})}function yh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qu(t)})}function vh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qu(t)})}function wh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qu(t)})}function xh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qu(t)})}function kh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qu(t)})}function _h(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qu(t)})}function Sh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qu(t)})}function Ch(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qu(t)})}function Eh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qu(t)})}function zh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qu(t)})}function Nh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qu(t)})}function Ah(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qu(t)})}function Ih(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qu(t)})}function Th(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qu(t)})}function Oh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qu(t)})}function Mh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qu(t)})}function Ph(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qu(t)})}function Lh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qu(t)})}function Dh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qu(t)})}function jh(e,t){return new e({type:"string",format:"date",check:"string_format",...qu(t)})}function Fh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qu(t)})}function Rh(e,t){return new e({type:"string",format:"duration",check:"string_format",...qu(t)})}function $h(e,t){return new e({type:"number",checks:[],...qu(t)})}function Bh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...qu(t)})}function Uh(e){return new e({type:"any"})}function qh(e){return new e({type:"unknown"})}function Vh(e,t){return new e({type:"never",...qu(t)})}function Wh(e,t){return new $d({check:"less_than",...qu(t),value:e,inclusive:!1})}function Hh(e,t){return new $d({check:"less_than",...qu(t),value:e,inclusive:!0})}function Zh(e,t){return new Bd({check:"greater_than",...qu(t),value:e,inclusive:!1})}function Jh(e,t){return new Bd({check:"greater_than",...qu(t),value:e,inclusive:!0})}function Kh(e,t){return new Ud({check:"multiple_of",...qu(t),value:e})}function Gh(e,t){return new Vd({check:"max_length",...qu(t),maximum:e})}function Yh(e,t){return new Wd({check:"min_length",...qu(t),minimum:e})}function Qh(e,t){return new Hd({check:"length_equals",...qu(t),length:e})}function Xh(e,t){return new Jd({check:"string_format",format:"regex",...qu(t),pattern:e})}function ef(e){return new Kd({check:"string_format",format:"lowercase",...qu(e)})}function tf(e){return new Gd({check:"string_format",format:"uppercase",...qu(e)})}function nf(e,t){return new Yd({check:"string_format",format:"includes",...qu(t),includes:e})}function rf(e,t){return new Qd({check:"string_format",format:"starts_with",...qu(t),prefix:e})}function of(e,t){return new Xd({check:"string_format",format:"ends_with",...qu(t),suffix:e})}function af(e){return new ep({check:"overwrite",tx:e})}function sf(e){/* @__PURE__ */
172
+ return af(t=>t.normalize(e))}function lf(){/* @__PURE__ */
173
+ return af(e=>e.trim())}function cf(){/* @__PURE__ */
174
+ return af(e=>e.toLowerCase())}function uf(){/* @__PURE__ */
175
+ return af(e=>e.toUpperCase())}function df(){/* @__PURE__ */
176
+ return af(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function pf(e,t,n){return new e({type:"array",element:t,...qu(n)})}function hf(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qu(n)})}function ff(e){const t=/* @__PURE__ */mf(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Gu(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Gu(r))}},e(n.value,n)));return t}function mf(e,t){const n=new Fd({check:"custom",...qu(t)});return n._zod.check=e,n}function gf(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ph,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function bf(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(a.ref||(a.ref=i),bf(i,t,r),t.seen.get(i).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),"input"===t.io&&wf(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function yf(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=/* @__PURE__ */new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,i[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const o=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+i}})(t);r.def={...r.schema},i&&(r.defId=i);const a=r.schema;for(const e in a)delete a[e];a.$ref=o};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t===i[0]){o(i);continue}if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){o(i);continue}}const r=e.metadataRegistry.get(i[0])?.id;(r||n.cycle||n.count>1&&"ref"===e.reused)&&o(i)}}function vf(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const o=n.def??n.schema,i={...o},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),s=n.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(o,s):(o.allOf=o.allOf??[],o.allOf.push(s)),Object.assign(o,i),t._zod.parent===a)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(s.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const s=t._zod.parent;if(s&&s!==a){r(s);const t=e.seen.get(s);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const s of[...e.seen.entries()].reverse())r(s[0]);const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const e=s[1];e.def&&e.defId&&(i[e.defId]=e.def)}e.external||Object.keys(i).length>0&&("draft-2020-12"===e.target?o.$defs=i:o.definitions=i);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:xf(t,"input",e.processors),output:xf(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function wf(e,t){const n=t??{seen:/* @__PURE__ */new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return wf(r.element,n);if("set"===r.type)return wf(r.valueType,n);if("lazy"===r.type)return wf(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return wf(r.innerType,n);if("intersection"===r.type)return wf(r.left,n)||wf(r.right,n);if("record"===r.type||"map"===r.type)return wf(r.keyType,n)||wf(r.valueType,n);if("pipe"===r.type)return wf(r.in,n)||wf(r.out,n);if("object"===r.type){for(const e in r.shape)if(wf(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(wf(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(wf(e,n))return!0;return!(!r.rest||!wf(r.rest,n))}return!1}const xf=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},a=gf({...o??{},target:i,io:t,processors:n});return bf(e,a),yf(a,e),vf(a,e)},kf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_f=(e,t,n,r)=>{const o=e._zod.def;bf(o.innerType,t,r),t.seen.get(e).ref=o.innerType},Sf=/* @__PURE__ */wu("ZodISODateTime",(e,t)=>{bp.init(e,t),Wf.init(e,t)}),Cf=/* @__PURE__ */wu("ZodISODate",(e,t)=>{yp.init(e,t),Wf.init(e,t)}),Ef=/* @__PURE__ */wu("ZodISOTime",(e,t)=>{vp.init(e,t),Wf.init(e,t)}),zf=/* @__PURE__ */wu("ZodISODuration",(e,t)=>{wp.init(e,t),Wf.init(e,t)}),Nf=wu("ZodError",(e,t)=>{Qu.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e}));else if("invalid_key"===o.code)r({issues:o.issues});else if("invalid_element"===o.code)r({issues:o.issues});else if(0===o.path.length)n._errors.push(t(o));else{let e=n,r=0;for(;r<o.path.length;){const n=o.path[r];r===o.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(o))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Eu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Eu,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),Af=/* @__PURE__ */ed(Nf),If=/* @__PURE__ */td(Nf),Tf=/* @__PURE__ */nd(Nf),Of=/* @__PURE__ */od(Nf),Mf=/* @__PURE__ */ad(Nf),Pf=/* @__PURE__ */sd(Nf),Lf=/* @__PURE__ */ld(Nf),Df=/* @__PURE__ */cd(Nf),jf=/* @__PURE__ */ud(Nf),Ff=/* @__PURE__ */dd(Nf),Rf=/* @__PURE__ */pd(Nf),$f=/* @__PURE__ */hd(Nf),Bf=/* @__PURE__ */wu("ZodType",(e,t)=>(rp.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:xf(e,"input"),output:xf(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=gf({...n,processors:t});return bf(e,r),yf(r,e),vf(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Mu(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Uu(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Af(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Tf(e,t,n),e.parseAsync=async(t,n)=>If(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Of(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Mf(e,t,n),e.decode=(t,n)=>Pf(e,t,n),e.encodeAsync=async(t,n)=>Lf(e,t,n),e.decodeAsync=async(t,n)=>Df(e,t,n),e.safeEncode=(t,n)=>jf(e,t,n),e.safeDecode=(t,n)=>Ff(e,t,n),e.safeEncodeAsync=async(t,n)=>Rf(e,t,n),e.safeDecodeAsync=async(t,n)=>$f(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){/* @__PURE__ */
177
+ return hf($m,e,t)}(t,n)),e.superRefine=t=>e.check(/* @__PURE__ */ff(t)),e.overwrite=t=>e.check(/* @__PURE__ */af(t)),e.optional=()=>Am(e),e.exactOptional=()=>new Im({type:"optional",innerType:e}),e.nullable=()=>Om(e),e.nullish=()=>Am(Om(e)),e.nonoptional=t=>function(e,t){return new Lm({type:"nonoptional",innerType:e,...qu(t)})}(e,t),e.array=()=>wm(e),e.or=t=>new _m({type:"union",options:[e,t],...qu(void 0)}),e.and=t=>new Sm({type:"intersection",left:e,right:t}),e.transform=t=>Fm(e,new zm({type:"transform",transform:t})),e.default=t=>{return n=t,new Mm({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Ru(n)}});var n},e.prefault=t=>{return n=t,new Pm({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Ru(n)}});var n},e.catch=t=>{return new Dm({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Fm(e,t),e.readonly=()=>new Rm({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return ph.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>ph.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return ph.get(e);const n=e.clone();return ph.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Uf=/* @__PURE__ */wu("_ZodString",(e,t)=>{op.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:a,patterns:s,contentEncoding:l}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),a&&(r.format=kf[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),l&&(r.contentEncoding=l),s&&s.size>0){const e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(/* @__PURE__ */Xh(...t)),e.includes=(...t)=>e.check(/* @__PURE__ */nf(...t)),e.startsWith=(...t)=>e.check(/* @__PURE__ */rf(...t)),e.endsWith=(...t)=>e.check(/* @__PURE__ */of(...t)),e.min=(...t)=>e.check(/* @__PURE__ */Yh(...t)),e.max=(...t)=>e.check(/* @__PURE__ */Gh(...t)),e.length=(...t)=>e.check(/* @__PURE__ */Qh(...t)),e.nonempty=(...t)=>e.check(/* @__PURE__ */Yh(1,...t)),e.lowercase=t=>e.check(/* @__PURE__ */ef(t)),e.uppercase=t=>e.check(/* @__PURE__ */tf(t)),e.trim=()=>e.check(/* @__PURE__ */lf()),e.normalize=(...t)=>e.check(/* @__PURE__ */sf(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */cf()),e.toUpperCase=()=>e.check(/* @__PURE__ */uf()),e.slugify=()=>e.check(/* @__PURE__ */df())}),qf=/* @__PURE__ */wu("ZodString",(e,t)=>{op.init(e,t),Uf.init(e,t),e.email=t=>e.check(/* @__PURE__ */fh(Hf,t)),e.url=t=>e.check(/* @__PURE__ */wh(Kf,t)),e.jwt=t=>e.check(/* @__PURE__ */Lh(um,t)),e.emoji=t=>e.check(/* @__PURE__ */xh(Gf,t)),e.guid=t=>e.check(/* @__PURE__ */mh(Zf,t)),e.uuid=t=>e.check(/* @__PURE__ */gh(Jf,t)),e.uuidv4=t=>e.check(/* @__PURE__ */bh(Jf,t)),e.uuidv6=t=>e.check(/* @__PURE__ */yh(Jf,t)),e.uuidv7=t=>e.check(/* @__PURE__ */vh(Jf,t)),e.nanoid=t=>e.check(/* @__PURE__ */kh(Yf,t)),e.guid=t=>e.check(/* @__PURE__ */mh(Zf,t)),e.cuid=t=>e.check(/* @__PURE__ */_h(Qf,t)),e.cuid2=t=>e.check(/* @__PURE__ */Sh(Xf,t)),e.ulid=t=>e.check(/* @__PURE__ */Ch(em,t)),e.base64=t=>e.check(/* @__PURE__ */Oh(sm,t)),e.base64url=t=>e.check(/* @__PURE__ */Mh(lm,t)),e.xid=t=>e.check(/* @__PURE__ */Eh(tm,t)),e.ksuid=t=>e.check(/* @__PURE__ */zh(nm,t)),e.ipv4=t=>e.check(/* @__PURE__ */Nh(rm,t)),e.ipv6=t=>e.check(/* @__PURE__ */Ah(om,t)),e.cidrv4=t=>e.check(/* @__PURE__ */Ih(im,t)),e.cidrv6=t=>e.check(/* @__PURE__ */Th(am,t)),e.e164=t=>e.check(/* @__PURE__ */Ph(cm,t)),e.datetime=t=>e.check(function(e){/* @__PURE__ */
178
+ return Dh(Sf,e)}(t)),e.date=t=>e.check(function(e){/* @__PURE__ */
179
+ return jh(Cf,e)}(t)),e.time=t=>e.check(function(e){/* @__PURE__ */
180
+ return Fh(Ef,e)}(t)),e.duration=t=>e.check(function(e){/* @__PURE__ */
181
+ return Rh(zf,e)}(t))});function Vf(e){/* @__PURE__ */
182
+ return hh(qf,e)}const Wf=/* @__PURE__ */wu("ZodStringFormat",(e,t)=>{ip.init(e,t),Uf.init(e,t)}),Hf=/* @__PURE__ */wu("ZodEmail",(e,t)=>{lp.init(e,t),Wf.init(e,t)}),Zf=/* @__PURE__ */wu("ZodGUID",(e,t)=>{ap.init(e,t),Wf.init(e,t)}),Jf=/* @__PURE__ */wu("ZodUUID",(e,t)=>{sp.init(e,t),Wf.init(e,t)}),Kf=/* @__PURE__ */wu("ZodURL",(e,t)=>{cp.init(e,t),Wf.init(e,t)}),Gf=/* @__PURE__ */wu("ZodEmoji",(e,t)=>{up.init(e,t),Wf.init(e,t)}),Yf=/* @__PURE__ */wu("ZodNanoID",(e,t)=>{dp.init(e,t),Wf.init(e,t)}),Qf=/* @__PURE__ */wu("ZodCUID",(e,t)=>{pp.init(e,t),Wf.init(e,t)}),Xf=/* @__PURE__ */wu("ZodCUID2",(e,t)=>{hp.init(e,t),Wf.init(e,t)}),em=/* @__PURE__ */wu("ZodULID",(e,t)=>{fp.init(e,t),Wf.init(e,t)}),tm=/* @__PURE__ */wu("ZodXID",(e,t)=>{mp.init(e,t),Wf.init(e,t)}),nm=/* @__PURE__ */wu("ZodKSUID",(e,t)=>{gp.init(e,t),Wf.init(e,t)}),rm=/* @__PURE__ */wu("ZodIPv4",(e,t)=>{xp.init(e,t),Wf.init(e,t)}),om=/* @__PURE__ */wu("ZodIPv6",(e,t)=>{kp.init(e,t),Wf.init(e,t)}),im=/* @__PURE__ */wu("ZodCIDRv4",(e,t)=>{_p.init(e,t),Wf.init(e,t)}),am=/* @__PURE__ */wu("ZodCIDRv6",(e,t)=>{Sp.init(e,t),Wf.init(e,t)}),sm=/* @__PURE__ */wu("ZodBase64",(e,t)=>{Ep.init(e,t),Wf.init(e,t)}),lm=/* @__PURE__ */wu("ZodBase64URL",(e,t)=>{zp.init(e,t),Wf.init(e,t)}),cm=/* @__PURE__ */wu("ZodE164",(e,t)=>{Np.init(e,t),Wf.init(e,t)}),um=/* @__PURE__ */wu("ZodJWT",(e,t)=>{Ap.init(e,t),Wf.init(e,t)}),dm=/* @__PURE__ */wu("ZodNumber",(e,t)=>{Ip.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:o,maximum:i,format:a,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof o&&(r.minimum=o,"number"==typeof c&&"draft-04"!==t.target&&(c>=o?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof l&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),"number"==typeof i&&(r.maximum=i,"number"==typeof l&&"draft-04"!==t.target&&(l<=i?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s)})(e,t,n),e.gt=(t,n)=>e.check(/* @__PURE__ */Zh(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */Jh(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */Jh(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */Wh(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */Hh(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */Hh(t,n)),e.int=t=>e.check(fm(t)),e.safe=t=>e.check(fm(t)),e.positive=t=>e.check(/* @__PURE__ */Zh(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */Jh(0,t)),e.negative=t=>e.check(/* @__PURE__ */Wh(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */Hh(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */Kh(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */Kh(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function pm(e){/* @__PURE__ */
183
+ return $h(dm,e)}const hm=/* @__PURE__ */wu("ZodNumberFormat",(e,t)=>{Tp.init(e,t),dm.init(e,t)});function fm(e){/* @__PURE__ */
184
+ return Bh(hm,e)}const mm=/* @__PURE__ */wu("ZodAny",(e,t)=>{Op.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),gm=/* @__PURE__ */wu("ZodUnknown",(e,t)=>{Mp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function bm(){/* @__PURE__ */
185
+ return qh(gm)}const ym=/* @__PURE__ */wu("ZodNever",(e,t)=>{Pp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),vm=/* @__PURE__ */wu("ZodArray",(e,t)=>{Dp.init(e,t),Bf.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=bf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Yh(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Yh(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Gh(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Qh(t,n)),e.unwrap=()=>e.element});function wm(e,t){/* @__PURE__ */
186
+ return pf(vm,e,t)}const xm=/* @__PURE__ */wu("ZodObject",(e,t)=>{Bp.init(e,t),Bf.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]=bf(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=bf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),Tu(e,"shape",()=>t.shape),e.keyof=()=>Em(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:bm()}),e.loose=()=>e.clone({...e._zod.def,catchall:bm()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Vh(ym,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Fu(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(!Fu(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)}(Nm,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)}(Lm,e,t[0])});function km(e,t){const n={type:"object",shape:e??{},...qu(t)};return new xm(n)}const _m=/* @__PURE__ */wu("ZodUnion",(e,t)=>{qp.init(e,t),Bf.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)=>bf(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}),Sm=/* @__PURE__ */wu("ZodIntersection",(e,t)=>{Vp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=bf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=bf(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)}),Cm=/* @__PURE__ */wu("ZodEnum",(e,t)=>{Zp.init(e,t),Bf.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 Cm({...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 Cm({...t,checks:[],...qu(r),entries:o})}});function Em(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Cm({type:"enum",entries:n,...qu(t)})}const zm=/* @__PURE__ */wu("ZodTransform",(e,t)=>{Jp.init(e,t),Bf.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)}}),Nm=/* @__PURE__ */wu("ZodOptional",(e,t)=>{Gp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_f(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Am(e){return new Nm({type:"optional",innerType:e})}const Im=/* @__PURE__ */wu("ZodExactOptional",(e,t)=>{Yp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_f(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Tm=/* @__PURE__ */wu("ZodNullable",(e,t)=>{Qp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=bf(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 Om(e){return new Tm({type:"nullable",innerType:e})}const Mm=/* @__PURE__ */wu("ZodDefault",(e,t)=>{Xp.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;bf(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}),Pm=/* @__PURE__ */wu("ZodPrefault",(e,t)=>{th.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;bf(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}),Lm=/* @__PURE__ */wu("ZodNonOptional",(e,t)=>{nh.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;bf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Dm=/* @__PURE__ */wu("ZodCatch",(e,t)=>{oh.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;bf(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}),jm=/* @__PURE__ */wu("ZodPipe",(e,t)=>{ih.init(e,t),Bf.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;bf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Fm(e,t){return new jm({type:"pipe",in:e,out:t})}const Rm=/* @__PURE__ */wu("ZodReadonly",(e,t)=>{sh.init(e,t),Bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;bf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),$m=/* @__PURE__ */wu("ZodCustom",(e,t)=>{ch.init(e,t),Bf.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)}),Bm=/* @__PURE__ */Object.create(null);Bm.open="0",Bm.close="1",Bm.ping="2",Bm.pong="3",Bm.message="4",Bm.upgrade="5",Bm.noop="6";const Um=/* @__PURE__ */Object.create(null);Object.keys(Bm).forEach(e=>{Um[Bm[e]]=e});const qm={type:"error",data:"parser error"},Vm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Wm="function"==typeof ArrayBuffer,Hm=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Zm=({type:e,data:t},n,r)=>Vm&&t instanceof Blob?n?r(t):Jm(t,r):Wm&&(t instanceof ArrayBuffer||Hm(t))?n?r(t):Jm(new Blob([t]),r):r(Bm[e]+(t||"")),Jm=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function Km(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Gm;const Ym="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Bb=0;Bb<64;Bb++)Ym["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(Bb)]=Bb;const Qm="function"==typeof ArrayBuffer,Xm=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:eg(e.substring(1),t)}:Um[n]?e.length>1?{type:Um[n],data:e.substring(1)}:{type:Um[n]}:qm},eg=(e,t)=>{if(Qm){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=Ym[e.charCodeAt(t)],r=Ym[e.charCodeAt(t+1)],o=Ym[e.charCodeAt(t+2)],i=Ym[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 tg(n,t)}return{base64:!0,data:e}},tg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ng=String.fromCharCode(30);let rg;function og(e){return e.reduce((e,t)=>e+t.length,0)}function ig(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 ag(e){if(e)return function(e){for(var t in ag.prototype)e[t]=ag.prototype[t];return e}(e)}ag.prototype.on=ag.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},ag.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},ag.prototype.off=ag.prototype.removeListener=ag.prototype.removeAllListeners=ag.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},ag.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},ag.prototype.emitReserved=ag.prototype.emit,ag.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},ag.prototype.hasListeners=function(e){return!!this.listeners(e).length};const sg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),lg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function cg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const ug=lg.setTimeout,dg=lg.clearTimeout;function pg(e,t){t.useNativeTimers?(e.setTimeoutFn=ug.bind(lg),e.clearTimeoutFn=dg.bind(lg)):(e.setTimeoutFn=lg.setTimeout.bind(lg),e.clearTimeoutFn=lg.clearTimeout.bind(lg))}function hg(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 fg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class mg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class gg extends ag{constructor(e){super(),this.writable=!1,pg(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 mg(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=Xm(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 bg extends gg{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(ng),r=[];for(let o=0;o<n.length;o++){const e=Xm(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)=>{Zm(e,!1,e=>{r[i]=e,++o===n&&t(r.join(ng))})})})(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]=fg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let yg=!1;try{yg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch($b){}const vg=yg;function wg(){}class xg extends bg{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 kg extends ag{constructor(e,t,n){super(),this.createRequest=e,pg(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=cg(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=kg.requestsCount++,kg.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=wg,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete kg.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 _g(){for(let e in kg.requests)kg.requests.hasOwnProperty(e)&&kg.requests[e].abort()}kg.requestsCount=0,kg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",_g):"function"==typeof addEventListener&&addEventListener("onpagehide"in lg?"pagehide":"unload",_g,!1));const Sg=function(){const e=Cg({xdomain:!1});return e&&null!==e.responseType}();function Cg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||vg))return new XMLHttpRequest}catch(n){}if(!t)try{return new(lg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Eg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class zg extends gg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Eg?{}:cg(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($b){return this.emitReserved("error",$b)}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;Zm(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&sg(()=>{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]=fg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ng=lg.WebSocket||lg.MozWebSocket,Ag={websocket:class extends zg{createSocket(e,t,n){return Eg?new Ng(e,t,n):t?new Ng(e,t):new Ng(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends gg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch($b){return this.emitReserved("error",$b)}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){rg||(rg=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(og(n)<1)break;const e=ig(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(og(n)<2)break;const e=ig(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(og(n)<8)break;const e=ig(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(qm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(og(n)<o)break;const e=ig(n,o);s.enqueue(Xm(i?e:rg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(qm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){Vm&&e.data instanceof Blob?e.data.arrayBuffer().then(Km).then(t):Wm&&(e.data instanceof ArrayBuffer||Hm(e.data))?t(Km(e.data)):Zm(e,!1,e=>{Gm||(Gm=new TextEncoder),t(Gm.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&&sg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends xg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Sg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new kg(Cg,this.uri(),e)}}},Ig=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Tg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Og(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=Ig.exec(e||""),i={},a=14;for(;a--;)i[Tg[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 Mg="function"==typeof addEventListener&&"function"==typeof removeEventListener,Pg=[];Mg&&addEventListener("offline",()=>{Pg.forEach(e=>e())},!1);class Lg extends ag{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=Og(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=Og(t.host).host);pg(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)),Mg&&(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"})},Pg.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&&Lg.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",Lg.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+=hg(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,sg(()=>{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(Lg.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(),Mg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Pg.indexOf(this._offlineEventListener);-1!==e&&Pg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Lg.protocol=4;class Dg extends Lg{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;Lg.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;Lg.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 jg=class extends Dg{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=>Ag[e]).filter(e=>!!e)),super(e,n)}};const Fg="function"==typeof ArrayBuffer,Rg=Object.prototype.toString,$g="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Rg.call(Blob),Bg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Rg.call(File);function Ug(e){return Fg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||$g&&e instanceof Blob||Bg&&e instanceof File}function qg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(qg(e[t]))return!0;return!1}if(Ug(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return qg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&qg(e[n]))return!0;return!1}function Vg(e){const t=[],n=e.data,r=e;return r.data=Wg(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Wg(e,t){if(!e)return e;if(Ug(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]=Wg(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]=Wg(e[r],t));return n}return e}function Hg(e,t){return e.data=Zg(e.data,t),delete e.attachments,e}function Zg(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]=Zg(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Zg(e[n],t));return e}const Jg=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Kg,Gg;(Gg=Kg||(Kg={}))[Gg.CONNECT=0]="CONNECT",Gg[Gg.DISCONNECT=1]="DISCONNECT",Gg[Gg.EVENT=2]="EVENT",Gg[Gg.ACK=3]="ACK",Gg[Gg.CONNECT_ERROR=4]="CONNECT_ERROR",Gg[Gg.BINARY_EVENT=5]="BINARY_EVENT",Gg[Gg.BINARY_ACK=6]="BINARY_ACK";class Yg extends ag{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===Kg.BINARY_EVENT;n||t.type===Kg.BINARY_ACK?(t.type=n?Kg.EVENT:Kg.ACK,this.reconstructor=new Qg(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Ug(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===Kg[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Kg.BINARY_EVENT||n.type===Kg.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(!Xg(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(!Yg.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 Kg.CONNECT:return eb(t);case Kg.DISCONNECT:return void 0===t;case Kg.CONNECT_ERROR:return"string"==typeof t||eb(t);case Kg.EVENT:case Kg.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Jg.indexOf(t[0]));case Kg.ACK:case Kg.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Qg{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=Hg(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Xg=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function eb(e){return"[object Object]"===Object.prototype.toString.call(e)}const tb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:Yg,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Kg.EVENT&&e.type!==Kg.ACK||!qg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Kg.EVENT?Kg.BINARY_EVENT:Kg.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Kg.BINARY_EVENT&&e.type!==Kg.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=Vg(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return Kg}},Symbol.toStringTag,{value:"Module"}));function nb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const rb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ob extends ag{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=[nb(e,"open",this.onopen.bind(this)),nb(e,"packet",this.onpacket.bind(this)),nb(e,"error",this.onerror.bind(this)),nb(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(rb.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:Kg.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:Kg.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 Kg.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 Kg.EVENT:case Kg.BINARY_EVENT:this.onevent(e);break;case Kg.ACK:case Kg.BINARY_ACK:this.onack(e);break;case Kg.DISCONNECT:this.ondisconnect();break;case Kg.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:Kg.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:Kg.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 ib(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}ib.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)},ib.prototype.reset=function(){this.attempts=0},ib.prototype.setMin=function(e){this.ms=e},ib.prototype.setMax=function(e){this.max=e},ib.prototype.setJitter=function(e){this.jitter=e};class ab extends ag{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,pg(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 ib({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||tb;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 jg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=nb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=nb(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(nb(e,"ping",this.onping.bind(this)),nb(e,"data",this.ondata.bind(this)),nb(e,"error",this.onerror.bind(this)),nb(e,"close",this.onclose.bind(this)),nb(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){sg(()=>{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 ob(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 sb={};function lb(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=Og(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=sb[o]&&i in sb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new ab(r,t):(sb[o]||(sb[o]=new ab(r,t)),s=sb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(lb,{Manager:ab,Socket:ob,io:lb,connect:lb});const cb="chat_device_id";function ub(){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 Dt("[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 db=km({id:Vf().optional(),type:Em(["text","image","audio","location","system"]).default("text"),content:Vf().optional(),imageUrl:Vf().url().optional(),audioUrl:Vf().optional(),latitude:pm().optional(),longitude:pm().optional(),timestamp:Vf().optional(),sender:Em(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Uh(mm).optional(),sources:wm(Vf()).optional()}),pb=km({agentId:Vf().optional(),name:Vf().optional(),label:Vf().optional(),avatarUrl:Vf().optional(),variantKey:Vf().optional()});class hb{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),Dt("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?Ft():(this.isDisabled=!0,this.queue=[],Ft(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ft()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const fb=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},mb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let gb=null,bb=null;function yb(e){gb=e}function vb(e){bb=e}const wb=r(null);function xb({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=>{gb?(gb(e),Ft(0)):Dt("sendMessage called but no handler registered")},[]),g=s(()=>{bb?(bb(),Ft()):Dt("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__ */
187
+ return y(wb.Provider,{value:v,children:[e,
188
+ /* @__PURE__ */b(Nb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function kb(){const e=o(wb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const _b=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Sb(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,onThemeUpdate:v}=e,[w,x]=i(0),k=f(0),{t:_}=D(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new hb(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),C=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||$t,h=l||Bt;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 Dt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Rt("Notification permission:",e),"granted"===e}catch(e){return jt("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){jt("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=>{Ft(0)})}catch(n){jt("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}),E=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:z,actions:N}=function(e,t="default"){const[r,o]=g(vu,yu),[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 bu.has(n)||bu.set(n,new gu(e,t)),bu.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){Dt("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){jt("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){jt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){jt("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}}),[]);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}}}(t,o),A=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),I=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(cb);if(e)return e;const t=ub();return localStorage.setItem(cb,t),t}catch{return Dt("localStorage not available, using session-only device ID"),ub()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=db.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=lb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:l?.token,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),e.on("connect_error",e=>{h(!1),c.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){jt("ChatSocket Error processing bot_message:",t)}}),e.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 Ft(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){Ft()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e));const o=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};e.on("onboarding:command",e=>o(e)),e.on("form:command",e=>o(e)),e.on("request_form_state",()=>{o({type:"botuyo-request-form-state"})}),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),e.on("custom_event",e=>{if(o({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data){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("agent_switched"===e?.eventName&&e?.data){const t=pb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):Ft()}});const i=t=>{const{type:n}=t.data||{};"botuyo-onboarding-state"!==n&&"botuyo-form-state"!==n||e.emit("form_state",t.data)};window.addEventListener("message",i),d.current=e,e.__formCleanup=()=>window.removeEventListener("message",i)},[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}),jt("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]),N=u(()=>rc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>A?{...l||{},seo:{...A||{}}}:l,[l,A]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=k.current>0?t-k.current:void 0;k.current=t,N.addMessage(e),S.trackMessageReceived(e.type,n),z.isOpen||"bot"!==e.sender||(x(e=>e+1),C.notifyWithSound(e))},[N,z.isOpen,S,C]),onConnected:s((e,t)=>{N.setConnected(!0),N.setSessionId(e),S.trackConnectionStatus(!0),t&&v&&v(t),t&&b&&b("backend_config",t)},[N,b,v,S]),onDisconnected:s(()=>{N.setConnected(!1),S.trackConnectionStatus(!1)},[N,S]),onTyping:s(e=>N.setTyping(e),[N]),onError:s(e=>{N.setError(e),S.trackError(e)},[N,S]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:v,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);v&&v(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&N.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:_("agent_switched",{name:t})})},[v,N,_]),onHistoryLoaded:s(e=>{0!==e.length&&N.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,fb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(mb)),i=e.filter(e=>!r.has(e.id)&&fb(e)>n&&!o.has(mb(e)));return[...t,...i]}(z.messages,e))},[z.messages,N])}),T=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}(z.messages),[z.messages]),O=f(T);a(()=>{O.current=T},[T]);const M=s(()=>{Ft(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),Ft()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),Ft())},[z.isOpen,N,y,S]),P=s(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void N.setError(_("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};N.addMessage(t),S.trackMessageSent("text"),I.sendMessage(e,"text"),O.current&&N.answerQuiz(O.current.id)},[N,I,E,S,_]),L=s((e,t,n)=>{N.answerQuiz(e.id,n),I.sendMessage(`Answer: ${t}`,"text"),S.trackMessageSent("text")},[N,I,S]),j=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}`},N.addMessage(n);const r=await _b(e);I.sendMessage(r,t)},[N,I]),F=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"};N.addMessage(t),I.sendMessage(JSON.stringify(e),"location")},[N,I]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&P(e.detail.message)},o=()=>{z.isOpen||N.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)}},[z.isOpen,N,P]),a(()=>(yb(P),()=>yb(null)),[P]);const R=s(()=>{N.clearMessages(),Rt("Chat history cleared")},[N]);a(()=>(vb(R),()=>vb(null)),[R]);const $=u(()=>{if(z.isTyping)return"thinking";const e=[...z.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[z.isTyping,z.messages]);return{state:z,actions:N,unreadCount:w,currentBotEmotion:$,isConnected:I.isConnected,getSocket:I.getSocket,activeQuiz:T,handleToggle:M,handleSendText:P,handleSendAttachment:j,handleSendLocation:F,handleQuizAnswer:L}}function Cb({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=L.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),Ft(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Eb(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,initialOpen:w=!1,hideLauncher:x=!1,voiceFirst:k=!1}=e,_=f(null),S=oc(),C=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}(_),[E,z]=i(),{mergedTheme:N,mergedStyles:A,getContainerStyle:I}=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={...zt,...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:{...Wc,...e?.bubbleStyles?.radius},bot:{...Hc,...e?.bubbleStyles?.bot},user:{...Zc,...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,E);a(()=>{N.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.')},[N.isHidden]);const{state:T,actions:O,unreadCount:M,currentBotEmotion:P,isConnected:L,handleToggle:D,handleSendText:j,handleSendAttachment:F,handleSendLocation:R,getSocket:$,activeQuiz:B,handleQuizAnswer:U}=Sb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:z}),q=f(!1);a(()=>{w&&E&&!q.current&&(q.current=!0,T.isOpen||O.openWindow())},[w,E,T.isOpen,O]);const V=u(()=>{const e={...d||{}},t=E;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,E]),W=s(()=>{O.closeWindow()},[O]),H=s(e=>{e.stopPropagation()},[]),Z=I(T.isOpen,S,c?.position),J=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(!N.cssVariables)return e;let t={...N.cssVariables};if(C){const e=E?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Nt,...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},[N.cssVariables,C,E,c?.darkCssVariables]),K=c?.voiceNoiseGate??E?.voiceNoiseGate,G=u(()=>({noiseGate:K}),[K]),[Y,Q]=i(!1);return a(()=>{k&&L&&Q(!0)},[k,L]),N.isHidden?null:E?k?/* @__PURE__ */b("div",{ref:_,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...J},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Vc,{children:/* @__PURE__ */b(Uc,{isOpen:Y,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:At(N),avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},logoUrl:N.logoUrl,avatar3dUrl:c?.avatar3dUrl||E?.avatar3dUrl,voiceConfig:G,getSocket:$})})}):/* @__PURE__ */y("div",{ref:_,id:"botuyo-chat-widget-root",className:Et("botuyo-chat-widget flex flex-col",!S&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Z,...J,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:[
189
+ /* @__PURE__ */b("div",{className:Et("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",S?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",T.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:T.isOpen?"auto":"none"},onMouseDown:H,onTouchStart:H,children:/* @__PURE__ */b(Vc,{children:/* @__PURE__ */b(qc,{isOpen:T.isOpen,isConnected:L,isTyping:T.isTyping,messages:T.messages,onClose:W,onSendMessage:j,onSendAttachment:F,onSendLocation:R,botName:N.botName,logoUrl:N.logoUrl,welcomeMessage:N.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||E?.inputPlaceholder,position:c?.position,bubbleStyles:A,avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},mediaConfig:V,theme:N,avatar3dUrl:c?.avatar3dUrl||E?.avatar3dUrl,voiceConfig:G,getSocket:$,suggestedQuestions:E?.suggestedQuestions,activeQuiz:B,onQuizAnswer:U})})}),!x&&/* @__PURE__ */b("div",{className:Et(T.isOpen?"hidden":"block",!S&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:H,onTouchStart:H,children:/* @__PURE__ */b(qt,{isOpen:T.isOpen,onClick:D,unreadCount:M,position:c?.position||"bottom-right",primaryColor:At(N),logoUrl:N.logoUrl,starterPrompt:c?.starterPrompt||E?.starterPrompt,avatars:c?.avatars||E?.avatars||E?.avatarAnimations||{},emotion:P,styles:A,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??E?.avatarScale,showPromptAvatar:c?.showPromptAvatar??E?.showPromptAvatar})})]}):null}function zb(e){/* @__PURE__ */
190
+ return b(Pt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Eb,{...e})})}function Nb(e){/* @__PURE__ */
191
+ return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(Cb,{children:/* @__PURE__ */b(zb,{...e})})})}const Ab=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Nb,ChatWidgetInner:Eb,ChatWidgetWithProviders:zb},Symbol.toStringTag,{value:"Module"}));function Ib({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__ */
192
+ return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(zb,{...i})})},n)}function Tb({url:e,autoRotate:t,hasCustomCamera:n}){const r=f(null),o=f(null),i=f(null),s=f(0),l=f(0),c=f(0),{scene:u,camera:d}=_();return a(()=>{const t=new z;return t.register(e=>new C(e)),t.load(e,e=>{const t=e.userData?.vrm;if(t){r.current=t,t.scene.rotation.y=Math.PI;const e=(new E.Box3).setFromObject(t.scene).getSize(new E.Vector3);if(c.current=0,l.current=Math.PI,u.add(t.scene),!n){const t=.75*e.y,n=d.fov*(Math.PI/180),r=.55*e.y*.5/Math.tan(n/2)*1.3;d.position.set(0,t,r),d.lookAt(0,t,0)}t.lookAt&&(t.lookAt.target=d)}else{const t=e.scene;t.updateMatrixWorld(!0);const r=(new E.Box3).setFromObject(t),a=r.getCenter(new E.Vector3),s=r.getSize(new E.Vector3),p=new E.Group;if(t.position.sub(a),p.add(t),o.current=p,c.current=0,l.current=0,u.add(p),!n){const e=d.fov*(Math.PI/180),t=.3*s.y,n=.5*s.y/Math.tan(e/2)*1.2;d.position.set(0,t,n),d.lookAt(0,t,0)}if(e.animations.length>0){const n=new E.AnimationMixer(t);i.current=n,e.animations.forEach(e=>{n.clipAction(e).play()})}}},void 0,e=>{console.error("[Avatar3DPreview] Failed to load model:",e)}),()=>{r.current&&(u.remove(r.current.scene),r.current=null),o.current&&(u.remove(o.current),o.current=null),i.current&&(i.current.stopAllAction(),i.current=null)}},[e,u,d,t]),S((e,n)=>{const a=Math.min(n,.1);s.current+=1.2*a;const u=t?.5*a:0;if(o.current){i.current&&i.current.update(a);const e=o.current,n=.003*Math.sin(s.current);e.position.y=c.current+n,t&&(l.current-=u);const r=.02*Math.sin(.3*s.current);return void(e.rotation.y=l.current+r)}const d=r.current;if(d){const e=.003*Math.sin(s.current);if(d.scene.position.y=c.current+e,t&&(l.current-=u,d.scene.rotation.y=l.current),d.humanoid){const e=d.humanoid.getNormalizedBoneNode("spine");if(e){const t=.008*Math.sin(.4*s.current),n=.005*Math.cos(.25*s.current);e.rotation.z=E.MathUtils.lerp(e.rotation.z,t,2*a),e.rotation.x=E.MathUtils.lerp(e.rotation.x,n,2*a)}}d.update(a)}}),null}function Ob({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function Mb({url:e,className:t="",cameraPosition:n,targetPosition:r,autoRotate:o=!0}){return e?/* @__PURE__ */b("div",{className:`relative w-full h-full ${t}`,children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"w-full h-full flex items-center justify-center text-gray-400 text-xs",children:"Loading 3D Model..."}),children:/* @__PURE__ */y(k,{style:{width:"100%",height:"100%",background:"transparent"},gl:{alpha:!0,antialias:!0,preserveDrawingBuffer:!1},camera:{fov:30,near:.01,far:10},dpr:[1,2],children:[
193
+ /* @__PURE__ */b(Ob,{position:n,target:r}),
194
194
  /* @__PURE__ */b("ambientLight",{intensity:.6}),
195
195
  /* @__PURE__ */b("directionalLight",{position:[1,2,3],intensity:.8,color:"#ffffff"}),
196
196
  /* @__PURE__ */b("directionalLight",{position:[-1,1,-1],intensity:.3,color:"#b4c6e7"}),
197
197
  /* @__PURE__ */b("pointLight",{position:[0,.5,-.5],intensity:.5,distance:3}),
198
- /* @__PURE__ */b(xb,{url:e,autoRotate:o,hasCustomCamera:!(!n||!r)})]})})}):null}const Sb="https://api.botuyo.com";class Cb 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 Eb={"--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%"},zb=p(()=>Promise.resolve().then(()=>vb).then(e=>({default:e.ChatWidgetWithProviders})));class Nb{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||Sb},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=L.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(Eb).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(Eb).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||Sb,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(zb,t));this.root.render(n.createElement(Cb,null,n.createElement(M,{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"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const Ab=new Nb;window.BotUyoChat=Ab;export{_b as A,Nb as B,yb as C,K as L,wb as P,se as X,Et as a,db as b,$ as c,bb as d,M as e,pb as f,At as g,P as h,Ab as i,D as u};
199
- //# sourceMappingURL=standalone-DrDCLfVL.js.map
198
+ /* @__PURE__ */b(Tb,{url:e,autoRotate:o,hasCustomCamera:!(!n||!r)})]})})}):null}const Pb="https://api.botuyo.com";class Lb 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 Db={"--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%"},jb=p(()=>Promise.resolve().then(()=>Ab).then(e=>({default:e.ChatWidgetWithProviders})));class Fb{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||Pb},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=L.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(Db).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(Db).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||Pb,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(jb,t));this.root.render(n.createElement(Lb,null,n.createElement(M,{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 Rb=new Fb;window.BotUyoChat=Rb;export{Mb as A,Fb as B,Nb as C,K as L,Ib as P,se as X,Et as a,xb as b,$ as c,zb as d,M as e,kb as f,At as g,P as h,Rb as i,D as u};
199
+ //# sourceMappingURL=standalone-DOLAS_vS.js.map