@botuyo/chat-widget-standalone 1.0.39 → 1.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/botuyo-chat.es.js +2 -2
- package/dist/botuyo-chat.es.js.map +1 -1
- package/dist/botuyo-chat.umd.js +1 -1
- package/dist/botuyo-chat.umd.js.map +1 -1
- package/dist/src/chat-widget/ChatWidget.d.ts.map +1 -1
- package/dist/stats-umd.html +1 -1
- package/dist/stats.html +1 -1
- package/package.json +1 -1
package/dist/botuyo-chat.es.js
CHANGED
|
@@ -30,8 +30,8 @@ return Fo(cn,t)}const ln=/* @__PURE__ */ft("ZodNumberFormat",(t,e)=>{Or.init(t,e
|
|
|
30
30
|
return Do(ln,t)}const pn=/* @__PURE__ */ft("ZodAny",(t,e)=>{Ir.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(t,e,r)=>{}}),hn=/* @__PURE__ */ft("ZodUnknown",(t,e)=>{$r.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(t,e,r)=>{}});function gn(){/* @__PURE__ */
|
|
31
31
|
return Uo(hn)}const mn=/* @__PURE__ */ft("ZodNever",(t,e)=>{Cr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e,r)=>{r.not={}})(0,0,e)}),fn=/* @__PURE__ */ft("ZodArray",(t,e)=>{Tr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=r,n=t._zod.def,{minimum:i,maximum:s}=t._zod.bag;"number"==typeof i&&(a.minItems=i),"number"==typeof s&&(a.maxItems=s),a.type="array",a.items=ha(n.element,e,{...o,path:[...o.path,"items"]})})(t,e,r,o),t.element=e.element,t.min=(e,r)=>t.check(/* @__PURE__ */Go(e,r)),t.nonempty=e=>t.check(/* @__PURE__ */Go(1,e)),t.max=(e,r)=>t.check(/* @__PURE__ */qo(e,r)),t.length=(e,r)=>t.check(/* @__PURE__ */Ko(e,r)),t.unwrap=()=>t.element}),wn=/* @__PURE__ */ft("ZodObject",(t,e)=>{Fr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=r,n=t._zod.def;a.type="object",a.properties={};const i=n.shape;for(const d in i)a.properties[d]=ha(i[d],e,{...o,path:[...o.path,"properties",d]});const s=new Set(Object.keys(i)),c=new Set([...s].filter(t=>{const r=n.shape[t]._zod;return"input"===e.io?void 0===r.optin:void 0===r.optout}));c.size>0&&(a.required=Array.from(c)),"never"===n.catchall?._zod.def.type?a.additionalProperties=!1:n.catchall?n.catchall&&(a.additionalProperties=ha(n.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):"output"===e.io&&(a.additionalProperties=!1)})(t,e,r,o),Ot(t,"shape",()=>e.shape),t.keyof=()=>xn(Object.keys(t._zod.def.shape)),t.catchall=e=>t.clone({...t._zod.def,catchall:e}),t.passthrough=()=>t.clone({...t._zod.def,catchall:gn()}),t.loose=()=>t.clone({...t._zod.def,catchall:gn()}),t.strict=()=>t.clone({...t._zod.def,catchall:/* @__PURE__ */Lo(mn,void 0)}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=e=>function(t,e){if(!At(e))throw new Error("Invalid input to extend: expected a plain object");const r=t._zod.def.checks;if(r&&r.length>0){const r=t._zod.def.shape;for(const t in e)if(void 0!==Object.getOwnPropertyDescriptor(r,t))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=$t(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return It(this,"shape",r),r}});return Dt(t,o)}(t,e),t.safeExtend=e=>function(t,e){if(!At(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=$t(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return It(this,"shape",r),r}});return Dt(t,r)}(t,e),t.merge=e=>function(t,e){const r=$t(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return It(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Dt(t,r)}(t,e),t.pick=e=>function(t,e){const r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Dt(t,$t(t._zod.def,{get shape(){const t={};for(const o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(t[o]=r.shape[o])}return It(this,"shape",t),t},checks:[]}))}(t,e),t.omit=e=>function(t,e){const r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=$t(t._zod.def,{get shape(){const o={...t._zod.def.shape};for(const t in e){if(!(t in r.shape))throw new Error(`Unrecognized key: "${t}"`);e[t]&&delete o[t]}return It(this,"shape",o),o},checks:[]});return Dt(t,a)}(t,e),t.partial=(...e)=>function(t,e,r){const o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=$t(e._zod.def,{get shape(){const o=e._zod.def.shape,a={...o};if(r)for(const e in r){if(!(e in o))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(a[e]=t?new t({type:"optional",innerType:o[e]}):o[e])}else for(const e in o)a[e]=t?new t({type:"optional",innerType:o[e]}):o[e];return It(this,"shape",a),a},checks:[]});return Dt(e,a)}(_n,t,e[0]),t.required=(...e)=>function(t,e,r){const o=$t(e._zod.def,{get shape(){const o=e._zod.def.shape,a={...o};if(r)for(const e in r){if(!(e in a))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(a[e]=new t({type:"nonoptional",innerType:o[e]}))}else for(const e in o)a[e]=new t({type:"nonoptional",innerType:o[e]});return It(this,"shape",a),a}});return Dt(e,o)}(Cn,t,e[0])}),bn=/* @__PURE__ */ft("ZodUnion",(t,e)=>{Zr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def,n=!1===a.inclusive,i=a.options.map((t,r)=>ha(t,e,{...o,path:[...o.path,n?"oneOf":"anyOf",r]}));n?r.oneOf=i:r.anyOf=i})(t,e,r,o),t.options=e.options}),vn=/* @__PURE__ */ft("ZodIntersection",(t,e)=>{Ur.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def,n=ha(a.left,e,{...o,path:[...o.path,"allOf",0]}),i=ha(a.right,e,{...o,path:[...o.path,"allOf",1]}),s=t=>"allOf"in t&&1===Object.keys(t).length,c=[...s(n)?n.allOf:[n],...s(i)?i.allOf:[i]];r.allOf=c})(t,e,r,o)}),yn=/* @__PURE__ */ft("ZodEnum",(t,e)=>{Wr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r)=>{const o=xt(t._zod.def.entries);o.every(t=>"number"==typeof t)&&(r.type="number"),o.every(t=>"string"==typeof t)&&(r.type="string"),r.enum=o})(t,0,r),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(t,o)=>{const a={};for(const n of t){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);a[n]=e.entries[n]}return new yn({...e,checks:[],...Zt(o),entries:a})},t.exclude=(t,o)=>{const a={...e.entries};for(const e of t){if(!r.has(e))throw new Error(`Key ${e} not found in enum`);delete a[e]}return new yn({...e,checks:[],...Zt(o),entries:a})}});function xn(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t;return new yn({type:"enum",entries:r,...Zt(e)})}const kn=/* @__PURE__ */ft("ZodTransform",(t,e)=>{Br.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e)=>{if("throw"===e.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,t),t._zod.parse=(r,o)=>{if("backward"===o.direction)throw new bt(t.constructor.name);r.addIssue=o=>{if("string"==typeof o)r.issues.push(Vt(o,r.value,e));else{const e=o;e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=r.value),e.inst??(e.inst=t),r.issues.push(Vt(e))}};const a=e.transform(r.value,r);return a instanceof Promise?a.then(t=>(r.value=t,r)):(r.value=a,r)}}),_n=/* @__PURE__ */ft("ZodOptional",(t,e)=>{Vr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>va(t,e,0,o),t.unwrap=()=>t._zod.def.innerType});function zn(t){return new _n({type:"optional",innerType:t})}const En=/* @__PURE__ */ft("ZodExactOptional",(t,e)=>{qr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>va(t,e,0,o),t.unwrap=()=>t._zod.def.innerType}),Sn=/* @__PURE__ */ft("ZodNullable",(t,e)=>{Gr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def,n=ha(a.innerType,e,o),i=e.seen.get(t);"openapi-3.0"===e.target?(i.ref=a.innerType,r.nullable=!0):r.anyOf=[n,{type:"null"}]})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType});function On(t){return new Sn({type:"nullable",innerType:t})}const In=/* @__PURE__ */ft("ZodDefault",(t,e)=>{Kr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def;ha(a.innerType,e,o),e.seen.get(t).ref=a.innerType,r.default=JSON.parse(JSON.stringify(a.defaultValue))})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),$n=/* @__PURE__ */ft("ZodPrefault",(t,e)=>{Yr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def;ha(a.innerType,e,o),e.seen.get(t).ref=a.innerType,"input"===e.io&&(r._prefault=JSON.parse(JSON.stringify(a.defaultValue)))})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType}),Cn=/* @__PURE__ */ft("ZodNonOptional",(t,e)=>{Xr.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def;ha(a.innerType,e,o),e.seen.get(t).ref=a.innerType})(t,e,0,o),t.unwrap=()=>t._zod.def.innerType}),Nn=/* @__PURE__ */ft("ZodCatch",(t,e)=>{to.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def;let n;ha(a.innerType,e,o),e.seen.get(t).ref=a.innerType;try{n=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=n})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),Tn=/* @__PURE__ */ft("ZodPipe",(t,e)=>{eo.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def,n="input"===e.io?"transform"===a.in._zod.def.type?a.out:a.in:a.out;ha(n,e,o),e.seen.get(t).ref=n})(t,e,0,o),t.in=e.in,t.out=e.out});function Mn(t,e){return new Tn({type:"pipe",in:t,out:e})}const An=/* @__PURE__ */ft("ZodReadonly",(t,e)=>{oo.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const a=t._zod.def;ha(a.innerType,e,o),e.seen.get(t).ref=a.innerType,r.readOnly=!0})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType}),jn=/* @__PURE__ */ft("ZodCustom",(t,e)=>{no.init(t,e),Fa.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e)=>{if("throw"===e.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,t)}),Pn="chat_device_id";function Fn(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const Dn=function(){const t={type:"object",shape:{id:Ua().optional(),type:xn(["text","image","audio","location","system"]).default("text"),content:Ua().optional(),imageUrl:Ua().url().optional(),audioUrl:Ua().url().optional(),latitude:dn().optional(),longitude:dn().optional(),timestamp:Ua().optional(),sender:xn(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Zo(pn).optional()}??{},...Zt(void 0)};return new wn(t)}();class Zn{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(t,e){this.endpoint=t,this.apiKey=e,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(t){this.track("message_sent",{type:t})}trackMessageReceived(t,e){this.track("message_received",{type:t,latency:e})}trackError(t,e){this.track("error",{error:t,context:e})}trackConnectionStatus(t){this.track("connection_status",{isConnected:t})}trackFeatureUsed(t){this.track("feature_used",{feature:t})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(t,e){this.track("attachment_sent",{type:t,size:e})}track(t,e){this.isDisabled||(this.queue.push({event:t,properties:{...e,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),x.warn("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const t=[...this.queue];this.queue=[];try{const e=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:t}),keepalive:!0});e.ok?x.debug(`Analytics: Flushed ${t.length} events`):(this.isDisabled=!0,this.queue=[],x.debug(`Analytics disabled: endpoint returned ${e.status}`))}catch(e){this.isDisabled=!0,this.queue=[],x.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}let Un=null,Ln=null;function Rn(t){Un=t}function Wn(t){Ln=t}const Bn=d(null);function Jn({children:t,defaultLocale:e,initialState:r,onStateChange:a,...n}){const[i,c]=o(r?.isOpen??!1),[d,l]=o(0),u=s(()=>{c(!0),l(0),a?.(!0)},[a]),p=s(()=>{c(!1),a?.(!1)},[a]),h=s(()=>{c(t=>{const e=!t;return e&&l(0),a?.(e),e})},[a]),g=s(t=>{Un?(Un(t),x.debug("ChatWidgetProvider sendMessage:",t)):x.warn("sendMessage called but no handler registered")},[]),m=s(()=>{Ln?(Ln(),x.debug("ChatWidgetProvider clearMessages called")):x.warn("clearMessages called but no handler registered")},[]),f={isOpen:i,open:u,close:p,toggle:h,sendMessage:g,clearMessages:m,unreadCount:d},w=s((t,e)=>{"message:received"!==t||i||l(t=>t+1),n.onEvent?.(t,e)},[i,n]);/* @__PURE__ */
|
|
32
32
|
return C(E,{defaultLocale:e,children:/* @__PURE__ */N(Bn.Provider,{value:f,children:[t,
|
|
33
|
-
/* @__PURE__ */C(Hn,{...n,onStateChange:t=>{c(t),t&&l(0),a?.(t)},onEvent:w})]})})}function Vn(){const t=l(Bn);if(!t)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return t}const qn=t=>new Promise((e,r)=>{const o=new FileReader;o.readAsDataURL(t),o.onload=()=>e(o.result),o.onerror=t=>r(t)});function Gn(t){const{apiKey:n,apiBaseUrl:d,agentId:l,pageContext:u,includeSEOMetadata:p=!1,theme:g,userContext:m,onLogin:f,onNavigate:b,onEvent:v,onStateChange:y,onThemeUpdate:k}=t,[E,S]=o(0),O=r(0),{t:I}=h(),$=function(t,e,o=!0){const n=r(null);return a(()=>{if(!o||!t||!e)return;const r=`${t}/analytics`;n.current=new Zn(r,e);const a=()=>n.current?.flush(),i=()=>{"hidden"===document.visibilityState&&n.current?.flush()};return window.addEventListener("beforeunload",a),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",a),window.removeEventListener("visibilitychange",i),n.current?.destroy()}},[t,e,o]),{trackOpen:s(()=>{n.current?.trackOpen()},[]),trackClose:s(()=>{n.current?.trackClose()},[]),trackMessageSent:s(t=>{n.current?.trackMessageSent(t)},[]),trackMessageReceived:s((t,e)=>{n.current?.trackMessageReceived(t,e)},[]),trackError:s((t,e)=>{n.current?.trackError(t,e)},[]),trackConnectionStatus:s(t=>{n.current?.trackConnectionStatus(t)},[]),trackFeatureUsed:s(t=>{n.current?.trackFeatureUsed(t)},[])}}(d,n,!0),C=function({enabled:t=!0,soundEnabled:e=!0,desktopEnabled:n=!0,botName:i="BotUyo",logoUrl:c,notificationSoundUrl:d}={}){const[l,u]=o("default"),p=r(null),h=c||w,g=d||z;a(()=>{e&&"undefined"!=typeof window&&(p.current=new Audio(g),p.current.volume=.3)},[e,g]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return x.warn("Notifications API not available"),!1;try{const t=await Notification.requestPermission();return u(t),x.info("Notification permission:",t),"granted"===t}catch(t){return x.error("Error requesting notification permission:",t),!1}},[]),f=s(e=>{if(t&&n&&"granted"===l&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${i}`;let r="Mensaje recibido";"text"===e.type&&"content"in e?r=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?r="📷 Imagen":"audio"===e.type?r="🎵 Audio":"location"===e.type&&(r="📍 Ubicación");const o=new Notification(t,{body:r,icon:h,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(r){x.error("Error showing notification:",r)}},[t,n,l,i,h]),b=s(()=>{if(t&&e&&("undefined"==typeof document||!document.hasFocus()))try{p.current?.play().catch(t=>{x.debug("Audio playback blocked:",t)})}catch(r){x.error("Error playing sound:",r)}},[t,e]),v=s(t=>{f(t),b()},[f,b]);return{permission:l,requestPermission:m,notify:f,playSound:b,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:g?.botName||"BotUyo",logoUrl:g?.logoUrl}),N=function(t=10,e=6e4){const o=r([]);return{isAllowed:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),!(o.current.length>=t||(o.current.push(r),0))},[t,e]),getRemainingAttempts:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),Math.max(0,t-o.current.length)},[t,e]),getTimeUntilReset:s(()=>{if(0===o.current.length)return 0;const t=Date.now(),r=o.current[0],a=e-(t-r);return Math.max(0,a)},[e]),reset:s(()=>{o.current=[]},[])}}(10,6e4),{state:M,actions:A}=function(t="default"){const[r,n]=c(mt,gt),[i,d]=o(!1),l=e.useMemo(()=>function(t="default"){return`botuyo_chat_v1_${t}`}(t),[t]),u=e.useMemo(()=>((t="default")=>(ht.has(t)||ht.set(t,new pt(t)),ht.get(t)))(t),[t]);a(()=>{"undefined"==typeof window||i||(async()=>{try{await u.migrateFromLocalStorage(t);const e=await u.getMessages(100),r=await u.getMetadata();if(e.length>0||r){const t={messages:e.map(t=>({...t,timestamp:new Date(t.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};n({type:"RESTORE_SESSION",payload:t})}}catch(e){x.warn("Chat: Error rehydrating from IndexedDB",e);try{const t=localStorage.getItem(l);if(t){const e=JSON.parse(t);e.messages&&(e.messages=e.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}))),n({type:"RESTORE_SESSION",payload:e})}}catch(r){x.error("Chat: Fallback rehydration failed",r)}}finally{d(!0)}})()},[i]),a(()=>{if(!i)return;const t=setTimeout(async()=>{try{await u.saveMessages(r.messages),await u.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(t){x.error("Chat Persistence Error:",t);try{const t={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(l,JSON.stringify(t))}catch(e){x.error("Chat: Fallback persistence failed",e)}}},500);return()=>clearTimeout(t)},[r.isOpen,r.messages,r.sessionId,i]);const p=s(t=>{n({type:"ADD_MESSAGE",payload:t})},[]),h=s(()=>n({type:"TOGGLE_WINDOW"}),[]),g=s(()=>n({type:"OPEN_WINDOW"}),[]),m=s(()=>n({type:"CLOSE_WINDOW"}),[]),f=s(t=>n({type:"SET_CONNECTED",payload:t}),[]),w=s(t=>n({type:"SET_TYPING",payload:t}),[]),b=s(t=>n({type:"SET_MESSAGES",payload:t}),[]),v=s(t=>n({type:"SET_ERROR",payload:t}),[]),y=s(t=>n({type:"SET_SESSION_ID",payload:t}),[]),k=s(()=>{localStorage.removeItem(l),n({type:"CLEAR_CHAT"})},[]),_=s(()=>{n({type:"SET_MESSAGES",payload:[]})},[]);return{state:r,isHydrated:i,actions:{toggleWindow:h,openWindow:g,closeWindow:m,setConnected:f,setTyping:w,addMessage:p,setMessages:b,setError:v,setSessionId:y,clearChat:k,clearMessages:_}}}(l),j=function(t=!1){const e="undefined"!=typeof window?window.location.pathname:"",r=i(()=>e,[e]),[n,s]=o({});return a(()=>{if(!t)return void s({});const e=setTimeout(()=>{const t=function(){if("undefined"==typeof window)return{};const t={};t.title=document.title,document.querySelectorAll("meta").forEach(e=>{const r=e.getAttribute("name"),o=e.getAttribute("property"),a=e.getAttribute("content");if(a){if(r)switch(r){case"description":t.description=a;break;case"keywords":t.keywords=a.split(",").map(t=>t.trim());break;case"author":t.author=a}if(o){if(o.startsWith("og:")){const e=o.replace("og:","og_");t[e]=a}if(o.startsWith("twitter:")){const e=o.replace("twitter:","twitter_");t[e]=a}}}});try{const e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length>0){const r=[];e.forEach(t=>{try{const e=JSON.parse(t.textContent||"");r.push(e)}catch{}}),r.length>0&&(t.structuredData=r)}}catch{}return t}();s(t)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(n).length>0?n:void 0}(p),P=function(t){const{apiKey:e,apiBaseUrl:n,agentId:c,pageContext:d,userContext:l}=t,u=r(t);a(()=>{u.current=t},[t]);const p=r(null),[h,g]=o(!1),[m,f]=o(!1),w=r(function(){try{const t=localStorage.getItem(Pn);if(t)return t;const e=Fn();return localStorage.setItem(Pn,e),e}catch{return x.warn("localStorage not available, using session-only device ID"),Fn()}}()),b=r(d);a(()=>{b.current=d},[d]);const v=s(t=>{const e=Dn.safeParse(t),r=e.success&&e.data.id?e.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=e.success&&e.data.sender?e.data.sender:"bot",a=e.success&&e.data.timestamp?new Date(e.data.timestamp):/* @__PURE__ */new Date,n=e.success?e.data:{type:"text"};switch(n.type){case"image":return{id:r,type:"image",sender:o,timestamp:a,imageUrl:n.imageUrl||n.content||"",altText:"Imagen enviada"};case"audio":return{id:r,type:"audio",sender:o,timestamp:a,content:n.audioUrl||n.content||""};case"location":return{id:r,type:"location",sender:o,timestamp:a,latitude:Number(n.latitude||0),longitude:Number(n.longitude||0),name:n.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:a,content:String(n.content||"")};default:return{id:r,type:"text",sender:o,timestamp:a,content:String(n.content||"Sin contenido"),emotion:n.emotion}}},[]),y=s(()=>{if(!e||!n)return;if(p.current?.connected)return;g(!0);const t=T(`${n}/webchat`,{auth:{apiKey:e,deviceId:w.current,agentId:c,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"}});t.on("connect",()=>{g(!1),f(!0),u.current.onConnected(`temp-${Date.now()}`,void 0)}),t.on("disconnect",t=>{g(!1),f(!1),u.current.onDisconnected()}),t.on("connect_error",t=>{g(!1),u.current.onError(`Error de conexión: ${t.message}`)}),t.on("connection_ack",t=>{u.current.onConnected(t.sessionId,t.config)}),t.on("bot_message",t=>{try{u.current.onMessage(v(t))}catch(e){x.error("ChatSocket Error processing bot_message:",e)}}),t.on("chat_history",t=>{if(t.messages&&Array.isArray(t.messages))if(u.current.onHistoryLoaded){const e=t.messages.map(t=>{try{return v(t)}catch(e){return x.debug("Error processing history message:",e),null}}).filter(t=>null!==t);u.current.onHistoryLoaded(e)}else t.messages.forEach(t=>{try{u.current.onMessage(v(t))}catch(e){x.debug("Error processing history message:",e)}});u.current.onEvent&&u.current.onEvent("history_loaded",t)}),t.on("bot_typing",t=>u.current.onTyping(t)),t.on("auth_success",t=>{u.current.onLogin&&u.current.onLogin(t),t.theme&&u.current.onThemeUpdate&&u.current.onThemeUpdate(t.theme)}),p.current=t},[e,n]),k=s(()=>{p.current&&(p.current.disconnect(),p.current=null,f(!1))},[]),z=r(y);z.current=y,a(()=>(z.current(),()=>{p.current&&(p.current.disconnect(),p.current=null)}),[]);const E=r([]),S=r([]),O=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),I=s(()=>{if(p.current?.connected)for(;E.current.length>0;){const t=E.current.shift();p.current.emit("user_message",t)}},[]);a(()=>{m&&I()},[m,I]),a(()=>{if(!m)return;const t=setInterval(()=>{const t=Date.now();S.current=S.current.filter(e=>t<e.nextRetryAt||(e.attempts>=e.maxAttempts?(u.current.onEvent?.("message_failed",{id:e.id,payload:e.payload}),x.error("Message failed after max retries:",e.id),!1):!p.current?.connected||(p.current.emit("user_message",e.payload,t=>{t?.success&&u.current.onEvent?.("message_sent",{id:e.id})}),e.attempts++,e.nextRetryAt=t+1e3*Math.pow(2,e.attempts),e.attempts<e.maxAttempts)))},500);return()=>clearInterval(t)},[m]);const $=s((t,e="text")=>{const r=O(),o={...b.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:w.current},a={id:r,content:t.trim(),type:e,metadata:o};return p.current?.connected?(p.current.emit("user_message",a,t=>{!1!==t?.success&&t?u.current.onEvent?.("message_sent",{id:r}):(S.current.push({id:r,payload:a,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),u.current.onEvent?.("message_retry_queued",{id:r}))}),r):(E.current.push(a),u.current.onEvent?.("queued_message",{id:r,payload:a}),r)},[O]),C=i(()=>_(t=>{p.current?.emit("typing",t)},250),[]);return{isConnected:m,isConnecting:h,sendMessage:$,sendTyping:C,getSocket:s(()=>p.current,[]),requestHistory:s(()=>{p.current?.emit("request_history")},[]),reconnect:y,disconnect:k}}({apiKey:n,apiBaseUrl:d,agentId:l,pageContext:i(()=>j?{...u||{},seo:{...j||{}}}:u,[u,j]),userContext:m,onMessage:s(t=>{const e=Date.now(),r=O.current>0?e-O.current:void 0;O.current=e,A.addMessage(t),$.trackMessageReceived(t.type,r),M.isOpen||"bot"!==t.sender||(S(t=>t+1),C.notifyWithSound(t))},[A,M.isOpen,$,C]),onConnected:s((t,e)=>{A.setConnected(!0),A.setSessionId(t),$.trackConnectionStatus(!0),e&&k&&k(e),e&&v&&v("backend_config",e)},[A,v,k,$]),onDisconnected:s(()=>{A.setConnected(!1),$.trackConnectionStatus(!1)},[A,$]),onTyping:s(t=>A.setTyping(t),[A]),onError:s(t=>{A.setError(t),$.trackError(t)},[A,$]),onLogin:f,onNavigate:b,onEvent:v,onThemeUpdate:k,onHistoryLoaded:s(t=>{const e=new Set(M.messages.map(t=>t.id)),r=t.filter(t=>!e.has(t.id));r.length>0&&(0===M.messages.length?A.setMessages(t):r.forEach(t=>A.addMessage(t)))},[M.messages,A])}),F=s(()=>{x.debug("ChatWidget handleToggle called, current isOpen:",M.isOpen),M.isOpen?(A.closeWindow(),$.trackClose(),y?.(!1),x.debug("ChatWidget Closing window")):(A.openWindow(),S(0),$.trackOpen(),y?.(!0),x.debug("ChatWidget Opening window"))},[M.isOpen,A,y,$]),D=s(t=>{if(!N.isAllowed()){const t=N.getTimeUntilReset(),e=Math.ceil(t/1e3);return void A.setError(I("rate_limit_exceeded")+` Espera ${e}s.`)}const e={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t};A.addMessage(e),$.trackMessageSent("text"),P.sendMessage(t,"text")},[A,P,N,$,I]),Z=s(async(t,e)=>{let r;r="audio"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(t)}:"image"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(t)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${t.name}`},A.addMessage(r);const o=await qn(t);P.sendMessage(o,e)},[A,P]),U=s(t=>{const e={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:t.latitude,longitude:t.longitude,name:"Mi ubicación"};A.addMessage(e),P.sendMessage(JSON.stringify(t),"location")},[A,P]);a(()=>{const t=()=>{M.isOpen||A.openWindow()},e=()=>{M.isOpen&&A.closeWindow()},r=()=>{M.isOpen?A.closeWindow():A.openWindow()},o=t=>{t.detail?.message&&D(t.detail.message)};return window.addEventListener("botuyo-chat:open",t),window.addEventListener("botuyo-chat:close",e),window.addEventListener("botuyo-chat:toggle",r),window.addEventListener("botuyo-chat:send-message",o),()=>{window.removeEventListener("botuyo-chat:open",t),window.removeEventListener("botuyo-chat:close",e),window.removeEventListener("botuyo-chat:toggle",r),window.removeEventListener("botuyo-chat:send-message",o)}},[M.isOpen,A,D]),a(()=>(Rn(D),()=>Rn(null)),[D]);const L=s(()=>{A.clearMessages(),x.info("Chat history cleared")},[A]);a(()=>(Wn(L),()=>Wn(null)),[L]);const R=i(()=>{if(M.isTyping)return"thinking";const t=[...M.messages].reverse().find(t=>"bot"===t.sender&&"text"===t.type);return"text"===t?.type&&t.emotion?t.emotion:"default"},[M.isTyping,M.messages]);return{state:M,actions:A,unreadCount:E,currentBotEmotion:R,isConnected:P.isConnected,getSocket:P.getSocket,handleToggle:F,handleSendText:D,handleSendAttachment:Z,handleSendLocation:U}}function Kn(t){const{apiKey:e,apiBaseUrl:n="https://api.botuyo.com",agentId:c,pageContext:d,includeSEOMetadata:l=!1,theme:u,mediaConfig:p,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w}=t,v=r(null),y=O();!function(t){const[e,r]=o(!1);a(()=>{let e=null;const o=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),o=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),a=document.getElementById("botuyo-chat-widget-root"),n=!!a?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),c="dark"===document.documentElement.getAttribute("data-theme"),d="dark"===document.body.getAttribute("data-theme"),l=!!t.current.parentElement?.closest('[data-theme="dark"]'),u=window.matchMedia("(prefers-color-scheme: dark)").matches,p=e||o||n||i||s||c||d||l||u;t.current&&(p?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(p)};o();const a=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>o();a.addEventListener("change",n);const i=new MutationObserver(()=>{o()}),s=document.getElementById("botuyo-chat-widget-root");s&&(i.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(i.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=s.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class","data-theme"]}),c=c.parentElement;const d=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),o())},100);return()=>{i.disconnect(),a.removeEventListener("change",n),clearInterval(d)}},[t])}(v);const[x,_]=o(),{mergedTheme:z,mergedStyles:E,getContainerStyle:S}=function(t,e){const r=function(){const[t,e]=o(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const t=window.matchMedia("(prefers-contrast: high)"),r=window.matchMedia("(prefers-contrast: more)"),o=t=>{e(t.matches)};return t.addEventListener("change",o),r.addEventListener("change",o),()=>{t.removeEventListener("change",o),r.removeEventListener("change",o)}},[]),t}(),n=i(()=>{const o=k(t,e);return r?{...o,primaryColor:"#000000",cssVariables:{...o.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:o},[t,e,r]),s=i(()=>({radius:{...L,...t?.bubbleStyles?.radius},bot:{...R,...t?.bubbleStyles?.bot},user:{...W,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:n,mergedStyles:s,getContainerStyle:(t,e,r)=>({"--chat-primary":n.primaryColor,zIndex:t?2147483647:9999,position:"fixed",top:e&&t?0:"auto",left:e&&t?0:"bottom-left"===r?"24px":"auto",right:e&&t?0:"bottom-right"!==r&&r?"auto":"24px",bottom:e&&t?0:"24px",width:e&&t?"100%":"auto",height:e&&t?"100%":"auto"})}}(u,x);a(()=>{z.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.')},[z.isHidden]);const{state:$,actions:T,unreadCount:M,currentBotEmotion:A,isConnected:j,handleToggle:P,handleSendText:F,handleSendAttachment:D,handleSendLocation:B,getSocket:J}=Gn({apiKey:e,apiBaseUrl:n,agentId:c,pageContext:d,includeSEOMetadata:l,theme:u,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w,onThemeUpdate:_}),V=s(t=>{T.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:t.sender,timestamp:/* @__PURE__ */new Date,content:t.content})},[T]),q=i(()=>{const t={...p||{}},e=x;return null!=e?.voiceEnabled&&(t.enableVoice=e.voiceEnabled),t},[p,x]),G=s(t=>{t.stopPropagation()},[]),K=S($.isOpen,y,u?.position),H=i(()=>{if(!z.cssVariables)return{};const t={},e=z.cssVariables;return e.background&&(t["--background"]=e.background),e.foreground&&(t["--foreground"]=e.foreground),e.card&&(t["--card"]=e.card),e.cardForeground&&(t["--card-foreground"]=e.cardForeground),e.primary&&(t["--primary"]=e.primary),e.primaryForeground&&(t["--primary-foreground"]=e.primaryForeground),e.muted&&(t["--muted"]=e.muted),e.mutedForeground&&(t["--muted-foreground"]=e.mutedForeground),e.border&&(t["--border"]=e.border),e.destructive&&(t["--destructive"]=e.destructive),e.radius&&(t["--radius"]=e.radius),e.spacing1&&(t["--spacing-1"]=e.spacing1),e.spacing2&&(t["--spacing-2"]=e.spacing2),e.spacing3&&(t["--spacing-3"]=e.spacing3),e.spacing4&&(t["--spacing-4"]=e.spacing4),e.spacing5&&(t["--spacing-5"]=e.spacing5),e.spacing6&&(t["--spacing-6"]=e.spacing6),e.spacing8&&(t["--spacing-8"]=e.spacing8),t},[z.cssVariables]);return z.isHidden?null:/* @__PURE__ */N("div",{ref:v,id:"botuyo-chat-widget",className:b("botuyo-chat-widget flex flex-col",!y&&("bottom-left"===u?.position?"items-start":"items-end")),style:{...K,...H,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===u?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===u?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===u?.effects?.softShadows?"false":void 0,children:[
|
|
33
|
+
/* @__PURE__ */C(Hn,{...n,onStateChange:t=>{c(t),t&&l(0),a?.(t)},onEvent:w})]})})}function Vn(){const t=l(Bn);if(!t)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return t}const qn=t=>new Promise((e,r)=>{const o=new FileReader;o.readAsDataURL(t),o.onload=()=>e(o.result),o.onerror=t=>r(t)});function Gn(t){const{apiKey:n,apiBaseUrl:d,agentId:l,pageContext:u,includeSEOMetadata:p=!1,theme:g,userContext:m,onLogin:f,onNavigate:b,onEvent:v,onStateChange:y,onThemeUpdate:k}=t,[E,S]=o(0),O=r(0),{t:I}=h(),$=function(t,e,o=!0){const n=r(null);return a(()=>{if(!o||!t||!e)return;const r=`${t}/analytics`;n.current=new Zn(r,e);const a=()=>n.current?.flush(),i=()=>{"hidden"===document.visibilityState&&n.current?.flush()};return window.addEventListener("beforeunload",a),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",a),window.removeEventListener("visibilitychange",i),n.current?.destroy()}},[t,e,o]),{trackOpen:s(()=>{n.current?.trackOpen()},[]),trackClose:s(()=>{n.current?.trackClose()},[]),trackMessageSent:s(t=>{n.current?.trackMessageSent(t)},[]),trackMessageReceived:s((t,e)=>{n.current?.trackMessageReceived(t,e)},[]),trackError:s((t,e)=>{n.current?.trackError(t,e)},[]),trackConnectionStatus:s(t=>{n.current?.trackConnectionStatus(t)},[]),trackFeatureUsed:s(t=>{n.current?.trackFeatureUsed(t)},[])}}(d,n,!0),C=function({enabled:t=!0,soundEnabled:e=!0,desktopEnabled:n=!0,botName:i="BotUyo",logoUrl:c,notificationSoundUrl:d}={}){const[l,u]=o("default"),p=r(null),h=c||w,g=d||z;a(()=>{e&&"undefined"!=typeof window&&(p.current=new Audio(g),p.current.volume=.3)},[e,g]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return x.warn("Notifications API not available"),!1;try{const t=await Notification.requestPermission();return u(t),x.info("Notification permission:",t),"granted"===t}catch(t){return x.error("Error requesting notification permission:",t),!1}},[]),f=s(e=>{if(t&&n&&"granted"===l&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${i}`;let r="Mensaje recibido";"text"===e.type&&"content"in e?r=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?r="📷 Imagen":"audio"===e.type?r="🎵 Audio":"location"===e.type&&(r="📍 Ubicación");const o=new Notification(t,{body:r,icon:h,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(r){x.error("Error showing notification:",r)}},[t,n,l,i,h]),b=s(()=>{if(t&&e&&("undefined"==typeof document||!document.hasFocus()))try{p.current?.play().catch(t=>{x.debug("Audio playback blocked:",t)})}catch(r){x.error("Error playing sound:",r)}},[t,e]),v=s(t=>{f(t),b()},[f,b]);return{permission:l,requestPermission:m,notify:f,playSound:b,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:g?.botName||"BotUyo",logoUrl:g?.logoUrl}),N=function(t=10,e=6e4){const o=r([]);return{isAllowed:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),!(o.current.length>=t||(o.current.push(r),0))},[t,e]),getRemainingAttempts:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),Math.max(0,t-o.current.length)},[t,e]),getTimeUntilReset:s(()=>{if(0===o.current.length)return 0;const t=Date.now(),r=o.current[0],a=e-(t-r);return Math.max(0,a)},[e]),reset:s(()=>{o.current=[]},[])}}(10,6e4),{state:M,actions:A}=function(t="default"){const[r,n]=c(mt,gt),[i,d]=o(!1),l=e.useMemo(()=>function(t="default"){return`botuyo_chat_v1_${t}`}(t),[t]),u=e.useMemo(()=>((t="default")=>(ht.has(t)||ht.set(t,new pt(t)),ht.get(t)))(t),[t]);a(()=>{"undefined"==typeof window||i||(async()=>{try{await u.migrateFromLocalStorage(t);const e=await u.getMessages(100),r=await u.getMetadata();if(e.length>0||r){const t={messages:e.map(t=>({...t,timestamp:new Date(t.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};n({type:"RESTORE_SESSION",payload:t})}}catch(e){x.warn("Chat: Error rehydrating from IndexedDB",e);try{const t=localStorage.getItem(l);if(t){const e=JSON.parse(t);e.messages&&(e.messages=e.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}))),n({type:"RESTORE_SESSION",payload:e})}}catch(r){x.error("Chat: Fallback rehydration failed",r)}}finally{d(!0)}})()},[i]),a(()=>{if(!i)return;const t=setTimeout(async()=>{try{await u.saveMessages(r.messages),await u.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(t){x.error("Chat Persistence Error:",t);try{const t={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(l,JSON.stringify(t))}catch(e){x.error("Chat: Fallback persistence failed",e)}}},500);return()=>clearTimeout(t)},[r.isOpen,r.messages,r.sessionId,i]);const p=s(t=>{n({type:"ADD_MESSAGE",payload:t})},[]),h=s(()=>n({type:"TOGGLE_WINDOW"}),[]),g=s(()=>n({type:"OPEN_WINDOW"}),[]),m=s(()=>n({type:"CLOSE_WINDOW"}),[]),f=s(t=>n({type:"SET_CONNECTED",payload:t}),[]),w=s(t=>n({type:"SET_TYPING",payload:t}),[]),b=s(t=>n({type:"SET_MESSAGES",payload:t}),[]),v=s(t=>n({type:"SET_ERROR",payload:t}),[]),y=s(t=>n({type:"SET_SESSION_ID",payload:t}),[]),k=s(()=>{localStorage.removeItem(l),n({type:"CLEAR_CHAT"})},[]),_=s(()=>{n({type:"SET_MESSAGES",payload:[]})},[]);return{state:r,isHydrated:i,actions:{toggleWindow:h,openWindow:g,closeWindow:m,setConnected:f,setTyping:w,addMessage:p,setMessages:b,setError:v,setSessionId:y,clearChat:k,clearMessages:_}}}(l),j=function(t=!1){const e="undefined"!=typeof window?window.location.pathname:"",r=i(()=>e,[e]),[n,s]=o({});return a(()=>{if(!t)return void s({});const e=setTimeout(()=>{const t=function(){if("undefined"==typeof window)return{};const t={};t.title=document.title,document.querySelectorAll("meta").forEach(e=>{const r=e.getAttribute("name"),o=e.getAttribute("property"),a=e.getAttribute("content");if(a){if(r)switch(r){case"description":t.description=a;break;case"keywords":t.keywords=a.split(",").map(t=>t.trim());break;case"author":t.author=a}if(o){if(o.startsWith("og:")){const e=o.replace("og:","og_");t[e]=a}if(o.startsWith("twitter:")){const e=o.replace("twitter:","twitter_");t[e]=a}}}});try{const e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length>0){const r=[];e.forEach(t=>{try{const e=JSON.parse(t.textContent||"");r.push(e)}catch{}}),r.length>0&&(t.structuredData=r)}}catch{}return t}();s(t)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(n).length>0?n:void 0}(p),P=function(t){const{apiKey:e,apiBaseUrl:n,agentId:c,pageContext:d,userContext:l}=t,u=r(t);a(()=>{u.current=t},[t]);const p=r(null),[h,g]=o(!1),[m,f]=o(!1),w=r(function(){try{const t=localStorage.getItem(Pn);if(t)return t;const e=Fn();return localStorage.setItem(Pn,e),e}catch{return x.warn("localStorage not available, using session-only device ID"),Fn()}}()),b=r(d);a(()=>{b.current=d},[d]);const v=s(t=>{const e=Dn.safeParse(t),r=e.success&&e.data.id?e.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=e.success&&e.data.sender?e.data.sender:"bot",a=e.success&&e.data.timestamp?new Date(e.data.timestamp):/* @__PURE__ */new Date,n=e.success?e.data:{type:"text"};switch(n.type){case"image":return{id:r,type:"image",sender:o,timestamp:a,imageUrl:n.imageUrl||n.content||"",altText:"Imagen enviada"};case"audio":return{id:r,type:"audio",sender:o,timestamp:a,content:n.audioUrl||n.content||""};case"location":return{id:r,type:"location",sender:o,timestamp:a,latitude:Number(n.latitude||0),longitude:Number(n.longitude||0),name:n.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:a,content:String(n.content||"")};default:return{id:r,type:"text",sender:o,timestamp:a,content:String(n.content||"Sin contenido"),emotion:n.emotion}}},[]),y=s(()=>{if(!e||!n)return;if(p.current?.connected)return;g(!0);const t=T(`${n}/webchat`,{auth:{apiKey:e,deviceId:w.current,agentId:c,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"}});t.on("connect",()=>{g(!1),f(!0),u.current.onConnected(`temp-${Date.now()}`,void 0)}),t.on("disconnect",t=>{g(!1),f(!1),u.current.onDisconnected()}),t.on("connect_error",t=>{g(!1),u.current.onError(`Error de conexión: ${t.message}`)}),t.on("connection_ack",t=>{u.current.onConnected(t.sessionId,t.config)}),t.on("bot_message",t=>{try{u.current.onMessage(v(t))}catch(e){x.error("ChatSocket Error processing bot_message:",e)}}),t.on("chat_history",t=>{if(t.messages&&Array.isArray(t.messages))if(u.current.onHistoryLoaded){const e=t.messages.map(t=>{try{return v(t)}catch(e){return x.debug("Error processing history message:",e),null}}).filter(t=>null!==t);u.current.onHistoryLoaded(e)}else t.messages.forEach(t=>{try{u.current.onMessage(v(t))}catch(e){x.debug("Error processing history message:",e)}});u.current.onEvent&&u.current.onEvent("history_loaded",t)}),t.on("bot_typing",t=>u.current.onTyping(t)),t.on("auth_success",t=>{u.current.onLogin&&u.current.onLogin(t),t.theme&&u.current.onThemeUpdate&&u.current.onThemeUpdate(t.theme)}),p.current=t},[e,n]),k=s(()=>{p.current&&(p.current.disconnect(),p.current=null,f(!1))},[]),z=r(y);z.current=y,a(()=>(z.current(),()=>{p.current&&(p.current.disconnect(),p.current=null)}),[]);const E=r([]),S=r([]),O=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),I=s(()=>{if(p.current?.connected)for(;E.current.length>0;){const t=E.current.shift();p.current.emit("user_message",t)}},[]);a(()=>{m&&I()},[m,I]),a(()=>{if(!m)return;const t=setInterval(()=>{const t=Date.now();S.current=S.current.filter(e=>t<e.nextRetryAt||(e.attempts>=e.maxAttempts?(u.current.onEvent?.("message_failed",{id:e.id,payload:e.payload}),x.error("Message failed after max retries:",e.id),!1):!p.current?.connected||(p.current.emit("user_message",e.payload,t=>{t?.success&&u.current.onEvent?.("message_sent",{id:e.id})}),e.attempts++,e.nextRetryAt=t+1e3*Math.pow(2,e.attempts),e.attempts<e.maxAttempts)))},500);return()=>clearInterval(t)},[m]);const $=s((t,e="text")=>{const r=O(),o={...b.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:w.current},a={id:r,content:t.trim(),type:e,metadata:o};return p.current?.connected?(p.current.emit("user_message",a,t=>{!1!==t?.success&&t?u.current.onEvent?.("message_sent",{id:r}):(S.current.push({id:r,payload:a,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),u.current.onEvent?.("message_retry_queued",{id:r}))}),r):(E.current.push(a),u.current.onEvent?.("queued_message",{id:r,payload:a}),r)},[O]),C=i(()=>_(t=>{p.current?.emit("typing",t)},250),[]);return{isConnected:m,isConnecting:h,sendMessage:$,sendTyping:C,getSocket:s(()=>p.current,[]),requestHistory:s(()=>{p.current?.emit("request_history")},[]),reconnect:y,disconnect:k}}({apiKey:n,apiBaseUrl:d,agentId:l,pageContext:i(()=>j?{...u||{},seo:{...j||{}}}:u,[u,j]),userContext:m,onMessage:s(t=>{const e=Date.now(),r=O.current>0?e-O.current:void 0;O.current=e,A.addMessage(t),$.trackMessageReceived(t.type,r),M.isOpen||"bot"!==t.sender||(S(t=>t+1),C.notifyWithSound(t))},[A,M.isOpen,$,C]),onConnected:s((t,e)=>{A.setConnected(!0),A.setSessionId(t),$.trackConnectionStatus(!0),e&&k&&k(e),e&&v&&v("backend_config",e)},[A,v,k,$]),onDisconnected:s(()=>{A.setConnected(!1),$.trackConnectionStatus(!1)},[A,$]),onTyping:s(t=>A.setTyping(t),[A]),onError:s(t=>{A.setError(t),$.trackError(t)},[A,$]),onLogin:f,onNavigate:b,onEvent:v,onThemeUpdate:k,onHistoryLoaded:s(t=>{const e=new Set(M.messages.map(t=>t.id)),r=t.filter(t=>!e.has(t.id));r.length>0&&(0===M.messages.length?A.setMessages(t):r.forEach(t=>A.addMessage(t)))},[M.messages,A])}),F=s(()=>{x.debug("ChatWidget handleToggle called, current isOpen:",M.isOpen),M.isOpen?(A.closeWindow(),$.trackClose(),y?.(!1),x.debug("ChatWidget Closing window")):(A.openWindow(),S(0),$.trackOpen(),y?.(!0),x.debug("ChatWidget Opening window"))},[M.isOpen,A,y,$]),D=s(t=>{if(!N.isAllowed()){const t=N.getTimeUntilReset(),e=Math.ceil(t/1e3);return void A.setError(I("rate_limit_exceeded")+` Espera ${e}s.`)}const e={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t};A.addMessage(e),$.trackMessageSent("text"),P.sendMessage(t,"text")},[A,P,N,$,I]),Z=s(async(t,e)=>{let r;r="audio"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(t)}:"image"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(t)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${t.name}`},A.addMessage(r);const o=await qn(t);P.sendMessage(o,e)},[A,P]),U=s(t=>{const e={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:t.latitude,longitude:t.longitude,name:"Mi ubicación"};A.addMessage(e),P.sendMessage(JSON.stringify(t),"location")},[A,P]);a(()=>{const t=()=>{M.isOpen||A.openWindow()},e=()=>{M.isOpen&&A.closeWindow()},r=()=>{M.isOpen?A.closeWindow():A.openWindow()},o=t=>{t.detail?.message&&D(t.detail.message)};return window.addEventListener("botuyo-chat:open",t),window.addEventListener("botuyo-chat:close",e),window.addEventListener("botuyo-chat:toggle",r),window.addEventListener("botuyo-chat:send-message",o),()=>{window.removeEventListener("botuyo-chat:open",t),window.removeEventListener("botuyo-chat:close",e),window.removeEventListener("botuyo-chat:toggle",r),window.removeEventListener("botuyo-chat:send-message",o)}},[M.isOpen,A,D]),a(()=>(Rn(D),()=>Rn(null)),[D]);const L=s(()=>{A.clearMessages(),x.info("Chat history cleared")},[A]);a(()=>(Wn(L),()=>Wn(null)),[L]);const R=i(()=>{if(M.isTyping)return"thinking";const t=[...M.messages].reverse().find(t=>"bot"===t.sender&&"text"===t.type);return"text"===t?.type&&t.emotion?t.emotion:"default"},[M.isTyping,M.messages]);return{state:M,actions:A,unreadCount:E,currentBotEmotion:R,isConnected:P.isConnected,getSocket:P.getSocket,handleToggle:F,handleSendText:D,handleSendAttachment:Z,handleSendLocation:U}}function Kn(t){const{apiKey:e,apiBaseUrl:n="https://api.botuyo.com",agentId:c,pageContext:d,includeSEOMetadata:l=!1,theme:u,mediaConfig:p,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w}=t,v=r(null),y=O();!function(t){const[e,r]=o(!1);a(()=>{let e=null;const o=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),o=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),a=document.getElementById("botuyo-chat-widget-root"),n=!!a?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),c="dark"===document.documentElement.getAttribute("data-theme"),d="dark"===document.body.getAttribute("data-theme"),l=!!t.current.parentElement?.closest('[data-theme="dark"]'),u=window.matchMedia("(prefers-color-scheme: dark)").matches,p=e||o||n||i||s||c||d||l||u;t.current&&(p?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(p)};o();const a=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>o();a.addEventListener("change",n);const i=new MutationObserver(()=>{o()}),s=document.getElementById("botuyo-chat-widget-root");s&&(i.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(i.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=s.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class","data-theme"]}),c=c.parentElement;const d=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),o())},100);return()=>{i.disconnect(),a.removeEventListener("change",n),clearInterval(d)}},[t])}(v);const[x,_]=o(),{mergedTheme:z,mergedStyles:E,getContainerStyle:S}=function(t,e){const r=function(){const[t,e]=o(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const t=window.matchMedia("(prefers-contrast: high)"),r=window.matchMedia("(prefers-contrast: more)"),o=t=>{e(t.matches)};return t.addEventListener("change",o),r.addEventListener("change",o),()=>{t.removeEventListener("change",o),r.removeEventListener("change",o)}},[]),t}(),n=i(()=>{const o=k(t,e);return r?{...o,primaryColor:"#000000",cssVariables:{...o.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:o},[t,e,r]),s=i(()=>({radius:{...L,...t?.bubbleStyles?.radius},bot:{...R,...t?.bubbleStyles?.bot},user:{...W,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:n,mergedStyles:s,getContainerStyle:(t,e,r)=>({"--chat-primary":n.primaryColor,zIndex:t?2147483647:9999,position:"fixed",top:e&&t?0:"auto",left:e&&t?0:"bottom-left"===r?"24px":"auto",right:e&&t?0:"bottom-right"!==r&&r?"auto":"24px",bottom:e&&t?0:"24px",width:e&&t?"100%":"auto",height:e&&t?"100%":"auto"})}}(u,x);a(()=>{z.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.')},[z.isHidden]);const{state:$,actions:T,unreadCount:M,currentBotEmotion:A,isConnected:j,handleToggle:P,handleSendText:F,handleSendAttachment:D,handleSendLocation:B,getSocket:J}=Gn({apiKey:e,apiBaseUrl:n,agentId:c,pageContext:d,includeSEOMetadata:l,theme:u,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w,onThemeUpdate:_}),V=s(t=>{T.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:t.sender,timestamp:/* @__PURE__ */new Date,content:t.content})},[T]),q=i(()=>{const t={...p||{}},e=x;return null!=e?.voiceEnabled&&(t.enableVoice=e.voiceEnabled),t},[p,x]),G=s(t=>{t.stopPropagation()},[]),K=S($.isOpen,y,u?.position),H=i(()=>{if(!z.cssVariables)return{};const t={},e=z.cssVariables;return e.background&&(t["--background"]=e.background),e.foreground&&(t["--foreground"]=e.foreground),e.card&&(t["--card"]=e.card),e.cardForeground&&(t["--card-foreground"]=e.cardForeground),e.primary&&(t["--primary"]=e.primary),e.primaryForeground&&(t["--primary-foreground"]=e.primaryForeground),e.muted&&(t["--muted"]=e.muted),e.mutedForeground&&(t["--muted-foreground"]=e.mutedForeground),e.border&&(t["--border"]=e.border),e.destructive&&(t["--destructive"]=e.destructive),e.radius&&(t["--radius"]=e.radius),e.spacing1&&(t["--spacing-1"]=e.spacing1),e.spacing2&&(t["--spacing-2"]=e.spacing2),e.spacing3&&(t["--spacing-3"]=e.spacing3),e.spacing4&&(t["--spacing-4"]=e.spacing4),e.spacing5&&(t["--spacing-5"]=e.spacing5),e.spacing6&&(t["--spacing-6"]=e.spacing6),e.spacing8&&(t["--spacing-8"]=e.spacing8),t},[z.cssVariables]);return z.isHidden?null:x?/* @__PURE__ */N("div",{ref:v,id:"botuyo-chat-widget",className:b("botuyo-chat-widget flex flex-col",!y&&("bottom-left"===u?.position?"items-start":"items-end")),style:{...K,...H,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===u?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===u?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===u?.effects?.softShadows?"false":void 0,children:[
|
|
34
34
|
/* @__PURE__ */C("div",{className:b("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",y?"bottom-left"===u?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",$.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:$.isOpen?"auto":"none"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */C(U,{children:/* @__PURE__ */C(I,{isOpen:$.isOpen,isConnected:j,isTyping:$.isTyping,messages:$.messages,onClose:()=>T.closeWindow(),onSendMessage:F,onSendAttachment:D,onSendLocation:B,botName:z.botName,logoUrl:z.logoUrl,welcomeMessage:z.welcomeMessage,inputPlaceholder:u?.inputPlaceholder||x?.inputPlaceholder,primaryColor:z.primaryColor,position:u?.position,bubbleStyles:E,avatars:u?.avatars||x?.avatars||x?.avatarAnimations||{},mediaConfig:q,theme:z,avatar3dUrl:u?.avatar3dUrl,getSocket:J,onAddVoiceMessage:V})})}),
|
|
35
|
-
/* @__PURE__ */C("div",{className:b($.isOpen?"hidden":"block",!y&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */C(Z,{isOpen:$.isOpen,onClick:P,unreadCount:M,position:u?.position||"bottom-right",primaryColor:z.primaryColor,logoUrl:z.logoUrl,starterPrompt:u?.starterPrompt||x?.starterPrompt,avatars:u?.avatars||x?.avatars||x?.avatarAnimations||{},emotion:A,styles:E,promptPersistence:u?.promptPersistence,avatarScale:u?.avatarScale??x?.avatarScale,showPromptAvatar:u?.showPromptAvatar??x?.showPromptAvatar})})]})}function Hn(t){/* @__PURE__ */
|
|
35
|
+
/* @__PURE__ */C("div",{className:b($.isOpen?"hidden":"block",!y&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */C(Z,{isOpen:$.isOpen,onClick:P,unreadCount:M,position:u?.position||"bottom-right",primaryColor:z.primaryColor,logoUrl:z.logoUrl,starterPrompt:u?.starterPrompt||x?.starterPrompt,avatars:u?.avatars||x?.avatars||x?.avatarAnimations||{},emotion:A,styles:E,promptPersistence:u?.promptPersistence,avatarScale:u?.avatarScale??x?.avatarScale,showPromptAvatar:u?.showPromptAvatar??x?.showPromptAvatar})})]}):null}function Hn(t){/* @__PURE__ */
|
|
36
36
|
return C(E,{defaultLocale:t.theme?.defaultLocale,children:/* @__PURE__ */C(S,{animations:t.theme?.animations,effects:t.theme?.effects,children:/* @__PURE__ */C(Kn,{...t})})})}const Yn=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Hn,ChatWidgetInner:Kn},Symbol.toStringTag,{value:"Module"})),Xn="https://api.botuyo.com";class Qn extends n{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,e){console.error("[BotUyoChat] Widget error:",t,e)}render(){return this.state.hasError?null:this.props.children}}const ti={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--cardForeground":"0 0% 98%","--primary":"160 84% 39%","--primaryForeground":"0 0% 100%","--muted":"240 3.7% 15.9%","--mutedForeground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},ei=u(()=>Promise.resolve().then(()=>Yn).then(t=>({default:t.ChatWidget})));class ri{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(t){return this.config={...t,apiBaseUrl:t.apiBaseUrl||Xn},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 t=document.createElement("style");t.textContent=M.replace(/:root/g,":host"),this.shadowRoot.appendChild(t),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 t=this.config.theme.cssVariables,e={background:t.background,foreground:t.foreground,card:t.card,cardForeground:t.cardForeground,primary:t.primary,primaryForeground:t.primaryForeground,muted:t.muted,mutedForeground:t.mutedForeground,border:t.border,destructive:t.destructive,radius:t.radius,spacing1:t.spacing1,spacing2:t.spacing2,spacing3:t.spacing3,spacing4:t.spacing4,spacing5:t.spacing5,spacing6:t.spacing6,spacing8:t.spacing8};Object.entries(e).forEach(([t,e])=>{void 0!==e&&this.mountPoint.style.setProperty(`--${t}`,e)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const t=document.documentElement.getAttribute("data-theme");return"dark"===t||"light"!==t&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(ti).forEach(t=>{this.mountPoint.style.removeProperty(t)}):Object.entries(ti).forEach(([t,e])=>{this.mountPoint.style.setProperty(t,e)})),!this.root&&this.mountPoint&&(this.root=t(this.mountPoint));const r={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||Xn,agentId:this.config.agentId,theme:{primaryColor:"#10b981",botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",borderRadius:"0.75rem",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},o=e.createElement(p,{fallback:e.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:r.theme?.primaryColor||"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},e.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"}}))},e.createElement(ei,r));this.root.render(e.createElement(Qn,null,e.createElement(E,{defaultLocale:this.config.theme?.defaultLocale,children:o}))),console.log("[BotUyoChat] Widget initialized",r)}update(t){this.config?(this.config={...this.config,...t,theme:{...this.config.theme,...t.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(t){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:t}}))}getState(){return null}}const oi=new ri;window.BotUyoChat=oi;export{ri as BotUyoChatWidget,D as ChatWidget,Jn as ChatWidgetProvider,Hn as ChatWidgetUnstyled,E as LanguageProvider,oi as default,Vn as useChatWidget,$ as useLanguage};
|
|
37
37
|
//# sourceMappingURL=botuyo-chat.es.js.map
|