@botuyo/chat-widget-standalone 1.0.89 → 1.0.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"ChatWidget.d.ts","sourceRoot":"","sources":["../../../src/chat-widget/ChatWidget.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAc9C,OAAO,iCAAiC,CAAA;AAKxC,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,kDAmRrD;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,2CAS7D;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,2CAQhD"}
1
+ {"version":3,"file":"ChatWidget.d.ts","sourceRoot":"","sources":["../../../src/chat-widget/ChatWidget.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAc9C,OAAO,iCAAiC,CAAA;AAKxC,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,kDAuRrD;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,2CAS7D;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,2CAQhD"}
@@ -1 +1 @@
1
- {"version":3,"file":"InputArea.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/InputArea.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAmB3C,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAA;IAChC,IAAI,EAAE,IAAI,CAAA;IACV,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,OAAO,CAAA;IACpB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,aAAa,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;IACxC,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,KAAK,IAAI,CAAA;IACzE,cAAc,CAAC,EAAE,CAAC,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAA;IAC5E,WAAW,CAAC,EAAE,MAAM,IAAI,CAAA;CACzB;AAED,wBAAgB,SAAS,CAAC,EACxB,WAAW,EACX,WAAqC,EACrC,YAAY,EACZ,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,cAAc,EACd,WAAW,GACZ,EAAE,cAAc,2CAifhB"}
1
+ {"version":3,"file":"InputArea.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/InputArea.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAmB3C,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAA;IAChC,IAAI,EAAE,IAAI,CAAA;IACV,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,OAAO,CAAA;IACpB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,aAAa,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;IACxC,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,KAAK,IAAI,CAAA;IACzE,cAAc,CAAC,EAAE,CAAC,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAA;IAC5E,WAAW,CAAC,EAAE,MAAM,IAAI,CAAA;CACzB;AAED,wBAAgB,SAAS,CAAC,EACxB,WAAW,EACX,WAAqC,EACrC,YAAY,EACZ,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,cAAc,EACd,WAAW,GACZ,EAAE,cAAc,2CAufhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"useFocusTrap.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/hooks/useFocusTrap.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,UAAU,mBAAmB;IAC3B,6BAA6B;IAC7B,OAAO,EAAE,OAAO,CAAA;IAChB,qDAAqD;IACrD,cAAc,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;IAC7C,oCAAoC;IACpC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAA;CACtB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,EAAE,mBAAmB,oDA+EtF"}
1
+ {"version":3,"file":"useFocusTrap.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/hooks/useFocusTrap.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,UAAU,mBAAmB;IAC3B,6BAA6B;IAC7B,OAAO,EAAE,OAAO,CAAA;IAChB,qDAAqD;IACrD,cAAc,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;IAC7C,oCAAoC;IACpC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAA;CACtB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,EAAE,mBAAmB,oDAuFtF"}
@@ -15,7 +15,7 @@ return y("div",{className:wt("flex items-center w-fit transition-all duration-50
15
15
  /* @__PURE__ */b(R,{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(R,{size:9}),e]},`${e}-${t}`))})]}):null}),Dl=p(()=>import("./AudioPlayer-BBhgXKGN.js").then(e=>({default:e.AudioPlayer}))),jl=p(()=>import("./Gallery-DIhvH6hq.js").then(e=>({default:e.Gallery}))),Fl=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:i,isFirst:a=!0,isLast:s=!0,index:l=0}){const{t:c}=I("extracted"),d="user"===e.sender,p="system"===e.type||"system"===e.sender,f=!d&&!p,m=_t({primaryColor:t}),g=function(){const e=o(Et);return e.enabled&&"none"!==e.messageEntry?{slide:"animate-message-slide",fade:"animate-message-fade",scale:"animate-message-scale",spring:"animate-message-spring"}[e.messageEntry]||"animate-message-spring":""}(),w=u(()=>{if(d)return null;if("text"===e.type){const t=e;if(t.emotion&&i?.[t.emotion])return i[t.emotion]}return n},[e,i,n,d]),x=({href:e,children:t})=>{if(!e)return null;const n=String(t).toLowerCase(),r=n.includes("reservar")||n.includes("ver")||n.includes("pagar"),o=e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps");let i=!1;try{i=new URL(e,window.location.origin).hostname===window.location.hostname}catch{}const a=i?t=>{t.preventDefault(),window.location.href=e}:void 0,s=i?void 0:"_blank",l=i?void 0:"noopener noreferrer";return o?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"block my-2 no-underline group",children:/* @__PURE__ */y("span",{className:"flex items-center gap-3 p-3 border rounded-xl shadow-sm group-hover:border-primary/30 transition-all",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))"},children:[
18
+ /* @__PURE__ */b(R,{size:9}),e]},`${e}-${t}`))})]}):null}),Dl=p(()=>import("./AudioPlayer-CqEMPcJU.js").then(e=>({default:e.AudioPlayer}))),jl=p(()=>import("./Gallery-isZAA7tT.js").then(e=>({default:e.Gallery}))),Fl=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:i,isFirst:a=!0,isLast:s=!0,index:l=0}){const{t:c}=I("extracted"),d="user"===e.sender,p="system"===e.type||"system"===e.sender,f=!d&&!p,m=_t({primaryColor:t}),g=function(){const e=o(Et);return e.enabled&&"none"!==e.messageEntry?{slide:"animate-message-slide",fade:"animate-message-fade",scale:"animate-message-scale",spring:"animate-message-spring"}[e.messageEntry]||"animate-message-spring":""}(),w=u(()=>{if(d)return null;if("text"===e.type){const t=e;if(t.emotion&&i?.[t.emotion])return i[t.emotion]}return n},[e,i,n,d]),x=({href:e,children:t})=>{if(!e)return null;const n=String(t).toLowerCase(),r=n.includes("reservar")||n.includes("ver")||n.includes("pagar"),o=e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps");let i=!1;try{i=new URL(e,window.location.origin).hostname===window.location.hostname}catch{}const a=i?t=>{t.preventDefault(),window.location.href=e}:void 0,s=i?void 0:"_blank",l=i?void 0:"noopener noreferrer";return o?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"block my-2 no-underline group",children:/* @__PURE__ */y("span",{className:"flex items-center gap-3 p-3 border rounded-xl shadow-sm group-hover:border-primary/30 transition-all",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))"},children:[
19
19
  /* @__PURE__ */b("span",{className:"flex-shrink-0 p-2 rounded-full",style:{backgroundColor:`${m}1a`,color:m},children:/* @__PURE__ */b(q,{size:16,strokeWidth:2.5})}),
20
20
  /* @__PURE__ */b("span",{className:"flex flex-col min-w-0 flex-1 text-[11px] font-bold text-foreground leading-tight uppercase tracking-tight",children:c("ver_ubicacion")}),
21
21
  /* @__PURE__ */b(F,{size:12,className:"text-muted-foreground/40 group-hover:text-primary"})]})}):r?/* @__PURE__ */y("a",{href:e,target:s,rel:l,onClick:a,className:"inline-flex items-center justify-center gap-2 px-4 py-2.5 mt-2 mx-1 text-[11px] font-black w-[calc(100%-0.5rem)] sm:w-auto rounded-xl shadow-md uppercase tracking-widest transition-transform active:scale-95 text-white",style:{backgroundColor:m},children:[t," ",
@@ -57,7 +57,7 @@ return y(n.Fragment,{children:[a&&/* @__PURE__ */b("div",{className:"flex justif
57
57
  /* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce [animation-delay:-0.15s]"}),
58
58
  /* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce"})]})}),
59
59
  /* @__PURE__ */b(Rl,{})]}),
60
- /* @__PURE__ */b("div",{ref:p,className:"h-6 shrink-0"})]})}):/* @__PURE__ */b("div",{className:"flex-1 bg-background"})},(e,t)=>{if(e.messages.length!==t.messages.length)return!1;if(e.isTyping!==t.isTyping)return!1;if(e.primaryColor!==t.primaryColor)return!1;if(e.botName!==t.botName)return!1;if(e.logoUrl!==t.logoUrl)return!1;const n=e.messages[e.messages.length-1],r=t.messages[t.messages.length-1];return n?.id===r?.id}),Vl={"image/jpeg":[255,216,255],"image/png":[137,80,78,71,13,10,26,10],"image/webp":[82,73,70,70],"image/gif":[71,73,70,56],"audio/mpeg":[255,251],"audio/wav":[82,73,70,70],"audio/webm":[26,69,223,163],"audio/ogg":[79,103,103,83]};async function ql(e,t={}){const{maxSizeMB:n=10,allowedExtensions:r,checkMagicBytes:o=!0}=t;if(!function(e,t=10){const n=1024*t*1024;return e.size<=n}(e,n))return{valid:!1,error:`El archivo es demasiado grande. Máximo ${n}MB`};if(r&&!function(e,t){const n=e.name.split(".").pop()?.toLowerCase();return!!n&&t.includes(n)}(e,r))return{valid:!1,error:`Extensión no permitida. Solo: ${r.join(", ")}`};if(o){const t=await async function(e){try{const t=Vl[e.type];if(!t)return!0;const n=await e.slice(0,12).arrayBuffer(),r=new Uint8Array(n);return t.every((e,t)=>r[t]===e)}catch(t){return console.error("File validation error:",t),!1}}(e);if(!t)return{valid:!1,error:"El archivo está corrupto o no es del tipo indicado"}}return{valid:!0}}const Wl=1e3,Hl={enableImages:!0,enableAudio:!0,enableFiles:!0,enableLocation:!0,allowedFileTypes:["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],maxFileSizeMB:10};function Zl({isConnected:e,placeholder:t="Escribe un mensaje...",primaryColor:n,mediaConfig:r,onSendMessage:o,onSendAttachment:a,onSendLocation:s,onVoiceCall:l}){const{t:c}=I(),[d,p]=i(""),[h,m]=i(!1),[g,w]=i(!1),[x,k]=i(0),[_,S]=i(null),[C,E]=i(!1),[z,N]=i(!1),O=f(null),T=f(null),A=f(null),M=f(null),P=f([]),L=f(null),D=_t({primaryColor:n}),j=u(()=>({...Hl,...r}),[r]),F=u(()=>j.enableImages||j.enableAudio||j.enableFiles||j.enableLocation,[j]),$=()=>{const t=d.trim();O.current&&(O.current.focus(),O.current.style.height="40px"),_?(a?.(_.file,_.type),S(null),p("")):t&&e&&(o(t),p(""))},U=async e=>{const t=e.target.files?.[0];if(!t)return;m(!1);const n=await ql(t,{maxSizeMB:j.maxFileSizeMB||10,allowedExtensions:j.allowedFileTypes||["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],checkMagicBytes:!0});if(n.valid)if(t.type.startsWith("image/")&&j.enableImages){E(!0);try{const{default:e}=await import("./browser-image-compression-CsxM8KJN.js"),n={maxSizeMB:.8,maxWidthOrHeight:1200,useWebWorker:!0},r=await e(t,n);S({type:"image",file:r,previewUrl:URL.createObjectURL(r)})}catch(r){Tt("Image compression failed:",r),S({type:"image",file:t,previewUrl:URL.createObjectURL(t)})}finally{E(!1)}}else S({type:"file",file:t,previewUrl:""});else alert(n.error||"Archivo no válido")},W=async e=>{if(M.current&&(e||(M.current.onstop=null),M.current.stop(),M.current.stream.getTracks().forEach(e=>e.stop())),L.current&&clearInterval(L.current),w(!1),k(0),e&&P.current.length>0){const e=new Blob(P.current,{type:"audio/webm"}),t=new File([e],`audio-${Date.now()}.webm`,{type:"audio/webm"}),n=await ql(t,{maxSizeMB:10});if(!n.valid)return Tt("Audio validation failed:",n.error),alert(n.error),void(P.current=[]);a?.(t,"audio"),P.current=[]}};/* @__PURE__ */
60
+ /* @__PURE__ */b("div",{ref:p,className:"h-6 shrink-0"})]})}):/* @__PURE__ */b("div",{className:"flex-1 bg-background"})},(e,t)=>{if(e.messages.length!==t.messages.length)return!1;if(e.isTyping!==t.isTyping)return!1;if(e.primaryColor!==t.primaryColor)return!1;if(e.botName!==t.botName)return!1;if(e.logoUrl!==t.logoUrl)return!1;const n=e.messages[e.messages.length-1],r=t.messages[t.messages.length-1];return n?.id===r?.id}),Vl={"image/jpeg":[255,216,255],"image/png":[137,80,78,71,13,10,26,10],"image/webp":[82,73,70,70],"image/gif":[71,73,70,56],"audio/mpeg":[255,251],"audio/wav":[82,73,70,70],"audio/webm":[26,69,223,163],"audio/ogg":[79,103,103,83]};async function ql(e,t={}){const{maxSizeMB:n=10,allowedExtensions:r,checkMagicBytes:o=!0}=t;if(!function(e,t=10){const n=1024*t*1024;return e.size<=n}(e,n))return{valid:!1,error:`El archivo es demasiado grande. Máximo ${n}MB`};if(r&&!function(e,t){const n=e.name.split(".").pop()?.toLowerCase();return!!n&&t.includes(n)}(e,r))return{valid:!1,error:`Extensión no permitida. Solo: ${r.join(", ")}`};if(o){const t=await async function(e){try{const t=Vl[e.type];if(!t)return!0;const n=await e.slice(0,12).arrayBuffer(),r=new Uint8Array(n);return t.every((e,t)=>r[t]===e)}catch(t){return console.error("File validation error:",t),!1}}(e);if(!t)return{valid:!1,error:"El archivo está corrupto o no es del tipo indicado"}}return{valid:!0}}const Wl=1e3,Hl={enableImages:!0,enableAudio:!0,enableFiles:!0,enableLocation:!0,allowedFileTypes:["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],maxFileSizeMB:10};function Zl({isConnected:e,placeholder:t="Escribe un mensaje...",primaryColor:n,mediaConfig:r,onSendMessage:o,onSendAttachment:a,onSendLocation:s,onVoiceCall:l}){const{t:c}=I(),[d,p]=i(""),[h,m]=i(!1),[g,w]=i(!1),[x,k]=i(0),[_,S]=i(null),[C,E]=i(!1),[z,N]=i(!1),O=f(null),T=f(null),A=f(null),M=f(null),P=f([]),L=f(null),D=_t({primaryColor:n}),j=u(()=>({...Hl,...r}),[r]),F=u(()=>j.enableImages||j.enableAudio||j.enableFiles||j.enableLocation,[j]),$=()=>{const t=d.trim();O.current&&(O.current.focus(),O.current.style.height="40px"),_?(a?.(_.file,_.type),S(null),p("")):t&&e&&(o(t),p("")),requestAnimationFrame(()=>{O.current?.focus()})},U=async e=>{const t=e.target.files?.[0];if(!t)return;m(!1);const n=await ql(t,{maxSizeMB:j.maxFileSizeMB||10,allowedExtensions:j.allowedFileTypes||["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],checkMagicBytes:!0});if(n.valid)if(t.type.startsWith("image/")&&j.enableImages){E(!0);try{const{default:e}=await import("./browser-image-compression-CsxM8KJN.js"),n={maxSizeMB:.8,maxWidthOrHeight:1200,useWebWorker:!0},r=await e(t,n);S({type:"image",file:r,previewUrl:URL.createObjectURL(r)})}catch(r){Tt("Image compression failed:",r),S({type:"image",file:t,previewUrl:URL.createObjectURL(t)})}finally{E(!1)}}else S({type:"file",file:t,previewUrl:""});else alert(n.error||"Archivo no válido")},W=async e=>{if(M.current&&(e||(M.current.onstop=null),M.current.stop(),M.current.stream.getTracks().forEach(e=>e.stop())),L.current&&clearInterval(L.current),w(!1),k(0),e&&P.current.length>0){const e=new Blob(P.current,{type:"audio/webm"}),t=new File([e],`audio-${Date.now()}.webm`,{type:"audio/webm"}),n=await ql(t,{maxSizeMB:10});if(!n.valid)return Tt("Audio validation failed:",n.error),alert(n.error),void(P.current=[]);a?.(t,"audio"),P.current=[]}};/* @__PURE__ */
61
61
  return y("div",{className:"relative",children:[(_||C)&&/* @__PURE__ */b("div",{className:"absolute bottom-full left-0 mb-2 p-2 rounded-2xl border shadow-soft-2xl animate-in slide-in-from-bottom-2 z-50",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))"},children:/* @__PURE__ */b("div",{className:"relative w-16 h-16",children:C?/* @__PURE__ */b("div",{className:"w-full h-full flex flex-col items-center justify-center bg-muted rounded-xl",children:/* @__PURE__ */b(V,{className:"animate-spin text-primary h-5 w-5"})}):/* @__PURE__ */y(v,"image"===_?.type?{children:[
62
62
  /* @__PURE__ */b("img",{src:_?.previewUrl,className:"w-full h-full object-cover rounded-xl border",alt:c("preview")}),
63
63
  /* @__PURE__ */b("button",{onClick:()=>S(null),className:"absolute -top-1.5 -right-1.5 bg-destructive text-white rounded-full p-1 shadow-md hover:scale-105",children:/* @__PURE__ */b(te,{size:10,strokeWidth:3})})]}:{children:[
@@ -117,7 +117,7 @@ return y("span",{style:{fontSize:"10px",padding:"2px 8px",borderRadius:"12px",ba
117
117
  /* @__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(U,{style:{width:"20px",height:"20px"}})})]}),I&&/* @__PURE__ */y("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 20px 20px"},children:[
118
118
  /* @__PURE__ */b("input",{type:"text",value:A,onChange:e=>M(e.target.value),onKeyDown:e=>"Enter"===e.key&&be(),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)"}}),
119
119
  /* @__PURE__ */b("button",{onClick:be,disabled:!A.trim(),style:{width:"40px",height:"40px",borderRadius:"50%",border:"none",cursor:A.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:A.trim()?n:"rgba(255,255,255,0.06)",color:A.trim()?"white":"rgba(255,255,255,0.2)",transition:"all 0.2s"},"aria-label":"Enviar texto",children:/* @__PURE__ */b(G,{style:{width:"16px",height:"16px"}})})]}),
120
- /* @__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 bc({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,onAddVoiceMessage:_,avatar3dUrl:S,theme:C,suggestedQuestions:E}){const[z,N]=i(!1),[O,T]=i(!1),[A,M]=i(!1),{t:P}=I(),L=Yl(),D=_t({cssVariables:C?.cssVariables}),j=function({isOpen:e,height:t,bottom:n}){const r=Yl(),[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||Gl)||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||Gl})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||Gl})}}},[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}),F=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null);return a(()=>{if(!e)return;o.current=document.activeElement;const i=t?.current,a=r.current;if(!a)return;const s=setTimeout(()=>{const e=a.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():a.focus()},100),l=e=>{if(a)if("Escape"!==e.key){if("Tab"===e.key){const t=a.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===t.length)return;const n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus())}}else n?.()};return document.addEventListener("keydown",l),()=>{clearTimeout(s),document.removeEventListener("keydown",l);const e=i||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,n,t]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return L&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,L]),!e)return null;const R="bottom-left"===C?.position;/* @__PURE__ */
120
+ /* @__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 bc({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,onAddVoiceMessage:_,avatar3dUrl:S,theme:C,suggestedQuestions:E}){const[z,N]=i(!1),[O,T]=i(!1),[A,M]=i(!1),{t:P}=I(),L=Yl(),D=_t({cssVariables:C?.cssVariables}),j=function({isOpen:e,height:t,bottom:n}){const r=Yl(),[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||Gl)||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||Gl})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||Gl})}}},[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}),F=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.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 L&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,L]),!e)return null;const R="bottom-left"===C?.position;/* @__PURE__ */
121
121
  return y(v,{children:[
122
122
  /* @__PURE__ */b("div",{id:"chat-dialog-description",className:"sr-only",children:P("accessibility.dialogDescription",{botName:o??"BotUyo"})}),
123
123
  /* @__PURE__ */y("div",{ref:F,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:wt("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!L&&["fixed",R?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],L&&["fixed inset-0 w-full"]),style:{...j,...L?{}:{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:[
@@ -169,9 +169,9 @@ return mh(Bf,e)}const Vf=/* @__PURE__ */Jc("ZodAny",(e,t)=>{ap.init(e,t),mf.init
169
169
  return bh(qf)}const Hf=/* @__PURE__ */Jc("ZodNever",(e,t)=>{lp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Zf=/* @__PURE__ */Jc("ZodArray",(e,t)=>{up.init(e,t),mf.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=qh(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Ch(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Ch(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Sh(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Eh(t,n)),e.unwrap=()=>e.element});function Jf(e,t){/* @__PURE__ */
170
170
  return Rh(Zf,e,t)}const Kf=/* @__PURE__ */Jc("ZodObject",(e,t)=>{mp.init(e,t),mf.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]=qh(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=qh(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),iu(e,"shape",()=>t.shape),e.keyof=()=>Xf(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Wf()}),e.loose=()=>e.clone({...e._zod.def,catchall:Wf()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */yh(Hf,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!pu(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=su(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return au(this,"shape",n),n}});return gu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!pu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=su(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return au(this,"shape",n),n}});return gu(e,n)}(e,t),e.merge=t=>function(e,t){const n=su(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return au(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return gu(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 gu(e,su(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 au(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=su(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 au(this,"shape",r),r},checks:[]});return gu(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=su(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 au(this,"shape",o),o},checks:[]});return gu(t,o)}(tm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=su(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 au(this,"shape",o),o}});return gu(t,r)}(lm,e,t[0])}),Yf=/* @__PURE__ */Jc("ZodUnion",(e,t)=>{bp.init(e,t),mf.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)=>qh(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}),Gf=/* @__PURE__ */Jc("ZodIntersection",(e,t)=>{yp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=qh(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=qh(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)}),Qf=/* @__PURE__ */Jc("ZodEnum",(e,t)=>{xp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Xc(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 Qf({...t,checks:[],...bu(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 Qf({...t,checks:[],...bu(r),entries:o})}});function Xf(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Qf({type:"enum",entries:n,...bu(t)})}const em=/* @__PURE__ */Jc("ZodTransform",(e,t)=>{kp.init(e,t),mf.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 Yc(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Su(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(Su(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),tm=/* @__PURE__ */Jc("ZodOptional",(e,t)=>{Sp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yh(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function nm(e){return new tm({type:"optional",innerType:e})}const rm=/* @__PURE__ */Jc("ZodExactOptional",(e,t)=>{Cp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yh(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),om=/* @__PURE__ */Jc("ZodNullable",(e,t)=>{Ep.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=qh(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 im(e){return new om({type:"nullable",innerType:e})}const am=/* @__PURE__ */Jc("ZodDefault",(e,t)=>{zp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;qh(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__ */Jc("ZodPrefault",(e,t)=>{Op.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;qh(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__ */Jc("ZodNonOptional",(e,t)=>{Ip.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;qh(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),cm=/* @__PURE__ */Jc("ZodCatch",(e,t)=>{Ap.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;qh(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}),um=/* @__PURE__ */Jc("ZodPipe",(e,t)=>{Mp.init(e,t),mf.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;qh(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function dm(e,t){return new um({type:"pipe",in:e,out:t})}const pm=/* @__PURE__ */Jc("ZodReadonly",(e,t)=>{Lp.init(e,t),mf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;qh(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),hm=/* @__PURE__ */Jc("ZodCustom",(e,t)=>{jp.init(e,t),mf.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)}),fm=/* @__PURE__ */Object.create(null);fm.open="0",fm.close="1",fm.ping="2",fm.pong="3",fm.message="4",fm.upgrade="5",fm.noop="6";const mm=/* @__PURE__ */Object.create(null);Object.keys(fm).forEach(e=>{mm[fm[e]]=e});const gm={type:"error",data:"parser error"},bm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),ym="function"==typeof ArrayBuffer,vm=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,wm=({type:e,data:t},n,r)=>bm&&t instanceof Blob?n?r(t):xm(t,r):ym&&(t instanceof ArrayBuffer||vm(t))?n?r(t):xm(new Blob([t]),r):r(fm[e]+(t||"")),xm=(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 _m;const Sm="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let sb=0;sb<64;sb++)Sm["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(sb)]=sb;const Cm="function"==typeof ArrayBuffer,Em=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Nm(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:zm(e.substring(1),t)}:mm[n]?e.length>1?{type:mm[n],data:e.substring(1)}:{type:mm[n]}:gm},zm=(e,t)=>{if(Cm){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=Sm[e.charCodeAt(t)],r=Sm[e.charCodeAt(t+1)],o=Sm[e.charCodeAt(t+2)],i=Sm[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 Nm(n,t)}return{base64:!0,data:e}},Nm=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Om=String.fromCharCode(30);let Im;function Tm(e){return e.reduce((e,t)=>e+t.length,0)}function Am(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 Mm(e){if(e)return function(e){for(var t in Mm.prototype)e[t]=Mm.prototype[t];return e}(e)}Mm.prototype.on=Mm.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Mm.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},Mm.prototype.off=Mm.prototype.removeListener=Mm.prototype.removeAllListeners=Mm.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},Mm.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},Mm.prototype.emitReserved=Mm.prototype.emit,Mm.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Mm.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Pm="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Lm="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Dm(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const jm=Lm.setTimeout,Fm=Lm.clearTimeout;function Rm(e,t){t.useNativeTimers?(e.setTimeoutFn=jm.bind(Lm),e.clearTimeoutFn=Fm.bind(Lm)):(e.setTimeoutFn=Lm.setTimeout.bind(Lm),e.clearTimeoutFn=Lm.clearTimeout.bind(Lm))}function $m(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 Bm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Um extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Vm extends Mm{constructor(e){super(),this.writable=!1,Rm(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 Um(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=Em(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 qm extends Vm{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(Om),r=[];for(let o=0;o<n.length;o++){const e=Em(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)=>{wm(e,!1,e=>{r[i]=e,++o===n&&t(r.join(Om))})})})(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]=Bm()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Wm=!1;try{Wm="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(ab){}const Hm=Wm;function Zm(){}class Jm extends qm{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 Km extends Mm{constructor(e,t,n){super(),this.createRequest=e,Rm(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=Dm(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=Km.requestsCount++,Km.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=Zm,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Km.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 Ym(){for(let e in Km.requests)Km.requests.hasOwnProperty(e)&&Km.requests[e].abort()}Km.requestsCount=0,Km.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Ym):"function"==typeof addEventListener&&addEventListener("onpagehide"in Lm?"pagehide":"unload",Ym,!1));const Gm=function(){const e=Qm({xdomain:!1});return e&&null!==e.responseType}();function Qm(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Hm))return new XMLHttpRequest}catch(n){}if(!t)try{return new(Lm[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Xm="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class eg extends Vm{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Xm?{}:Dm(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(ab){return this.emitReserved("error",ab)}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;wm(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&Pm(()=>{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]=Bm()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const tg=Lm.WebSocket||Lm.MozWebSocket,ng={websocket:class extends eg{createSocket(e,t,n){return Xm?new tg(e,t,n):t?new tg(e,t):new tg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Vm{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(ab){return this.emitReserved("error",ab)}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){Im||(Im=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(Tm(n)<1)break;const e=Am(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(Tm(n)<2)break;const e=Am(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(Tm(n)<8)break;const e=Am(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(gm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(Tm(n)<o)break;const e=Am(n,o);s.enqueue(Em(i?e:Im.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(gm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){bm&&e.data instanceof Blob?e.data.arrayBuffer().then(km).then(t):ym&&(e.data instanceof ArrayBuffer||vm(e.data))?t(km(e.data)):wm(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&&Pm(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Jm{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Gm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Km(Qm,this.uri(),e)}}},rg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,og=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ig(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=rg.exec(e||""),i={},a=14;for(;a--;)i[og[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 ag="function"==typeof addEventListener&&"function"==typeof removeEventListener,sg=[];ag&&addEventListener("offline",()=>{sg.forEach(e=>e())},!1);class lg extends Mm{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=ig(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=ig(t.host).host);Rm(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)),ag&&(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&&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+=$m(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,Pm(()=>{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(),ag&&(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}}}lg.protocol=4;class cg 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 ug=class extends cg{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=>ng[e]).filter(e=>!!e)),super(e,n)}};const dg="function"==typeof ArrayBuffer,pg=Object.prototype.toString,hg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===pg.call(Blob),fg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===pg.call(File);function mg(e){return dg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||hg&&e instanceof Blob||fg&&e instanceof File}function gg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(gg(e[t]))return!0;return!1}if(mg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return gg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&gg(e[n]))return!0;return!1}function bg(e){const t=[],n=e.data,r=e;return r.data=yg(n,t),r.attachments=t.length,{packet:r,buffers:t}}function yg(e,t){if(!e)return e;if(mg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=yg(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=yg(e[r],t));return n}return e}function vg(e,t){return e.data=wg(e.data,t),delete e.attachments,e}function wg(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]=wg(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=wg(e[n],t));return e}const xg=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var kg,_g;(_g=kg||(kg={}))[_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 Sg extends Mm{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 Cg(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!mg(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(!Eg(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(!Sg.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 zg(t);case kg.DISCONNECT:return void 0===t;case kg.CONNECT_ERROR:return"string"==typeof t||zg(t);case kg.EVENT:case kg.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===xg.indexOf(t[0]));case kg.ACK:case kg.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Cg{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=vg(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Eg=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function zg(e){return"[object Object]"===Object.prototype.toString.call(e)}const Ng=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:Sg,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==kg.EVENT&&e.type!==kg.ACK||!gg(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=bg(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return kg}},Symbol.toStringTag,{value:"Module"}));function Og(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Ig=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Tg extends Mm{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=[Og(e,"open",this.onopen.bind(this)),Og(e,"packet",this.onpacket.bind(this)),Og(e,"error",this.onerror.bind(this)),Og(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(Ig.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 Ag(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}Ag.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)},Ag.prototype.reset=function(){this.attempts=0},Ag.prototype.setMin=function(e){this.ms=e},Ag.prototype.setMax=function(e){this.max=e},Ag.prototype.setJitter=function(e){this.jitter=e};class Mg extends Mm{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,Rm(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 Ag({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||Ng;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 ug(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Og(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Og(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(Og(e,"ping",this.onping.bind(this)),Og(e,"data",this.ondata.bind(this)),Og(e,"error",this.onerror.bind(this)),Og(e,"close",this.onclose.bind(this)),Og(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){Pm(()=>{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 Tg(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 Pg={};function Lg(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=ig(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=Pg[o]&&i in Pg[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new Mg(r,t):(Pg[o]||(Pg[o]=new Mg(r,t)),s=Pg[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(Lg,{Manager:Mg,Socket:Tg,io:Lg,connect:Lg});const Dg="chat_device_id";function jg(){return"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 Fg=function(){const e={type:"object",shape:{id:yf().optional(),type:Xf(["text","image","audio","location","system"]).default("text"),content:yf().optional(),imageUrl:yf().url().optional(),audioUrl:yf().optional(),latitude:$f().optional(),longitude:$f().optional(),timestamp:yf().optional(),sender:Xf(["bot","user","system"]).optional(),emotion:/* @__PURE__ */gh(Vf).optional(),sources:Jf(yf()).optional()}??{},...bu(void 0)};return new Kf(e)}();class Rg{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),It("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?At():(this.isDisabled=!0,this.queue=[],At(t.status))}catch(t){this.isDisabled=!0,this.queue=[],At()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}let $g=null,Bg=null;function Ug(e){$g=e}function Vg(e){Bg=e}const qg=r(null);function Wg({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)},[r]),p=s(()=>{l(!1),r?.(!1)},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t})},[r]),f=s(e=>{$g?($g(e),At(0)):It("sendMessage called but no handler registered")},[]),m=s(()=>{Bg?(Bg(),At()):It("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__ */
171
171
  return y(qg.Provider,{value:g,children:[e,
172
- /* @__PURE__ */b(Qg,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:v})]})}function Hg(){const e=o(qg);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Zg=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Jg(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:_}=I(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Rg(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||Pt,h=l||Lt;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 It("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Mt("Notification permission:",e),"granted"===e}catch(e){return Tt("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){Tt("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=>{At(0)})}catch(n){Tt("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(Zc,Hc),[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 Wc.has(n)||Wc.set(n,new qc(e,t)),Wc.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){It("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){Tt("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){Tt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){Tt("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:[]})},[]);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:_}}}(t,o),O=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),T=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(Dg);if(e)return e;const t=jg();return localStorage.setItem(Dg,t),t}catch{return It("localStorage not available, using session-only device ID"),jg()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Fg.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=Lg(`${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){Tt("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 At(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){At()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e)),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),d.current=e},[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}),Tt("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(()=>Kl(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(()=>O?{...l||{},seo:{...O||{}}}:l,[l,O]),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,onHistoryLoaded:s(e=>{const t=new Set(z.messages.map(e=>e.id)),n=e.filter(e=>!t.has(e.id));n.length>0&&(0===z.messages.length?N.setMessages(e):n.forEach(e=>N.addMessage(e)))},[z.messages,N])}),A=s(()=>{At(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),At()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),At())},[z.isOpen,N,y,S]),M=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"),T.sendMessage(e,"text")},[N,T,E,S,_]),P=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 Zg(e);T.sendMessage(r,t)},[N,T]),L=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),T.sendMessage(JSON.stringify(e),"location")},[N,T]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&M(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,M]),a(()=>(Ug(M),()=>Ug(null)),[M]);const D=s(()=>{N.clearMessages(),Mt("Chat history cleared")},[N]);a(()=>(Vg(D),()=>Vg(null)),[D]);const j=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:j,isConnected:T.isConnected,getSocket:T.getSocket,handleToggle:A,handleSendText:M,handleSendAttachment:P,handleSendLocation:L}}function Kg({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=O.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),At(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Yg(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}=e,w=f(null),x=Yl(),k=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}(w),[_,S]=i(),{mergedTheme:C,mergedStyles:E,getContainerStyle:z}=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={...xt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...vc,...e?.bubbleStyles?.radius},bot:{...wc,...e?.bubbleStyles?.bot},user:{...xc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,_);a(()=>{C.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.')},[C.isHidden]);const{state:N,actions:O,unreadCount:I,currentBotEmotion:T,isConnected:A,handleToggle:M,handleSendText:P,handleSendAttachment:L,handleSendLocation:D,getSocket:j}=Jg({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:S}),F=s(e=>{O.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:e.sender,timestamp:e.timestamp||/* @__PURE__ */new Date,content:e.content})},[O]),R=u(()=>{const e={...d||{}},t=_;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,_]),$=s(e=>{e.stopPropagation()},[]),B=z(N.isOpen,x,c?.position),U=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(!C.cssVariables)return e;let t={...C.cssVariables};if(k){const e=_?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...kt,...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},[C.cssVariables,k,_,c?.darkCssVariables]);return C.isHidden?null:_?/* @__PURE__ */y("div",{ref:w,id:"botuyo-chat-widget-root",className:wt("botuyo-chat-widget flex flex-col",!x&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...B,...U,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:[
173
- /* @__PURE__ */b("div",{className:wt("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",x?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",N.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:N.isOpen?"auto":"none"},onMouseDown:$,onTouchStart:$,children:/* @__PURE__ */b(yc,{children:/* @__PURE__ */b(bc,{isOpen:N.isOpen,isConnected:A,isTyping:N.isTyping,messages:N.messages,onClose:()=>O.closeWindow(),onSendMessage:P,onSendAttachment:L,onSendLocation:D,botName:C.botName,logoUrl:C.logoUrl,welcomeMessage:C.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||_?.inputPlaceholder,position:c?.position,bubbleStyles:E,avatars:c?.avatars||_?.avatars||_?.avatarAnimations||{},mediaConfig:R,theme:C,avatar3dUrl:c?.avatar3dUrl,getSocket:j,onAddVoiceMessage:F,suggestedQuestions:_?.suggestedQuestions})})}),
174
- /* @__PURE__ */b("div",{className:wt(N.isOpen?"hidden":"block",!x&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:$,onTouchStart:$,children:/* @__PURE__ */b(jt,{isOpen:N.isOpen,onClick:M,unreadCount:I,position:c?.position||"bottom-right",primaryColor:_t(C),logoUrl:C.logoUrl,starterPrompt:c?.starterPrompt||_?.starterPrompt,avatars:c?.avatars||_?.avatars||_?.avatarAnimations||{},emotion:T,styles:E,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??_?.avatarScale,showPromptAvatar:c?.showPromptAvatar??_?.showPromptAvatar})})]}):null}function Gg(e){/* @__PURE__ */
172
+ /* @__PURE__ */b(Qg,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:v})]})}function Hg(){const e=o(qg);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Zg=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Jg(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:_}=I(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Rg(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||Pt,h=l||Lt;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 It("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Mt("Notification permission:",e),"granted"===e}catch(e){return Tt("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){Tt("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=>{At(0)})}catch(n){Tt("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(Zc,Hc),[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 Wc.has(n)||Wc.set(n,new qc(e,t)),Wc.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){It("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){Tt("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){Tt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){Tt("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:[]})},[]);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:_}}}(t,o),O=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),T=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(Dg);if(e)return e;const t=jg();return localStorage.setItem(Dg,t),t}catch{return It("localStorage not available, using session-only device ID"),jg()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Fg.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=Lg(`${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){Tt("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 At(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){At()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e)),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),d.current=e},[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}),Tt("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(()=>Kl(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(()=>O?{...l||{},seo:{...O||{}}}:l,[l,O]),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,onHistoryLoaded:s(e=>{const t=new Set(z.messages.map(e=>e.id)),n=e.filter(e=>!t.has(e.id));n.length>0&&(0===z.messages.length?N.setMessages(e):n.forEach(e=>N.addMessage(e)))},[z.messages,N])}),A=s(()=>{At(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),At()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),At())},[z.isOpen,N,y,S]),M=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"),T.sendMessage(e,"text")},[N,T,E,S,_]),P=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 Zg(e);T.sendMessage(r,t)},[N,T]),L=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),T.sendMessage(JSON.stringify(e),"location")},[N,T]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&M(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,M]),a(()=>(Ug(M),()=>Ug(null)),[M]);const D=s(()=>{N.clearMessages(),Mt("Chat history cleared")},[N]);a(()=>(Vg(D),()=>Vg(null)),[D]);const j=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:j,isConnected:T.isConnected,getSocket:T.getSocket,handleToggle:A,handleSendText:M,handleSendAttachment:P,handleSendLocation:L}}function Kg({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=O.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),At(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Yg(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}=e,w=f(null),x=Yl(),k=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}(w),[_,S]=i(),{mergedTheme:C,mergedStyles:E,getContainerStyle:z}=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={...xt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...vc,...e?.bubbleStyles?.radius},bot:{...wc,...e?.bubbleStyles?.bot},user:{...xc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,_);a(()=>{C.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.')},[C.isHidden]);const{state:N,actions:O,unreadCount:I,currentBotEmotion:T,isConnected:A,handleToggle:M,handleSendText:P,handleSendAttachment:L,handleSendLocation:D,getSocket:j}=Jg({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:S}),F=s(e=>{O.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:e.sender,timestamp:e.timestamp||/* @__PURE__ */new Date,content:e.content})},[O]),R=u(()=>{const e={...d||{}},t=_;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,_]),$=s(()=>{O.closeWindow()},[O]),B=s(e=>{e.stopPropagation()},[]),U=z(N.isOpen,x,c?.position),V=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(!C.cssVariables)return e;let t={...C.cssVariables};if(k){const e=_?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...kt,...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},[C.cssVariables,k,_,c?.darkCssVariables]);return C.isHidden?null:_?/* @__PURE__ */y("div",{ref:w,id:"botuyo-chat-widget-root",className:wt("botuyo-chat-widget flex flex-col",!x&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...U,...V,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:[
173
+ /* @__PURE__ */b("div",{className:wt("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",x?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",N.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:N.isOpen?"auto":"none"},onMouseDown:B,onTouchStart:B,children:/* @__PURE__ */b(yc,{children:/* @__PURE__ */b(bc,{isOpen:N.isOpen,isConnected:A,isTyping:N.isTyping,messages:N.messages,onClose:$,onSendMessage:P,onSendAttachment:L,onSendLocation:D,botName:C.botName,logoUrl:C.logoUrl,welcomeMessage:C.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||_?.inputPlaceholder,position:c?.position,bubbleStyles:E,avatars:c?.avatars||_?.avatars||_?.avatarAnimations||{},mediaConfig:R,theme:C,avatar3dUrl:c?.avatar3dUrl,getSocket:j,onAddVoiceMessage:F,suggestedQuestions:_?.suggestedQuestions})})}),
174
+ /* @__PURE__ */b("div",{className:wt(N.isOpen?"hidden":"block",!x&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:B,onTouchStart:B,children:/* @__PURE__ */b(jt,{isOpen:N.isOpen,onClick:M,unreadCount:I,position:c?.position||"bottom-right",primaryColor:_t(C),logoUrl:C.logoUrl,starterPrompt:c?.starterPrompt||_?.starterPrompt,avatars:c?.avatars||_?.avatars||_?.avatarAnimations||{},emotion:T,styles:E,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??_?.avatarScale,showPromptAvatar:c?.showPromptAvatar??_?.showPromptAvatar})})]}):null}function Gg(e){/* @__PURE__ */
175
175
  return b(Nt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Yg,{...e})})}function Qg(e){/* @__PURE__ */
176
176
  return b(z,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(Kg,{children:/* @__PURE__ */b(Gg,{...e})})})}const Xg=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Qg,ChatWidgetInner:Yg,ChatWidgetWithProviders:Gg},Symbol.toStringTag,{value:"Module"})),eb="https://api.botuyo.com";class tb 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 nb={"--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%"},rb=p(()=>Promise.resolve().then(()=>Xg).then(e=>({default:e.ChatWidgetWithProviders})));class ob{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||eb},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=O.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(nb).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(nb).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||eb,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(rb,t));this.root.render(n.createElement(tb,null,n.createElement(z,{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 ib=new ob;window.BotUyoChat=ib;export{ob as B,Qg as C,V as L,te as X,wt as a,Wg as b,P as c,Gg as d,z as e,Hg as f,_t as g,N as h,ib as i,I as u};
177
- //# sourceMappingURL=standalone-iuUHOprG.js.map
177
+ //# sourceMappingURL=standalone-Qr-pn16V.js.map