@vocantly/widget 0.1.12 → 0.1.13

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/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- var $e=Object.create;var K=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var ye=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(s){throw t=0,s}},Ne=(e,t)=>{for(var s in t)K(e,s,{get:t[s],enumerable:!0})},xe=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pe(t))!We.call(e,n)&&n!==s&&K(e,n,{get:()=>t[n],enumerable:!(i=Ve(t,n))||i.enumerable});return e};var se=(e,t,s)=>(s=e!=null?$e(Fe(e)):{},xe(t||!e||!e.__esModule?K(s,"default",{value:e,enumerable:!0}):s,e)),qe=e=>xe(K({},"__esModule",{value:!0}),e);var Ce=ye((St,ie)=>{"use strict";var ze=Object.prototype.hasOwnProperty,S="~";function P(){}Object.create&&(P.prototype=Object.create(null),new P().__proto__||(S=!1));function Je(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function Se(e,t,s,i,n){if(typeof s!="function")throw new TypeError("The listener must be a function");var a=new Je(s,i||e,n),r=S?S+t:t;return e._events[r]?e._events[r].fn?e._events[r]=[e._events[r],a]:e._events[r].push(a):(e._events[r]=a,e._eventsCount++),e}function Q(e,t){--e._eventsCount===0?e._events=new P:delete e._events[t]}function x(){this._events=new P,this._eventsCount=0}x.prototype.eventNames=function(){var t=[],s,i;if(this._eventsCount===0)return t;for(i in s=this._events)ze.call(s,i)&&t.push(S?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(s)):t};x.prototype.listeners=function(t){var s=S?S+t:t,i=this._events[s];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,r=new Array(a);n<a;n++)r[n]=i[n].fn;return r};x.prototype.listenerCount=function(t){var s=S?S+t:t,i=this._events[s];return i?i.fn?1:i.length:0};x.prototype.emit=function(t,s,i,n,a,r){var l=S?S+t:t;if(!this._events[l])return!1;var c=this._events[l],h=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),h){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,s),!0;case 3:return c.fn.call(c.context,s,i),!0;case 4:return c.fn.call(c.context,s,i,n),!0;case 5:return c.fn.call(c.context,s,i,n,a),!0;case 6:return c.fn.call(c.context,s,i,n,a,r),!0}for(d=1,u=new Array(h-1);d<h;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var y=c.length,m;for(d=0;d<y;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),h){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,s);break;case 3:c[d].fn.call(c[d].context,s,i);break;case 4:c[d].fn.call(c[d].context,s,i,n);break;default:if(!u)for(m=1,u=new Array(h-1);m<h;m++)u[m-1]=arguments[m];c[d].fn.apply(c[d].context,u)}}return!0};x.prototype.on=function(t,s,i){return Se(this,t,s,i,!1)};x.prototype.once=function(t,s,i){return Se(this,t,s,i,!0)};x.prototype.removeListener=function(t,s,i,n){var a=S?S+t:t;if(!this._events[a])return this;if(!s)return Q(this,a),this;var r=this._events[a];if(r.fn)r.fn===s&&(!n||r.once)&&(!i||r.context===i)&&Q(this,a);else{for(var l=0,c=[],h=r.length;l<h;l++)(r[l].fn!==s||n&&!r[l].once||i&&r[l].context!==i)&&c.push(r[l]);c.length?this._events[a]=c.length===1?c[0]:c:Q(this,a)}return this};x.prototype.removeAllListeners=function(t){var s;return t?(s=S?S+t:t,this._events[s]&&Q(this,s)):(this._events=new P,this._eventsCount=0),this};x.prototype.off=x.prototype.removeListener;x.prototype.addListener=x.prototype.on;x.prefixed=S;x.EventEmitter=x;typeof ie!="undefined"&&(ie.exports=x)});var Te=ye((It,_e)=>{"use strict";_e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var yt={};Ne(yt,{close:()=>wt,destroy:()=>vt,init:()=>mt,open:()=>bt});module.exports=qe(yt);var k=se(Ce(),1);var v=[];for(Y=0;Y<256;++Y)v.push((Y+256).toString(16).slice(1));var Y;function ke(e,t=0){return(v[e[t+0]]+v[e[t+1]]+v[e[t+2]]+v[e[t+3]]+"-"+v[e[t+4]]+v[e[t+5]]+"-"+v[e[t+6]]+v[e[t+7]]+"-"+v[e[t+8]]+v[e[t+9]]+"-"+v[e[t+10]]+v[e[t+11]]+v[e[t+12]]+v[e[t+13]]+v[e[t+14]]+v[e[t+15]]).toLowerCase()}var G,Be=new Uint8Array(16);function ne(){if(!G&&(G=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!G))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return G(Be)}var Ke=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),re={randomUUID:Ke};function Qe(e,t,s){if(re.randomUUID&&!t&&!e)return re.randomUUID();e=e||{};var i=e.random||(e.rng||ne)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){s=s||0;for(var n=0;n<16;++n)t[s+n]=i[n];return t}return ke(i)}var ae=Qe;var ht={},Ye=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,s)=>(typeof require!="undefined"?require:t)[s]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=class{constructor(e=!1){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[Vocantly SDK]",...e)}info(...e){this.enabled&&console.info("[Vocantly SDK]",...e)}warn(...e){this.enabled&&console.warn("[Vocantly SDK]",...e)}error(...e){this.enabled&&console.error("[Vocantly SDK]",...e)}},oe=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,U=null,F=null;async function Ge(){return oe?U||F||(F=(async()=>{try{try{return U=await Promise.resolve().then(()=>se(Te(),1)),U}catch(e){if(typeof Ye!="undefined"){let{createRequire:t}=await import("module");return U=t(ht.url||__filename)("ws"),U}throw e}}catch{return null}finally{F=null}})(),F):null}var Xe=class extends k.default{constructor(e,t={}){var s,i,n;super(),this.ws=null,this.token=null,this.reconnectAttempts=0,this.reconnectTimer=null,this.isManuallyDisconnected=!1,this.isTokenExpired=!1,this.url=e,this.autoReconnect=(s=t.autoReconnect)!=null?s:!0,this.maxReconnectAttempts=(i=t.maxReconnectAttempts)!=null?i:5,this.logger=new E((n=t.debug)!=null?n:!1)}connect(e){if(!e||e.length===0){let t=new Error("Token is required for connection");return this.emit("error",t),Promise.reject(t)}return this.token=e,this.isManuallyDisconnected=!1,this.isTokenExpired=!1,this.attemptConnection()}async attemptConnection(){var s;let e=new URL(this.url),t=(s=this.token)!=null?s:"";if(oe){let i=await Ge();if(this.logger.debug("ws module loaded:",!!i),i&&i.WebSocket)return this.logger.debug("Using ws package with Authorization header"),new Promise((n,a)=>{try{let r=new i.WebSocket(e.toString(),{headers:{Authorization:`Bearer ${t}`}});this.ws=r;let l=!1,c=h=>{if(l)return;l=!0;let u=String((h==null?void 0:h.message)||h||"").toLowerCase();if(u.includes("401")||u.includes("unauthorized")||h!=null&&h.code&&String(h.code).includes("401")){this.handleTokenExpiration();let d=new Error("Token expired or invalid. Please refresh your token and reconnect.");d.name="TokenExpiredError",this.emit("error",d),a(d);return}};typeof r.addEventListener=="function"?(r.addEventListener("error",c),r.addEventListener("open",()=>{r.removeEventListener("error",c)})):typeof r.once=="function"&&(r.once("error",c),r.once("open",()=>{})),this.setupEventHandlers(n,a)}catch(r){this.logger.error("Failed to create ws.WebSocket:",r),a(r)}});this.logger.warn("ws package not available, falling back to native WebSocket")}return this.logger.debug("Using native WebSocket with query parameter",{url:e.toString(),hasToken:!!t}),new Promise((i,n)=>{try{if(!t||t.length===0){let l=new Error("Token is required for WebSocket connection");this.logger.error(l.message),n(l);return}let a=new URL(e.toString());a.searchParams.set("token",t),this.ws=new globalThis.WebSocket(a.toString()),this.logger.debug("WebSocket instance created",{readyState:this.ws.readyState,url:this.ws.url,protocol:this.ws.protocol});let r=this.ws;this.setupEventHandlers(i,n),setTimeout(()=>{(r.readyState===WebSocket.CLOSED||r.readyState===WebSocket.CLOSING)&&this.logger.warn("WebSocket closed immediately after creation",{readyState:r.readyState,url:r.url})},100)}catch(a){this.logger.error("Failed to create native WebSocket:",a),n(a)}})}setupEventHandlers(e,t){this.ws&&(this.ws.onopen=()=>{this.reconnectAttempts=0,this.isTokenExpired=!1;let s=this.ws;if(!s){this.logger.error("WebSocket is null in onopen handler"),t(new Error("WebSocket instance lost"));return}if(this.logger.debug("WebSocket connected",{readyState:s.readyState,url:s.url,protocol:s.protocol,extensions:s.extensions}),s.readyState!==WebSocket.OPEN){this.logger.error("WebSocket readyState is not OPEN after onopen",{readyState:s.readyState}),t(new Error(`WebSocket not open: readyState=${s.readyState}`));return}this.emit("connected"),e()},this.ws.onmessage=s=>{try{let i=JSON.parse(s.data);this.logger.debug("Received message:",i),this.emit("message",i)}catch(i){let n=i instanceof Error?i:new Error("Failed to parse message");this.logger.error("Failed to parse message:",n),this.emit("error",n)}},this.ws.onerror=s=>{this.logger.error("WebSocket error:",s);let i;if(s instanceof Error?i=s:s&&s.message?i=s instanceof Error?s:new Error(String(s.message)):i=new Error("WebSocket connection error"),oe&&s&&s.message){let n=String(s.message).toLowerCase();if(n.includes("401")||n.includes("unauthorized")){this.handleTokenExpiration();let a=new Error("Token expired or invalid. Please refresh your token and reconnect.");a.name="TokenExpiredError",this.emit("error",a),t(a);return}}this.emit("error",i)},this.ws.onclose=s=>{if(this.logger.debug("WebSocket closed:",{code:s.code,reason:s.reason,wasClean:s.wasClean}),s.code===1006&&this.logger.warn("Abnormal closure (1006) - connection closed without proper handshake. Possible causes: network issue, server closed connection, CORS issue, or protocol mismatch."),s.code===1008||s.code===1002||s.reason&&s.reason.toLowerCase().includes("unauthorized")||s.reason&&s.reason.toLowerCase().includes("401")){this.handleTokenExpiration();let n=new Error("Token expired or invalid. Please refresh your token and reconnect.");n.name="TokenExpiredError",this.emit("error",n),this.emit("disconnected",{code:s.code,reason:s.reason,tokenExpired:!0});return}this.emit("disconnected",{code:s.code,reason:s.reason}),!this.isManuallyDisconnected&&!this.isTokenExpired&&this.autoReconnect?this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():(this.logger.warn("Max reconnection attempts reached"),this.emit("error",new Error("Max reconnection attempts reached"))):this.isTokenExpired&&this.logger.warn("Not reconnecting: token is expired")})}handleTokenExpiration(){this.isTokenExpired=!0,this.autoReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}disconnect(){this.isManuallyDisconnected=!0,this.autoReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.logger.debug("WebSocket disconnected")}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){let t=new Error("WebSocket is not connected");throw this.logger.error(t.message),this.emit("error",t),t}try{let t=JSON.stringify(e);this.logger.debug("Sending message:",e),this.ws.send(t)}catch(t){let s=t instanceof Error?t:new Error("Failed to send message");throw this.logger.error("Send error:",s),this.emit("error",s),s}}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getReconnectAttempts(){return this.reconnectAttempts}scheduleReconnect(){if(this.reconnectTimer||!this.token)return;this.reconnectAttempts++;let e=[1e3,2e3,5e3,1e4],t=e[Math.min(this.reconnectAttempts-1,e.length-1)];this.logger.debug(`Scheduling reconnect attempt ${this.reconnectAttempts} in ${t}ms`),this.emit("reconnecting",{attempt:this.reconnectAttempts,delay:t}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.attemptConnection().catch(()=>{})},t)}},Ze=class{constructor(){this.token=null}setToken(e){if(!this.isValidFormat(e))throw new Error("Invalid token format");this.token=e}getToken(){return this.token}hasToken(){return this.token!==null&&this.token.length>0}clearToken(){this.token=null}rotateToken(e){if(!this.isValidFormat(e))throw new Error("Invalid token format");this.token=e}isValidFormat(e){return typeof e=="string"&&e.length>0}validateTokenPresence(){if(!this.hasToken())throw new Error("Token is required but not set")}},W=class{static createOptimistic(e,t,s,i="text",n){return{id:t,conversationId:e,content:s,messageType:i,optimistic:!0,receiptState:"sent",createdAt:new Date,metadata:n}}static fromServerPayload(e,t){var n,a;let s=(n=t.sender_id)!=null?n:t.senderId,i=(a=t.sender_type)!=null?a:t.senderType;return{id:t.message_id,conversationId:e,content:t.content,senderId:s,senderName:t.sender_name,senderType:i,messageType:t.message_type==="system"?"system":"text",optimistic:!1,receiptState:"sent",createdAt:t.sent_at?new Date(t.sent_at):new Date}}static confirmOptimistic(e,t){var n,a,r;let s=(n=t.sender_id)!=null?n:t.senderId,i=(a=t.sender_type)!=null?a:t.senderType;return{...e,optimistic:!1,senderId:s,senderName:t.sender_name,senderType:i,receiptState:(r=e.receiptState)!=null?r:"sent",createdAt:t.sent_at?new Date(t.sent_at):e.createdAt}}static updateReceiptState(e,t){return{...e,receiptState:t}}},et=class extends k.default{constructor(e=!1){super(),this.receiptState=new Map,this.logger=new E(e)}getReceiptState(e){return this.receiptState.get(e)}handleDelivered(e,t){var i;if(!e)return this.logger.warn("Invalid delivered receipt: missing messageId"),!1;let s=(i=this.receiptState.get(e))!=null?i:"sent";return this.compareStates(s,"delivered")<0?(this.receiptState.set(e,"delivered"),this.emit("receipt",{messageId:e,state:"delivered",userId:t}),this.logger.debug("Receipt delivered:",e),!0):(this.logger.debug("Delivered receipt ignored (already delivered or read):",e),!1)}handleRead(e,t){var i;if(!e)return this.logger.warn("Invalid read receipt: missing messageId"),!1;let s=(i=this.receiptState.get(e))!=null?i:"sent";return this.compareStates(s,"read")<0?(this.receiptState.set(e,"read"),this.emit("receipt",{messageId:e,state:"read",userId:t}),this.logger.debug("Receipt read:",e),!0):(this.logger.debug("Read receipt ignored (already read):",e),!1)}compareStates(e,t){let s=["sent","delivered","read"],i=s.indexOf(e),n=s.indexOf(t);return i===-1||n===-1?0:i-n}clearConversation(e,t){let s=0;for(let i of t)this.receiptState.has(i)&&(this.receiptState.delete(i),s++);s>0&&this.logger.debug("Cleared receipt state for conversation:",e,`(${s} messages)`)}clearMessage(e){this.receiptState.delete(e)&&this.logger.debug("Cleared receipt state for message:",e)}clear(){this.receiptState.clear(),this.logger.debug("Cleared all receipt state")}},tt=class extends k.default{constructor(e=!1){super(),this.seenMessageIds=new Map,this.optimisticMessages=new Map,this.confirmedMessages=new Map,this.warnedMissingSenderId=new Set,this.logger=new E(e),this.receiptManager=new et(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,s,i="text",n){let a=W.createOptimistic(e,t,s,i,n);return this.trackOptimisticMessage(e,t,a),this.trackMessageId(e,t),this.emit("message",a),this.logger.debug("Created optimistic message:",t),a}handleIncomingMessage(e,t){let s=t.message_id,i=this.getOptimisticMessage(e,s);if(i){let a=this.reconcileOptimisticMessage(i,t);return a.senderId==null&&!this.warnedMissingSenderId.has(e)&&(this.warnedMissingSenderId.add(e),console.warn('[Vocantly SDK] Message payload missing sender_id (and sender_type). Clients cannot show "You" vs other participant. The realtime backend MUST include sender_id and sender_type in every type:"message" payload. See docs/REALTIME_WEBSOCKET_CONTRACT.md.')),this.removeOptimisticMessage(e,s),this.trackMessageId(e,s),this.trackConfirmedMessage(e,s,a),a}if(this.hasSeenMessage(e,s))return this.logger.debug("Duplicate message ignored:",s),null;this.trackMessageId(e,s);let n=W.fromServerPayload(e,t);return n.senderId==null&&!this.warnedMissingSenderId.has(e)&&(this.warnedMissingSenderId.add(e),console.warn('[Vocantly SDK] Message payload missing sender_id (and sender_type). Clients cannot show "You" vs other participant. The realtime backend MUST include sender_id and sender_type in every type:"message" payload. See docs/REALTIME_WEBSOCKET_CONTRACT.md.')),this.trackConfirmedMessage(e,s,n),this.emit("message",n),this.logger.debug("Handled incoming message:",s),n}handleReceipt(e,t,s,i){s==="delivered"?this.receiptManager.handleDelivered(t,i):s==="read"&&this.receiptManager.handleRead(t,i)}updateMessageReceiptState(e){for(let[,t]of this.confirmedMessages.entries()){let s=t.get(e.messageId);if(s){let i=W.updateReceiptState(s,e.state);t.set(e.messageId,i),this.emit("message",i),this.logger.debug("Updated message receipt state:",e.messageId,e.state);return}}for(let[,t]of this.optimisticMessages.entries()){let s=t.get(e.messageId);if(s){let i=W.updateReceiptState(s,e.state);t.set(e.messageId,i),this.emit("message",i),this.logger.debug("Updated optimistic message receipt state:",e.messageId,e.state);return}}this.logger.warn("Receipt for unknown message:",e.messageId)}reconcileOptimisticMessage(e,t){let s=W.confirmOptimistic(e,t);return this.logger.debug("Reconciled optimistic message (no second emit):",e.id),s}hasSeenMessage(e,t){var i;let s=this.seenMessageIds.get(e);return(i=s==null?void 0:s.has(t))!=null?i:!1}trackMessageIdsFromHistory(e,t){for(let s of t)this.trackMessageId(e,s)}trackMessageId(e,t){let s=this.seenMessageIds.get(e);s||(s=new Set,this.seenMessageIds.set(e,s)),s.add(t)}trackOptimisticMessage(e,t,s){let i=this.optimisticMessages.get(e);i||(i=new Map,this.optimisticMessages.set(e,i)),i.set(t,s)}getOptimisticMessage(e,t){let s=this.optimisticMessages.get(e);return s==null?void 0:s.get(t)}removeOptimisticMessage(e,t){let s=this.optimisticMessages.get(e);s&&(s.delete(t),s.size===0&&this.optimisticMessages.delete(e))}trackConfirmedMessage(e,t,s){let i=this.confirmedMessages.get(e);i||(i=new Map,this.confirmedMessages.set(e,i)),i.set(t,s)}getMessageIds(e){let t=this.confirmedMessages.get(e),s=this.optimisticMessages.get(e),i=new Set;if(t)for(let n of t.keys())i.add(n);if(s)for(let n of s.keys())i.add(n);return Array.from(i)}clearConversation(e){this.seenMessageIds.delete(e),this.optimisticMessages.delete(e);let t=this.getMessageIds(e);this.receiptManager.clearConversation(e,t),this.confirmedMessages.delete(e),this.logger.debug("Cleared message tracking for conversation:",e)}clear(){this.seenMessageIds.clear(),this.optimisticMessages.clear(),this.confirmedMessages.clear(),this.receiptManager.clear(),this.logger.debug("Cleared all message tracking")}},st=class extends k.default{constructor(e=!1){super(),this.typingTimers=new Map,this.activeTyping=new Map,this.TYPING_TIMEOUT_MS=5e3,this.logger=new E(e)}handleTypingStart(e,t){if(!e||!t){this.logger.warn("Invalid typing_start: missing conversationId or userId");return}let s=this.activeTyping.get(e);s||(s=new Set,this.activeTyping.set(e,s));let i=this.typingTimers.get(e);i||(i=new Map,this.typingTimers.set(e,i));let n=s.has(t),a=i.get(t);a&&clearTimeout(a),s.add(t);let r=setTimeout(()=>{this.handleTypingStop(e,t)},this.TYPING_TIMEOUT_MS);i.set(t,r),n?this.logger.debug("Typing timer restarted:",e,t):(this.emit("typing",{conversationId:e,userId:t,state:"start"}),this.logger.debug("Typing started:",e,t))}handleTypingStop(e,t){if(!e||!t){this.logger.warn("Invalid typing_stop: missing conversationId or userId");return}let s=this.activeTyping.get(e),i=this.typingTimers.get(e);if(!s||!s.has(t)){this.logger.debug("Typing stop ignored (user not typing):",e,t);return}let n=i==null?void 0:i.get(t);n&&(clearTimeout(n),i==null||i.delete(t)),s.delete(t),s.size===0&&this.activeTyping.delete(e),i&&i.size===0&&this.typingTimers.delete(e),this.emit("typing",{conversationId:e,userId:t,state:"stop"}),this.logger.debug("Typing stopped:",e,t)}clearConversation(e){let t=this.activeTyping.get(e),s=this.typingTimers.get(e);if(t){for(let i of t)this.emit("typing",{conversationId:e,userId:i,state:"stop"});this.activeTyping.delete(e)}if(s){for(let i of s.values())clearTimeout(i);this.typingTimers.delete(e)}this.logger.debug("Cleared typing state for conversation:",e)}clear(){for(let e of this.typingTimers.values())for(let t of e.values())clearTimeout(t);this.typingTimers.clear(),this.activeTyping.clear(),this.logger.debug("Cleared all typing state")}getTypingUsers(e){let t=this.activeTyping.get(e);return t?Array.from(t):[]}},it=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Ee,Me=typeof RTCPeerConnection!="undefined"&&typeof navigator!="undefined"&&typeof((Ee=navigator.mediaDevices)==null?void 0:Ee.getUserMedia)=="function",N=class extends k.default{constructor(e={}){var t;super(),this.peers=new Map,this.localStream=null,this.mediaOptions={},this.screenTrack=null,this.cameraTrack=null,this.options=e,this.iceServers=(t=e.iceServers)!=null?t:it,this.getIceServers=e.getIceServers,this.iceServersResolved=!e.getIceServers}static isAvailable(){return Me}static async enumerateDevices(){var e;if(!((e=navigator.mediaDevices)!=null&&e.enumerateDevices))return[];try{return await navigator.mediaDevices.enumerateDevices()}catch{return[]}}setMediaOptions(e){this.mediaOptions={...this.mediaOptions,...e}}async getMedia(e){if(this.localStream)return this.localStream;let t=this.mediaOptions,s={echoCancellation:!0,noiseSuppression:t.noiseSuppression!==!1};t.audioDeviceId&&(s.deviceId={exact:t.audioDeviceId});let i=!1;if(e==="video"){let a={};t.videoDeviceId&&(a.deviceId={exact:t.videoDeviceId}),t.lowBandwidth&&(a.width={ideal:640},a.height={ideal:360},a.frameRate={ideal:15,max:20}),i=Object.keys(a).length?a:!0}let n=await navigator.mediaDevices.getUserMedia({audio:s,video:i});return t.startMuted&&n.getAudioTracks().forEach(a=>a.enabled=!1),t.startVideoOff&&n.getVideoTracks().forEach(a=>a.enabled=!1),this.localStream=n,n}async createPeerConnection(e,t){if(!Me)return null;if(!this.iceServersResolved&&this.getIceServers)try{this.iceServers=await this.getIceServers(),this.iceServersResolved=!0}catch(n){this.options.debug&&console.warn("Failed to fetch ICE servers, using defaults:",n),this.iceServersResolved=!0}let s=new RTCPeerConnection({iceServers:this.iceServers}),i={pc:s};return this.peers.set(e,i),s.ontrack=n=>{n.streams[0]&&(i.remoteStream=n.streams[0],this.emit("remote_stream",{userId:e,stream:n.streams[0]}))},s.onicecandidate=n=>{n.candidate&&this.emit("ice_candidate",{userId:e,candidate:n.candidate.toJSON()})},s.oniceconnectionstatechange=()=>{if(s.iceConnectionState==="connected"||s.iceConnectionState==="completed")this.mediaOptions.lowBandwidth&&this.setVideoBitrate(35e4),this.emit("peer_connected",{userId:e});else if(s.iceConnectionState==="failed"){let n=this.peers.get(e);n&&!n.hasRestartedIce&&typeof s.restartIce=="function"?(n.hasRestartedIce=!0,s.restartIce()):this.emit("ice_failed",{userId:e})}},s}async createOffer(e,t){let s=await this.getMedia(t),i=await this.createPeerConnection(e,t);if(!i)return null;s.getTracks().forEach(a=>i.addTrack(a,s));let n=await i.createOffer();return await i.setLocalDescription(n),n}async handleOffer(e,t,s){let i=await this.getMedia(s),n=await this.createPeerConnection(e,s);if(!n)return null;i.getTracks().forEach(r=>n.addTrack(r,i)),await n.setRemoteDescription(new RTCSessionDescription(t));let a=await n.createAnswer();return await n.setLocalDescription(a),a}async handleAnswer(e,t){let s=this.peers.get(e);s&&await s.pc.setRemoteDescription(new RTCSessionDescription(t))}async addIceCandidate(e,t){let s=this.peers.get(e);if(s)try{await s.pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){this.options.debug&&console.warn("addIceCandidate failed:",i)}}getLocalStream(){return this.localStream}getRemoteStream(e){var t;return(t=this.peers.get(e))==null?void 0:t.remoteStream}getAllRemoteStreams(){let e=new Map;for(let[t,s]of this.peers)s.remoteStream&&e.set(t,s.remoteStream);return e}async applyVideoConstraints(e){var s;let t=(s=this.localStream)==null?void 0:s.getVideoTracks()[0];if(t)try{await t.applyConstraints(e)}catch{}}async applyAudioConstraints(e){var s;let t=(s=this.localStream)==null?void 0:s.getAudioTracks()[0];if(t)try{await t.applyConstraints(e)}catch{}}async setVideoBitrate(e){for(let[,t]of this.peers){let s=t.pc.getSenders().find(n=>{var a;return((a=n.track)==null?void 0:a.kind)==="video"});if(!s)continue;let i=s.getParameters();(!i.encodings||i.encodings.length===0)&&(i.encodings=[{}]);for(let n of i.encodings)e==null?delete n.maxBitrate:n.maxBitrate=e;try{await s.setParameters(i)}catch{}}}async setLowBandwidth(e){this.mediaOptions.lowBandwidth=e,await this.applyVideoConstraints(e?{width:{max:640},height:{max:360},frameRate:{max:20}}:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}}),await this.setVideoBitrate(e?35e4:null)}async switchDevice(e,t){if(!this.localStream)return;let s=e==="video"?{video:{deviceId:{exact:t}}}:{audio:{deviceId:{exact:t}}},i=await navigator.mediaDevices.getUserMedia(s),n=e==="video"?i.getVideoTracks()[0]:i.getAudioTracks()[0];if(!n)return;let a=e==="video"?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];a&&(n.enabled=a.enabled);for(let[,r]of this.peers){let l=r.pc.getSenders().find(c=>{var h;return((h=c.track)==null?void 0:h.kind)===e});l&&await l.replaceTrack(n)}a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(n)}isScreenSharing(){return!!this.screenTrack}async startScreenShare(){var n,a;if(this.screenTrack)return!0;let e=navigator.mediaDevices;if(!e.getDisplayMedia)return!1;let t=await e.getDisplayMedia({video:!0,audio:!1}),s=t.getVideoTracks()[0];if(!s)return!1;this.cameraTrack=(a=(n=this.localStream)==null?void 0:n.getVideoTracks()[0])!=null?a:null;let i=!1;for(let[,r]of this.peers){let l=r.pc.getSenders().find(c=>{var h;return((h=c.track)==null?void 0:h.kind)==="video"});l&&(await l.replaceTrack(s),i=!0)}return i?(this.screenTrack=s,s.onended=()=>{this.stopScreenShare()},this.emit("screen_share_changed",{active:!0,stream:t}),!0):(s.stop(),!1)}async stopScreenShare(){var e;if(this.screenTrack){for(let[,t]of this.peers){let s=t.pc.getSenders().find(i=>{var n;return((n=i.track)==null?void 0:n.kind)==="video"||i.track===this.screenTrack});s&&await s.replaceTrack((e=this.cameraTrack)!=null?e:null)}this.screenTrack.stop(),this.screenTrack=null,this.emit("screen_share_changed",{active:!1})}}closePeer(e){let t=this.peers.get(e);t&&t.pc.signalingState!=="closed"&&t.pc.close(),this.peers.delete(e)}cleanup(){for(let[e]of this.peers)this.closePeer(e);this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.removeAllListeners()}async getCallStats(){let e={};for(let[,t]of this.peers)try{(await t.pc.getStats()).forEach(i=>{var a,r,l,c,h,u,d,y,m,w;let n=i;if(i.type==="inbound-rtp")e.packets_lost_in=((a=e.packets_lost_in)!=null?a:0)+((r=n.packetsLost)!=null?r:0),e.packets_received=((l=e.packets_received)!=null?l:0)+((c=n.packetsReceived)!=null?c:0),e.bytes_received=((h=e.bytes_received)!=null?h:0)+((u=n.bytesReceived)!=null?u:0),typeof n.jitter=="number"&&(e.jitter_ms=n.jitter*1e3);else if(i.type==="outbound-rtp")e.packets_sent=((d=e.packets_sent)!=null?d:0)+((y=n.packetsSent)!=null?y:0),e.bytes_sent=((m=e.bytes_sent)!=null?m:0)+((w=n.bytesSent)!=null?w:0);else if(i.type==="candidate-pair"&&i.state==="succeeded"){let A=i.currentRoundTripTime;typeof A=="number"&&(e.rtt_ms=A*1e3)}})}catch{}return e}setLocalAudioEnabled(e){this.localStream&&this.localStream.getAudioTracks().forEach(t=>t.enabled=e)}setLocalVideoEnabled(e){this.localStream&&this.localStream.getVideoTracks().forEach(t=>t.enabled=e)}},nt=6e4,rt=class extends k.default{constructor(e,t={}){var s,i;super(),this.ringTimeoutId=null,this.webRTC=null,this.callRole=null,this.currentCallType="video",this.participants=new Set,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.callConnectedEmitted=!1,this.conversationId=e,this.logger=new E((s=t.debug)!=null?s:!1),this.ringTimeoutMs=(i=t.ringTimeout)!=null?i:nt,this.submitCallQuality=t.submitCallQuality,N.isAvailable()&&(this.webRTC=new N({debug:t.debug,getIceServers:t.getIceServers}))}emitCallConnected(e,t,s){this.callConnectedEmitted||(this.callConnectedEmitted=!0,this.callStartedAt==null&&(this.callStartedAt=Date.now()),this.emit("call_connected",{localStream:e,remoteStream:t,remoteUserId:s}))}setSendCallHandler(e){this.sendCallHandler=e}setCallOptions(e){var t;(t=this.webRTC)==null||t.setMediaOptions(e)}listDevices(){return N.enumerateDevices()}applyVideoConstraints(e){return this.webRTC?this.webRTC.applyVideoConstraints(e):Promise.resolve()}applyAudioConstraints(e){return this.webRTC?this.webRTC.applyAudioConstraints(e):Promise.resolve()}switchDevice(e,t){return this.webRTC?this.webRTC.switchDevice(e,t):Promise.resolve()}setLowBandwidth(e){return this.webRTC?this.webRTC.setLowBandwidth(e):Promise.resolve()}startScreenShare(){return this.webRTC?this.webRTC.startScreenShare():Promise.resolve(!1)}stopScreenShare(){return this.webRTC?this.webRTC.stopScreenShare():Promise.resolve()}isScreenSharing(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.isScreenSharing())!=null?t:!1}setSubmitCallQuality(e){this.submitCallQuality=e}send(e){if(!this.sendCallHandler){let t=new Error("Call not connected. Join conversation first.");throw this.emit("call_error",{reason:"websocket_lost",message:t.message}),t}this.sendCallHandler(e)}clearRingTimeout(){this.ringTimeoutId&&(clearTimeout(this.ringTimeoutId),this.ringTimeoutId=null)}startCall(e="video"){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.callRole="caller",this.currentCallType=e;let t={type:"call_invite",conversation_id:this.conversationId,payload:{call_type:e}};this.send(t),this.logger.debug("call.invite sent",{conversation_id:this.conversationId,call_type:e}),this.ringTimeoutId=setTimeout(()=>{this.ringTimeoutId=null,this.logger.debug("call ring timeout - no answer"),this.endCall("no_answer"),this.emit("call_timeout",{reason:"no_answer"})},this.ringTimeoutMs)}acceptCall(){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.callRole="callee";let e={type:"call_accept",conversation_id:this.conversationId};this.send(e),this.logger.debug("call.accept sent",{conversation_id:this.conversationId})}joinCall(e="video"){this.callRole="joiner",this.currentCallType=e;let t={type:"call_join",conversation_id:this.conversationId};this.send(t),this.logger.debug("call.join sent",{conversation_id:this.conversationId})}rejectCall(e){this.clearRingTimeout();let t={type:"call_reject",conversation_id:this.conversationId,payload:e?{reason:e}:void 0};this.send(t),this.logger.debug("call.reject sent",{conversation_id:this.conversationId,reason:e})}endCall(e){this.clearRingTimeout();let t={type:"call_hangup",conversation_id:this.conversationId,payload:e?{reason:e}:void 0};this.send(t),this.logger.debug("call.hangup sent",{conversation_id:this.conversationId,reason:e})}handleCallInvite(e){this.currentCallType=e.call_type||"video",this.emit("call_invite",{callType:this.currentCallType,callerId:e.caller_id,callerName:e.caller_name})}async handleCallAccept(e){this.clearRingTimeout();let t=e==null?void 0:e.sender_id;if(this.participants.add(t!=null?t:"unknown"),this.webRTC&&t&&this.callRole==="caller")try{let s=await this.webRTC.createOffer(t,this.currentCallType);s&&(this.sendOffer(t,s),this.setupWebRTCEvents())}catch(s){this.logger.debug("WebRTC createOffer failed:",s),this.emit("call_error",{reason:"permission_denied",message:String(s)})}this.emit("call_accept",{accepterId:t})}async handleCallJoin(e){let t=e.joiner_id;if(t&&this.participants.add(t),this.webRTC&&t&&(this.callRole==="caller"||this.callRole==="callee"))try{let s=await this.webRTC.createOffer(t,this.currentCallType);s&&(this.sendOffer(t,s),this.setupWebRTCEvents())}catch(s){this.logger.debug("WebRTC createOffer for joiner failed:",s)}this.emit("call_join",{joinerId:e.joiner_id,joinerName:e.joiner_name})}handleCallReject(e){this.clearRingTimeout(),this.emit("call_reject",{reason:e==null?void 0:e.reason})}async handleCallHangup(e){var s;this.clearRingTimeout();let t=(s=e==null?void 0:e.reason)!=null?s:"user_hangup";await this.submitQualityAndCleanup(t),this.callRole=null,this.participants.clear(),this.emit("call_hangup",{endedBy:e==null?void 0:e.ended_by,reason:t})}handleCallParticipantLeft(e){var s;let t=e.left_user_id;t&&(this.participants.delete(t),(s=this.webRTC)==null||s.closePeer(t)),this.emit("peer_left",{userId:t})}handleCallError(e){this.clearRingTimeout(),this.emit("call_error",{code:e.code,message:e.message,details:e.details})}async handleCallOffer(e){var i;let t=(i=e.from_user_id)!=null?i:e.sender_id,s=e.sdp;if(!(!t||!s)){if(this.participants.add(t),this.webRTC&&(this.callRole==="callee"||this.callRole==="joiner"))try{this.setupWebRTCEvents();let n=await this.webRTC.handleOffer(t,s,this.currentCallType);if(n){this.sendAnswer(t,n);let a=this.webRTC.getLocalStream(),r=this.webRTC.getRemoteStream(t);a&&r&&this.emitCallConnected(a,r,t)}}catch(n){this.logger.debug("WebRTC handleOffer failed:",n),this.emit("call_error",{reason:"permission_denied",message:String(n)})}this.emit("call_offer",{sdp:s,fromUserId:t})}}async handleCallAnswer(e){var i;let t=(i=e.from_user_id)!=null?i:e.sender_id,s=e.sdp;if(!(!t||!s)){if(this.webRTC){await this.webRTC.handleAnswer(t,s);let n=this.webRTC.getLocalStream(),a=this.webRTC.getRemoteStream(t);n&&a&&this.emitCallConnected(n,a,t)}this.emit("call_answer",{sdp:s,fromUserId:t})}}async handleCallICECandidate(e){var i;let t=(i=e.from_user_id)!=null?i:e.sender_id,s=e.candidate;!t||!s||(this.webRTC&&await this.webRTC.addIceCandidate(t,s),this.emit("call_ice_candidate",{candidate:s,fromUserId:t}))}handleCallMute(e){this.emit("peer_mute",{userId:e==null?void 0:e.user_id})}handleCallUnmute(e){this.emit("peer_unmute",{userId:e==null?void 0:e.user_id})}handleVideoOff(e){this.emit("peer_video_off",{userId:e==null?void 0:e.user_id})}handleVideoOn(e){this.emit("peer_video_on",{userId:e==null?void 0:e.user_id})}setMuted(e){var s;(s=this.webRTC)==null||s.setLocalAudioEnabled(!e);let t=e?{type:"call_mute",conversation_id:this.conversationId}:{type:"call_unmute",conversation_id:this.conversationId};this.send(t),this.emit("local_mute_changed",{muted:e})}setVideoEnabled(e){var s;(s=this.webRTC)==null||s.setLocalVideoEnabled(e);let t=e?{type:"video_on",conversation_id:this.conversationId}:{type:"video_off",conversation_id:this.conversationId};this.send(t),this.emit("local_video_changed",{enabled:e})}getLocalStream(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.getLocalStream())!=null?t:null}getRemoteStream(e){var t;return(t=this.webRTC)==null?void 0:t.getRemoteStream(e)}getAllRemoteStreams(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.getAllRemoteStreams())!=null?t:new Map}sendOffer(e,t){let s={sdp:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_offer",conversation_id:this.conversationId,payload:s})}sendAnswer(e,t){let s={sdp:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_answer",conversation_id:this.conversationId,payload:s})}setupWebRTCEvents(){!this.webRTC||this.webRTCEventsSetup||(this.webRTCEventsSetup=!0,this.webRTC.on("ice_candidate",({userId:e,candidate:t})=>{let s={candidate:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_ice_candidate",conversation_id:this.conversationId,payload:s})}),this.webRTC.on("remote_stream",({userId:e,stream:t})=>{var i;let s=(i=this.webRTC)==null?void 0:i.getLocalStream();s&&this.emitCallConnected(s,t,e)}),this.webRTC.on("ice_failed",async()=>{await this.submitQualityAndCleanup("ice_failed"),this.emit("call_error",{reason:"ice_failed",message:"ICE connection failed"})}),this.webRTC.on("screen_share_changed",e=>this.emit("screen_share_changed",e)))}async submitQualityAndCleanup(e,t=!1){let s=this.webRTC,i={end_reason:e};this.callStartedAt!=null&&(i.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3));try{if(s){let n=await s.getCallStats();Object.assign(i,n)}}catch{}if(this.submitCallQuality)try{await this.submitCallQuality(this.conversationId,i,e)}catch(n){this.logger.debug("submitCallQuality failed:",n)}s==null||s.cleanup(),this.webRTC=t?null:N.isAvailable()?new N({}):null,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.callConnectedEmitted=!1}async getCallStats(){let e={};if(this.callStartedAt!=null&&(e.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3)),this.webRTC){let t=await this.webRTC.getCallStats();Object.assign(e,t)}return e}cleanup(){this.clearRingTimeout(),this.submitQualityAndCleanup("user_left",!0),this.webRTC=null,this.webRTCEventsSetup=!1,this.callRole=null,this.participants.clear(),this.removeAllListeners()}},at=class extends k.default{constructor(e,t=!1){var i,n,a;super(),this._isJoined=!1;let s=typeof t=="boolean"?{debug:t}:t;this.id=e,this.messageManager=new tt((i=s.debug)!=null?i:!1),this.typingManager=new st((n=s.debug)!=null?n:!1),this.callManager=new rt(e,{debug:(a=s.debug)!=null?a:!1,getIceServers:s.getIceServers}),this.callManager.on("call_invite",r=>this.emit("call_invite",r)),this.callManager.on("call_accept",r=>this.emit("call_accept",r)),this.callManager.on("call_join",r=>this.emit("call_join",r)),this.callManager.on("call_reject",r=>this.emit("call_reject",r)),this.callManager.on("call_hangup",r=>this.emit("call_hangup",r)),this.callManager.on("peer_left",r=>this.emit("peer_left",r)),this.callManager.on("peer_mute",r=>this.emit("peer_mute",r)),this.callManager.on("peer_unmute",r=>this.emit("peer_unmute",r)),this.callManager.on("peer_video_off",r=>this.emit("peer_video_off",r)),this.callManager.on("peer_video_on",r=>this.emit("peer_video_on",r)),this.callManager.on("local_mute_changed",r=>this.emit("local_mute_changed",r)),this.callManager.on("local_video_changed",r=>this.emit("local_video_changed",r)),this.callManager.on("screen_share_changed",r=>this.emit("screen_share_changed",r)),this.callManager.on("call_connected",r=>this.emit("call_connected",r)),this.callManager.on("call_error",r=>this.emit("call_error",r)),this.callManager.on("call_timeout",r=>this.emit("call_timeout",r)),this.messageManager.on("message",r=>{r.conversationId===this.id&&this.emit("message",r)}),this.messageManager.on("receipt",r=>{this.emit("receipt",r)}),this.typingManager.on("typing",r=>{r.conversationId===this.id&&this.emit("typing",{userId:r.userId,state:r.state})})}get isJoined(){return this._isJoined}setSendMessageHandler(e){this.sendMessageHandler=e}setSendTypingHandler(e){this.sendTypingHandler=e}setSendReadHandler(e){this.sendReadHandler=e}setSendCallHandler(e){this.callManager.setSendCallHandler(e)}setSubmitCallQuality(e){this.callManager.setSubmitCallQuality(e)}setFetchMessagesCallback(e){this.fetchMessagesCallback=e}async fetchMessages(e){var s;if(!this.fetchMessagesCallback)throw new Error("REST not configured. Set apiUrl in Vocantly config for fetchMessages() (token, API keys, or getRestHeaders).");let t=await this.fetchMessagesCallback({externalUserId:(s=e==null?void 0:e.externalUserId)!=null?s:"",cursor:e==null?void 0:e.cursor,limit:e==null?void 0:e.limit});return this.messageManager.trackMessageIdsFromHistory(this.id,t.messages.map(i=>i.id)),t}markJoined(){this._isJoined||(this._isJoined=!0,this.emit("joined",{conversation_id:this.id}))}markLeft(){this._isJoined&&(this._isJoined=!1,this.callManager.cleanup(),this.emit("left",{conversation_id:this.id}))}sendMessage(e,t="text",s){if(!this.sendMessageHandler){let a=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",a),a}if(!this._isJoined){let a=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",a),a}let i=ae();this.messageManager.createOptimisticMessage(this.id,i,e,t,s);let n={type:"message",conversation_id:this.id,payload:{message_id:i,content:e,message_type:t}};try{this.sendMessageHandler(n)}catch(a){let r=a instanceof Error?a:new Error("Failed to send message");throw this.emit("error",r),r}}handleIncomingMessage(e){this.messageManager.handleIncomingMessage(this.id,e)}handleReceipt(e,t,s){this.messageManager.handleReceipt(this.id,e,t,s)}handleTyping(e){e.state==="start"?this.typingManager.handleTypingStart(this.id,e.user_id):e.state==="stop"&&this.typingManager.handleTypingStop(this.id,e.user_id)}emitPresence(e){this.emit("presence",{userId:e.user_id,state:e.state})}clearMessages(){this.messageManager.clearConversation(this.id)}clearTyping(){this.typingManager.clearConversation(this.id)}startCall(e="video"){this.ensureJoinedForCall(),this.callManager.startCall(e)}acceptCall(){this.ensureJoinedForCall(),this.callManager.acceptCall()}joinCall(e){this.ensureJoinedForCall(),this.callManager.joinCall(e!=null?e:"video")}rejectCall(e){this.ensureJoinedForCall(),this.callManager.rejectCall(e)}endCall(e){this.ensureJoinedForCall(),this.callManager.endCall(e)}setMuted(e){this.ensureJoinedForCall(),this.callManager.setMuted(e)}setVideoEnabled(e){this.ensureJoinedForCall(),this.callManager.setVideoEnabled(e)}setCallOptions(e){this.callManager.setCallOptions(e)}listDevices(){return this.callManager.listDevices()}applyVideoConstraints(e){return this.callManager.applyVideoConstraints(e)}applyAudioConstraints(e){return this.callManager.applyAudioConstraints(e)}switchDevice(e,t){return this.callManager.switchDevice(e,t)}setLowBandwidth(e){return this.callManager.setLowBandwidth(e)}startScreenShare(){return this.ensureJoinedForCall(),this.callManager.startScreenShare()}stopScreenShare(){return this.callManager.stopScreenShare()}isScreenSharing(){return this.callManager.isScreenSharing()}getLocalStream(){return this.callManager.getLocalStream()}getRemoteStream(e){return this.callManager.getRemoteStream(e)}getAllRemoteStreams(){return this.callManager.getAllRemoteStreams()}getCallStats(){return this.callManager.getCallStats()}handleIncomingCallMessage(e,t){switch(e){case"call_invite":this.callManager.handleCallInvite(t||{});break;case"call_accept":this.callManager.handleCallAccept(t);break;case"call_join":this.callManager.handleCallJoin(t||{});break;case"call_reject":this.callManager.handleCallReject(t);break;case"call_hangup":this.callManager.handleCallHangup(t);break;case"call_participant_left":this.callManager.handleCallParticipantLeft(t||{});break;case"call_error":this.callManager.handleCallError(t||{});break;case"call_offer":this.callManager.handleCallOffer(t||{});break;case"call_answer":this.callManager.handleCallAnswer(t||{});break;case"call_ice_candidate":this.callManager.handleCallICECandidate(t||{});break;case"call_mute":this.callManager.handleCallMute(t||{});break;case"call_unmute":this.callManager.handleCallUnmute(t||{});break;case"video_off":this.callManager.handleVideoOff(t||{});break;case"video_on":this.callManager.handleVideoOn(t||{});break}}ensureJoinedForCall(){if(!this._isJoined)throw new Error("Conversation is not joined. Call join() first.")}startTyping(){if(!this.sendTypingHandler){let t=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",t),t}if(!this._isJoined){let t=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",t),t}let e={type:"typing_start",conversation_id:this.id};try{this.sendTypingHandler(e)}catch(t){let s=t instanceof Error?t:new Error("Failed to send typing_start");throw this.emit("error",s),s}}stopTyping(){if(!this.sendTypingHandler){let t=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",t),t}if(!this._isJoined){let t=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",t),t}let e={type:"typing_stop",conversation_id:this.id};try{this.sendTypingHandler(e)}catch(t){let s=t instanceof Error?t:new Error("Failed to send typing_stop");throw this.emit("error",s),s}}markRead(e){if(!this.sendReadHandler){let s=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",s),s}if(!this._isJoined){let s=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",s),s}let t={type:"read",conversation_id:this.id,payload:{message_id:e}};try{this.sendReadHandler(t)}catch(s){let i=s instanceof Error?s:new Error("Failed to send read receipt");throw this.emit("error",i),i}}},ot=class extends k.default{constructor(e,t=!1,s,i,n){super(),this.conversations=new Map,this.restFetcher=null,this.appId=null,this.iceServersCache=null,this.sendMessageHandler=e,this.sendTypingHandler=i,this.sendCallHandler=n,this.supportMessageHandler=s,this.debug=t,this.logger=new E(t)}setRestFetcher(e){if(this.restFetcher=e,e)for(let t of this.conversations.values())t.setSubmitCallQuality((s,i,n)=>this.submitCallQualityToApi(s,i,n))}setAppId(e){this.appId=e&&e.trim()||null,this.iceServersCache=null}getIceServersFetcher(){if(!(!this.restFetcher||!this.appId))return async()=>{var r;if(this.iceServersCache)return this.iceServersCache;let t=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/apps/${encodeURIComponent(this.appId)}/ice-servers`,s=await this.restFetcher.getHeaders(),i=await fetch(t,{method:"GET",headers:s});if(!i.ok)throw new Error(`ICE servers fetch failed: ${i.status}`);let n=await i.json();if(!n.success||!((r=n.data)!=null&&r.iceServers))throw new Error("Invalid ICE servers response");let a=n.data.iceServers;return this.iceServersCache=a,a}}setSupportMessageHandler(e){this.supportMessageHandler=e}setSendTypingHandler(e){this.sendTypingHandler=e;for(let t of this.conversations.values())t.setSendTypingHandler(e)}setSendCallHandler(e){this.sendCallHandler=e;for(let t of this.conversations.values())t.setSendCallHandler(e)}setSendReadHandler(e){this.sendReadHandler=e;for(let t of this.conversations.values())t.setSendReadHandler(e)}async list(e){var m,w,A;if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for list() and fetchMessages() (token, API keys, or getRestHeaders).");let t=this.restFetcher.apiUrl.replace(/\/$/,""),s=(m=e==null?void 0:e.externalUserId)==null?void 0:m.trim(),i=Math.min(Math.max(1,(w=e==null?void 0:e.limit)!=null?w:20),100),n=new URLSearchParams({limit:String(i)});s&&n.set("external_user_id",s),e!=null&&e.cursor&&n.set("cursor",e.cursor);let a=n.toString(),r=`${t}/sdk/conversations${a?`?${a}`:""}`,l=await this.restFetcher.getHeaders(),c=await fetch(r,{method:"GET",headers:l});if(!c.ok){let H=await c.text(),O={};try{O=JSON.parse(H)}catch{O={message:H}}throw new Error(O.message||`HTTP ${c.status}: ${H}`)}let h=await c.json();if(!h.success||!h.data)throw new Error(h.message||"Invalid response");let u=h.data,d=Array.isArray(u.conversations)?u.conversations:[],y=(A=u.pagination)!=null?A:{has_next_page:!1,next_cursor:null,limit:i};return{conversations:d,pagination:y}}async getMessages(e,t,s={}){var d;if(!(e!=null&&e.trim()))throw new Error("conversationId is required");if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for list() and fetchMessages().");let i=Math.min(Math.max(1,(d=s.limit)!=null?d:20),100),n=new URLSearchParams({limit:String(i)});t!=null&&t.trim()&&n.set("external_user_id",t.trim()),s.cursor&&n.set("cursor",s.cursor);let a=this.restFetcher.apiUrl.replace(/\/$/,""),r=n.toString(),l=`${a}/sdk/conversations/${encodeURIComponent(e.trim())}/messages${r?`?${r}`:""}`,c=await this.restFetcher.getHeaders(),h=await fetch(l,{method:"GET",headers:c});if(!h.ok){let y=await h.text(),m={};try{m=JSON.parse(y)}catch{m={message:y}}throw new Error(m.message||`HTTP ${h.status}: ${y}`)}let u=await h.json();if(!u.success||!u.data)throw new Error(u.message||"Invalid response");return{messages:u.data.messages||[],pagination:u.data.pagination||{has_next_page:!1,next_cursor:null,limit:i}}}async submitCallQualityToApi(e,t,s){if(!this.restFetcher)return;let n=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/conversations/${encodeURIComponent(e)}/call-quality`,a=await this.restFetcher.getHeaders(),r={end_reason:s};typeof t.duration_seconds=="number"&&(r.duration_seconds=t.duration_seconds),typeof t.packets_lost_in=="number"&&(r.packets_lost_in=t.packets_lost_in),typeof t.packets_lost_out=="number"&&(r.packets_lost_out=t.packets_lost_out),typeof t.packets_received=="number"&&(r.packets_received=t.packets_received),typeof t.packets_sent=="number"&&(r.packets_sent=t.packets_sent),typeof t.bytes_received=="number"&&(r.bytes_received=t.bytes_received),typeof t.bytes_sent=="number"&&(r.bytes_sent=t.bytes_sent),typeof t.jitter_ms=="number"&&(r.jitter_ms=t.jitter_ms),typeof t.rtt_ms=="number"&&(r.rtt_ms=t.rtt_ms);let l=await fetch(n,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok){let c=await l.text();throw this.logger.debug("submitCallQuality failed:",l.status,c),new Error(`Call quality submit failed: ${l.status}`)}}get(e){if(!e||e.length===0)throw new Error("Conversation ID is required");let t=this.conversations.get(e);return t||(t=new at(e,{debug:this.debug,getIceServers:this.getIceServersFetcher()}),this.sendMessageHandler&&t.setSendMessageHandler(this.sendMessageHandler),this.sendTypingHandler&&t.setSendTypingHandler(this.sendTypingHandler),this.sendCallHandler&&t.setSendCallHandler(this.sendCallHandler),this.sendReadHandler&&t.setSendReadHandler(this.sendReadHandler),this.conversations.set(e,t),this.logger.debug("Created conversation instance:",e)),this.restFetcher&&(t.setFetchMessagesCallback(s=>this.getMessages(e,s.externalUserId,{cursor:s.cursor,limit:s.limit})),t.setSubmitCallQuality((s,i,n)=>this.submitCallQualityToApi(s,i,n))),t}has(e){return this.conversations.has(e)}async join(e,t){if(!e||e.length===0)throw new Error("Conversation ID is required");this.get(e),await t(e),this.logger.debug("Join requested for conversation:",e)}async leave(e,t){if(!e||e.length===0)throw new Error("Conversation ID is required");let s=this.conversations.get(e);s?(s.clearTyping(),await t(e),s.markLeft(),this.logger.debug("Left conversation:",e)):(await t(e),this.logger.warn("Attempted to leave unknown conversation:",e))}routeIncomingMessage(e){var s;let t;switch(e.type){case"joined":t=((s=e.payload)==null?void 0:s.conversation_id)||e.conversation_id,t&&this.get(t).markJoined();break;case"message":if(t=e.conversation_id,t){let i=this.conversations.get(t);i?i.isJoined?i.handleIncomingMessage(e.payload):this.logger.warn("Received message for conversation that is not joined:",t):this.logger.warn("Received message for unknown conversation:",t)}break;case"typing":if(t=e.conversation_id,t){let i=this.conversations.get(t);i?i.isJoined?i.handleTyping(e.payload):this.logger.warn("Received typing indicator for conversation that is not joined:",t):this.logger.warn("Received typing indicator for unknown conversation:",t)}break;case"receipt":if(t=e.conversation_id,t){let i=this.conversations.get(t);if(i)if(i.isJoined){let n=e;i.handleReceipt(n.payload.message_id,n.payload.state,n.payload.user_id)}else this.logger.warn("Received receipt for conversation that is not joined:",t);else this.logger.warn("Received receipt for unknown conversation:",t)}break;case"support":break;case"presence":if(t=e.conversation_id,t){let i=this.conversations.get(t);i&&i.isJoined&&i.emitPresence(e.payload)}break;case"error":this.logger.error("Received error message:",e.error);break;case"call_invite":case"call_accept":case"call_join":case"call_reject":case"call_hangup":case"call_participant_left":case"call_error":case"call_offer":case"call_answer":case"call_ice_candidate":case"call_mute":case"call_unmute":case"video_off":case"video_on":if(t=e.conversation_id,t){let i=this.get(t),n="payload"in e?e.payload:void 0;i.handleIncomingCallMessage(e.type,n)}break}}routeSupportMessage(e){var i;if(!this.supportMessageHandler){this.logger.warn("Support message handler not set, ignoring support message");return}let t=e.conversation_id;if(!t){this.logger.warn("Support message missing conversation_id");return}let s=(i=e.payload)==null?void 0:i.event;if(!s){this.logger.warn("Support message missing event type");return}this.supportMessageHandler(t,s,e.payload)}remove(e){let t=this.conversations.get(e);t&&(t.markLeft(),t.clearMessages(),t.clearTyping(),this.conversations.delete(e),this.logger.debug("Removed conversation instance:",e))}getAllIds(){return Array.from(this.conversations.keys())}clear(){for(let e of this.conversations.values())e.markLeft(),e.clearMessages(),e.clearTyping();this.conversations.clear(),this.logger.debug("Cleared all conversations")}},ct=class extends k.default{constructor(e=!1){super(),this.presenceState=new Map,this.logger=new E(e)}handlePresence(e,t){if(!e){this.logger.warn("Invalid presence event: missing userId");return}if(t!=="online"&&t!=="offline"){this.logger.warn("Invalid presence state:",t);return}this.presenceState.get(e)!==t?(this.presenceState.set(e,t),this.emit("presence",{userId:e,state:t}),this.logger.debug("Presence changed:",e,t)):this.logger.debug("Duplicate presence event ignored:",e,t)}getPresence(e){return this.presenceState.get(e)}getPresences(e){let t=new Map;for(let s of e){let i=this.presenceState.get(s);i&&t.set(s,i)}return t}clearPresence(e){let t=this.presenceState.has(e);this.presenceState.delete(e),t&&this.logger.debug("Cleared presence for user:",e)}clear(){this.presenceState.clear(),this.logger.debug("Cleared all presence state")}},lt=class extends k.default{constructor(e,t,s,i=!1){super(),this.botActive=!1,this.status="queued",this.conversationId=e,this.conversation=t,this.role=s,this.logger=new E(i),this.conversation.on("message",n=>this.emit("message",n)),this.conversation.on("typing",n=>this.emit("typing",n)),this.conversation.on("presence",n=>this.emit("presence",n)),this.conversation.on("joined",n=>this.emit("joined",n)),this.conversation.on("left",n=>this.emit("left",n)),this.conversation.on("error",n=>this.emit("error",n))}getConversation(){return this.conversation}isCustomer(){return this.role==="customer"}isAgent(){return this.role==="agent"}getRole(){return this.role}isBotActive(){return this.botActive}getAssignedAgent(){return this.assignedAgentId}getStatus(){return this.status}handleAssigned(e){if(this.assignedAgentId===e)return;let t=this.assignedAgentId,s=t!==void 0;this.assignedAgentId=e,this.status==="queued"?this.status="assigned":this.status==="assigned"||this.status,s?(this.emit("assigned",{agentId:e,previousAgentId:t}),this.logger.debug("Support session reassigned:",this.conversationId,e,"from",t)):(this.emit("assigned",{agentId:e}),this.logger.debug("Support session assigned:",this.conversationId,e))}handleUnassigned(){if(this.assignedAgentId===void 0)return;let e=this.assignedAgentId;this.assignedAgentId=void 0,(this.status==="assigned"||this.status==="active")&&(this.status="queued"),this.emit("unassigned",{previousAgentId:e}),this.logger.debug("Support session unassigned:",this.conversationId)}handleBotTakeover(){this.botActive||(this.botActive=!0,this.emit("bot_takeover",{}),this.logger.debug("Bot took over support session:",this.conversationId))}handleBotReleased(){this.botActive&&(this.botActive=!1,this.emit("bot_released",{}),this.logger.debug("Bot released support session:",this.conversationId))}handleClosed(){if(this.status==="closed")return;let e=this.status;this.status="closed",this.emit("closed",{previousStatus:e}),this.logger.debug("Support session closed:",this.conversationId)}handleReopened(){this.status==="closed"&&(this.status=this.assignedAgentId?"assigned":"queued",this.emit("reopened",{}),this.logger.debug("Support session reopened:",this.conversationId))}sendMessage(e,t="text",s){this.conversation.sendMessage(e,t,s)}async join(){}async leave(){}},dt=class extends k.default{constructor(e,t=!1){super(),this.sessions=new Map,this.getConversationHandler=e,this.debug=t,this.logger=new E(t)}get(e,t="customer"){if(!e||e.length===0)throw new Error("Conversation ID is required");let s=this.sessions.get(e);if(!s){let i=this.getConversationHandler(e);s=new lt(e,i,t,this.debug),s.on("assigned",n=>this.emit("assigned",{conversationId:e,...n})),s.on("unassigned",n=>this.emit("unassigned",{conversationId:e,...n})),s.on("bot_takeover",()=>this.emit("bot_takeover",{conversationId:e})),s.on("bot_released",()=>this.emit("bot_released",{conversationId:e})),s.on("closed",n=>this.emit("closed",{conversationId:e,...n})),s.on("reopened",()=>this.emit("reopened",{conversationId:e})),this.sessions.set(e,s),this.logger.debug("Created support session:",e,t)}return s}has(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}handleSupportEvent(e,t,s){let i=this.sessions.get(e);if(!i){t==="assigned"&&(s!=null&&s.agent_id)?this.logger.debug("Support event for unknown session, will be handled when session is created:",e):this.logger.warn("Support event for unknown session:",e,t);return}switch(t){case"assigned":s!=null&&s.agent_id&&typeof s.agent_id=="string"&&i.handleAssigned(s.agent_id);break;case"unassigned":i.handleUnassigned();break;case"bot_takeover":i.handleBotTakeover();break;case"bot_released":i.handleBotReleased();break;case"closed":i.handleClosed();break;case"reopened":i.handleReopened();break}}remove(e){this.sessions.get(e)&&(this.sessions.delete(e),this.logger.debug("Removed support session:",e))}clear(){this.sessions.clear(),this.logger.debug("Cleared all support sessions")}},Re=class extends k.default{constructor(e){var a,r;super(),this.connectionState="disconnected",this.wsClient=null,this.config={autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,debug:!1,apiUrl:"",...e},this.tokenManager=new Ze,this.tokenManager.setToken(e.token),this.logger=new E(this.config.debug),this.wsClient=new Xe(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new dt(l=>this.conversationManager.get(l),this.config.debug),this.conversationManager=new ot(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},this.config.debug,void 0,l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.conversationManager.setSendReadHandler(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.presenceManager=new ct(this.config.debug),this.presenceManager.on("presence",l=>{this.emit("presence",l)});let t=(a=this.config.apiUrl)==null?void 0:a.trim(),s=(r=this.config.appId)==null?void 0:r.trim(),i=this.config.apiKey&&this.config.apiSecret,n=typeof this.config.getRestHeaders=="function";if(t){let l=async()=>{if(n&&this.config.getRestHeaders)return this.config.getRestHeaders();if(i)return{"X-Api-Key":this.config.apiKey,"X-Api-Secret":this.config.apiSecret,"Content-Type":"application/json"};let c=this.tokenManager.getToken();if(!c)throw new Error("Token required for list() and fetchMessages() when API keys are not set");return{Authorization:`Bearer ${c}`,"Content-Type":"application/json"}};this.conversationManager.setRestFetcher({apiUrl:t,getHeaders:l}),s&&this.conversationManager.setAppId(s)}this.setupWebSocketHandlers()}setupWebSocketHandlers(){this.wsClient&&(this.wsClient.on("connected",()=>{this.connectionState="connected",this.emit("connected"),this.emit("state",this.connectionState),this.logger.debug("SDK connected")}),this.wsClient.on("disconnected",e=>{this.connectionState="disconnected",this.emit("disconnected",e),this.emit("state",this.connectionState),this.logger.debug("SDK disconnected")}),this.wsClient.on("reconnecting",e=>{this.connectionState="reconnecting",this.emit("reconnecting",e),this.emit("state",this.connectionState),this.logger.debug("SDK reconnecting",e)}),this.wsClient.on("message",e=>{if(this.emit("message",e),this.conversationManager.routeIncomingMessage(e),e.type==="presence"){let t=e;t.payload&&this.presenceManager.handlePresence(t.payload.user_id,t.payload.state)}switch(e.type==="support"&&this.conversationManager.routeSupportMessage(e),e.type){case"joined":this.emit("joined",e);break;case"message":this.emit("message",e);break;case"typing":this.emit("typing",e);break;case"receipt":break;case"support":break;case"presence":break;case"error":this.emit("error",e);break}}),this.wsClient.on("error",e=>{this.connectionState="error";let t=e instanceof Error?e.message:"";(e instanceof Error?e.name:"")==="TokenExpiredError"||t&&t.includes("Token expired")?(this.logger.error("Token expired:",t),this.logger.warn("To reconnect, call sdk.updateToken(newToken) then sdk.connect()")):this.logger.error("SDK error:",e);let i=e instanceof Error?e:new Error("WebSocket connection error");this.emit("error",i),this.emit("state",this.connectionState)}))}getState(){return this.connectionState}getConfig(){return{...this.config}}async connect(){if(this.connectionState==="connected"){this.logger.warn("Already connected");return}if(this.connectionState==="connecting"){this.logger.warn("Connection already in progress");return}this.tokenManager.validateTokenPresence();let e=this.tokenManager.getToken();if(!e)throw new Error("Token is required for connection");this.connectionState="connecting",this.emit("state",this.connectionState),this.logger.debug("Connecting...");try{if(!this.wsClient)throw new Error("WebSocket client not initialized");await this.wsClient.connect(e)}catch(t){this.connectionState="error",this.emit("state",this.connectionState);let s=t instanceof Error?t:new Error("Connection failed");throw this.emit("error",s),s}}async disconnect(){this.connectionState!=="disconnected"&&(this.logger.debug("Disconnecting..."),this.conversationManager.clear(),this.presenceManager.clear(),this.supportManager.clear(),this.wsClient&&this.wsClient.disconnect(),this.connectionState="disconnected",this.emit("disconnected"),this.emit("state",this.connectionState))}isConnected(){var e;return this.connectionState==="connected"&&((e=this.wsClient)==null?void 0:e.isConnected())===!0}updateToken(e){if(!e||e.length===0)throw new Error("Token cannot be empty");this.tokenManager.setToken(e),this.logger.debug("Token updated"),this.isConnected()&&(this.logger.warn("Token updated while connected. Disconnecting to reconnect with new token..."),this.disconnect())}get conversations(){return{get:e=>this.conversationManager.get(e),has:e=>this.conversationManager.has(e),join:e=>this.conversationManager.join(e,t=>this.joinConversation(t)),leave:e=>this.conversationManager.leave(e,t=>this.leaveConversation(t)),list:e=>this.conversationManager.list(e)}}get support(){return{get:(e,t="customer")=>this.supportManager.get(e,t),has:e=>this.supportManager.has(e)}}async joinConversation(e){if(!this.isConnected())throw new Error("Must be connected before joining a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"join",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Join conversation sent:",e)}catch(s){let i=s instanceof Error?s:new Error("Failed to join conversation");throw this.emit("error",i),i}}async leaveConversation(e){if(!this.isConnected())throw new Error("Must be connected before leaving a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"leave",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Leave conversation sent:",e)}catch(s){let i=s instanceof Error?s:new Error("Failed to leave conversation");throw this.emit("error",i),i}}rotateToken(e){this.tokenManager.rotateToken(e),this.logger.debug("Token rotated"),this.isConnected()&&this.logger.warn("Token rotated while connected. Reconnect may be required.")}getTokenManager(){return this.tokenManager}};var gt={wsUrl:"",token:"",conversationId:"",publicKey:"",title:"Support",subtitle:"We typically reply in a few minutes",greeting:"Hi! \u{1F44B} How can we help you today?",placeholder:"Type your message\u2026",primaryColor:"#195EFF",position:"bottom-right",launcher:"\u{1F4AC}",autoOpen:!1,debug:!1,collectContact:!1,requireEmail:!1,contactPrompt:"Let\u2019s get you connected",csat:!0,csatPrompt:"How would you rate the support you received?",csatThanks:"Thanks for the feedback!",calls:!1,callBundleUrl:"https://cdn.jsdelivr.net/npm/@vocantly/widget@0.1.12/dist/vocantly-widget-call.js"},_=null;function Ae(e){try{let t=JSON.parse(atob(e.split(".")[1]));return t.user_id||t.sub||null}catch{return null}}function R(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Oe(e){return R(e).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>").replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\n/g,"<br>")}var q=null;function pt(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;q=q||new e,q.resume&&q.resume();let t=q,s=t.currentTime,i=t.createOscillator(),n=t.createGain();i.type="sine",i.frequency.setValueAtTime(880,s),i.frequency.exponentialRampToValueAtTime(1320,s+.08),n.gain.setValueAtTime(1e-4,s),n.gain.exponentialRampToValueAtTime(.16,s+.02),n.gain.exponentialRampToValueAtTime(1e-4,s+.34),i.connect(n).connect(t.destination),i.start(s),i.stop(s+.36)}catch{}}function ut(e,t){if(document.getElementById("caf-widget-styles"))return;let a=`
1
+ var Ke=Object.create;var G=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var _e=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},Ze=(e,t)=>{for(var i in t)G(e,i,{get:t[i],enumerable:!0})},Te=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ye(t))!Xe.call(e,n)&&n!==i&&G(e,n,{get:()=>t[n],enumerable:!(s=Qe(t,n))||s.enumerable});return e};var ne=(e,t,i)=>(i=e!=null?Ke(Ge(e)):{},Te(t||!e||!e.__esModule?G(i,"default",{value:e,enumerable:!0}):i,e)),et=e=>Te(G({},"__esModule",{value:!0}),e);var Ee=_e((Dt,re)=>{"use strict";var tt=Object.prototype.hasOwnProperty,_="~";function V(){}Object.create&&(V.prototype=Object.create(null),new V().__proto__||(_=!1));function it(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function Me(e,t,i,s,n){if(typeof i!="function")throw new TypeError("The listener must be a function");var a=new it(i,s||e,n),r=_?_+t:t;return e._events[r]?e._events[r].fn?e._events[r]=[e._events[r],a]:e._events[r].push(a):(e._events[r]=a,e._eventsCount++),e}function X(e,t){--e._eventsCount===0?e._events=new V:delete e._events[t]}function S(){this._events=new V,this._eventsCount=0}S.prototype.eventNames=function(){var t=[],i,s;if(this._eventsCount===0)return t;for(s in i=this._events)tt.call(i,s)&&t.push(_?s.slice(1):s);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(i)):t};S.prototype.listeners=function(t){var i=_?_+t:t,s=this._events[i];if(!s)return[];if(s.fn)return[s.fn];for(var n=0,a=s.length,r=new Array(a);n<a;n++)r[n]=s[n].fn;return r};S.prototype.listenerCount=function(t){var i=_?_+t:t,s=this._events[i];return s?s.fn?1:s.length:0};S.prototype.emit=function(t,i,s,n,a,r){var c=_?_+t:t;if(!this._events[c])return!1;var l=this._events[c],p=arguments.length,m,f;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),p){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,i),!0;case 3:return l.fn.call(l.context,i,s),!0;case 4:return l.fn.call(l.context,i,s,n),!0;case 5:return l.fn.call(l.context,i,s,n,a),!0;case 6:return l.fn.call(l.context,i,s,n,a,r),!0}for(f=1,m=new Array(p-1);f<p;f++)m[f-1]=arguments[f];l.fn.apply(l.context,m)}else{var y=l.length,v;for(f=0;f<y;f++)switch(l[f].once&&this.removeListener(t,l[f].fn,void 0,!0),p){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,i);break;case 3:l[f].fn.call(l[f].context,i,s);break;case 4:l[f].fn.call(l[f].context,i,s,n);break;default:if(!m)for(v=1,m=new Array(p-1);v<p;v++)m[v-1]=arguments[v];l[f].fn.apply(l[f].context,m)}}return!0};S.prototype.on=function(t,i,s){return Me(this,t,i,s,!1)};S.prototype.once=function(t,i,s){return Me(this,t,i,s,!0)};S.prototype.removeListener=function(t,i,s,n){var a=_?_+t:t;if(!this._events[a])return this;if(!i)return X(this,a),this;var r=this._events[a];if(r.fn)r.fn===i&&(!n||r.once)&&(!s||r.context===s)&&X(this,a);else{for(var c=0,l=[],p=r.length;c<p;c++)(r[c].fn!==i||n&&!r[c].once||s&&r[c].context!==s)&&l.push(r[c]);l.length?this._events[a]=l.length===1?l[0]:l:X(this,a)}return this};S.prototype.removeAllListeners=function(t){var i;return t?(i=_?_+t:t,this._events[i]&&X(this,i)):(this._events=new V,this._eventsCount=0),this};S.prototype.off=S.prototype.removeListener;S.prototype.addListener=S.prototype.on;S.prefixed=_;S.EventEmitter=S;typeof re!="undefined"&&(re.exports=S)});var Ie=_e((Kt,Ae)=>{"use strict";Ae.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Ut={};Ze(Ut,{close:()=>Ot,destroy:()=>Ht,init:()=>It,open:()=>jt});module.exports=et(Ut);var M=ne(Ee(),1);var x=[];for(Z=0;Z<256;++Z)x.push((Z+256).toString(16).slice(1));var Z;function Re(e,t=0){return(x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+"-"+x[e[t+4]]+x[e[t+5]]+"-"+x[e[t+6]]+x[e[t+7]]+"-"+x[e[t+8]]+x[e[t+9]]+"-"+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]).toLowerCase()}var ee,st=new Uint8Array(16);function ae(){if(!ee&&(ee=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ee))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ee(st)}var nt=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),oe={randomUUID:nt};function rt(e,t,i){if(oe.randomUUID&&!t&&!e)return oe.randomUUID();e=e||{};var s=e.random||(e.rng||ae)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,t){i=i||0;for(var n=0;n<16;++n)t[i+n]=s[n];return t}return Re(s)}var te=rt;var _t={},at=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,i)=>(typeof require!="undefined"?require:t)[i]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var j=class{constructor(e=!1){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[Vocantly SDK]",...e)}info(...e){this.enabled&&console.info("[Vocantly SDK]",...e)}warn(...e){this.enabled&&console.warn("[Vocantly SDK]",...e)}error(...e){this.enabled&&console.error("[Vocantly SDK]",...e)}},ce=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,D=null,N=null;async function ot(){return ce?D||N||(N=(async()=>{try{try{return D=await Promise.resolve().then(()=>ne(Ie(),1)),D}catch(e){if(typeof at!="undefined"){let{createRequire:t}=await import("module");return D=t(_t.url||__filename)("ws"),D}throw e}}catch{return null}finally{N=null}})(),N):null}var ct=class extends M.default{constructor(e,t={}){var i,s,n;super(),this.ws=null,this.token=null,this.reconnectAttempts=0,this.reconnectTimer=null,this.isManuallyDisconnected=!1,this.isTokenExpired=!1,this.url=e,this.autoReconnect=(i=t.autoReconnect)!=null?i:!0,this.maxReconnectAttempts=(s=t.maxReconnectAttempts)!=null?s:5,this.logger=new j((n=t.debug)!=null?n:!1)}connect(e){if(!e||e.length===0){let t=new Error("Token is required for connection");return this.emit("error",t),Promise.reject(t)}return this.token=e,this.isManuallyDisconnected=!1,this.isTokenExpired=!1,this.attemptConnection()}async attemptConnection(){var i;let e=new URL(this.url),t=(i=this.token)!=null?i:"";if(ce){let s=await ot();if(this.logger.debug("ws module loaded:",!!s),s&&s.WebSocket)return this.logger.debug("Using ws package with Authorization header"),new Promise((n,a)=>{try{let r=new s.WebSocket(e.toString(),{headers:{Authorization:`Bearer ${t}`}});this.ws=r;let c=!1,l=p=>{if(c)return;c=!0;let m=String((p==null?void 0:p.message)||p||"").toLowerCase();if(m.includes("401")||m.includes("unauthorized")||p!=null&&p.code&&String(p.code).includes("401")){this.handleTokenExpiration();let f=new Error("Token expired or invalid. Please refresh your token and reconnect.");f.name="TokenExpiredError",this.emit("error",f),a(f);return}};typeof r.addEventListener=="function"?(r.addEventListener("error",l),r.addEventListener("open",()=>{r.removeEventListener("error",l)})):typeof r.once=="function"&&(r.once("error",l),r.once("open",()=>{})),this.setupEventHandlers(n,a)}catch(r){this.logger.error("Failed to create ws.WebSocket:",r),a(r)}});this.logger.warn("ws package not available, falling back to native WebSocket")}return this.logger.debug("Using native WebSocket with query parameter",{url:e.toString(),hasToken:!!t}),new Promise((s,n)=>{try{if(!t||t.length===0){let c=new Error("Token is required for WebSocket connection");this.logger.error(c.message),n(c);return}let a=new URL(e.toString());a.searchParams.set("token",t),this.ws=new globalThis.WebSocket(a.toString()),this.logger.debug("WebSocket instance created",{readyState:this.ws.readyState,url:this.ws.url,protocol:this.ws.protocol});let r=this.ws;this.setupEventHandlers(s,n),setTimeout(()=>{(r.readyState===WebSocket.CLOSED||r.readyState===WebSocket.CLOSING)&&this.logger.warn("WebSocket closed immediately after creation",{readyState:r.readyState,url:r.url})},100)}catch(a){this.logger.error("Failed to create native WebSocket:",a),n(a)}})}setupEventHandlers(e,t){this.ws&&(this.ws.onopen=()=>{this.reconnectAttempts=0,this.isTokenExpired=!1;let i=this.ws;if(!i){this.logger.error("WebSocket is null in onopen handler"),t(new Error("WebSocket instance lost"));return}if(this.logger.debug("WebSocket connected",{readyState:i.readyState,url:i.url,protocol:i.protocol,extensions:i.extensions}),i.readyState!==WebSocket.OPEN){this.logger.error("WebSocket readyState is not OPEN after onopen",{readyState:i.readyState}),t(new Error(`WebSocket not open: readyState=${i.readyState}`));return}this.emit("connected"),e()},this.ws.onmessage=i=>{try{let s=JSON.parse(i.data);this.logger.debug("Received message:",s),this.emit("message",s)}catch(s){let n=s instanceof Error?s:new Error("Failed to parse message");this.logger.error("Failed to parse message:",n),this.emit("error",n)}},this.ws.onerror=i=>{this.logger.error("WebSocket error:",i);let s;if(i instanceof Error?s=i:i&&i.message?s=i instanceof Error?i:new Error(String(i.message)):s=new Error("WebSocket connection error"),ce&&i&&i.message){let n=String(i.message).toLowerCase();if(n.includes("401")||n.includes("unauthorized")){this.handleTokenExpiration();let a=new Error("Token expired or invalid. Please refresh your token and reconnect.");a.name="TokenExpiredError",this.emit("error",a),t(a);return}}this.emit("error",s)},this.ws.onclose=i=>{if(this.logger.debug("WebSocket closed:",{code:i.code,reason:i.reason,wasClean:i.wasClean}),i.code===1006&&this.logger.warn("Abnormal closure (1006) - connection closed without proper handshake. Possible causes: network issue, server closed connection, CORS issue, or protocol mismatch."),i.code===1008||i.code===1002||i.reason&&i.reason.toLowerCase().includes("unauthorized")||i.reason&&i.reason.toLowerCase().includes("401")){this.handleTokenExpiration();let n=new Error("Token expired or invalid. Please refresh your token and reconnect.");n.name="TokenExpiredError",this.emit("error",n),this.emit("disconnected",{code:i.code,reason:i.reason,tokenExpired:!0});return}this.emit("disconnected",{code:i.code,reason:i.reason}),!this.isManuallyDisconnected&&!this.isTokenExpired&&this.autoReconnect?this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():(this.logger.warn("Max reconnection attempts reached"),this.emit("error",new Error("Max reconnection attempts reached"))):this.isTokenExpired&&this.logger.warn("Not reconnecting: token is expired")})}handleTokenExpiration(){this.isTokenExpired=!0,this.autoReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}disconnect(){this.isManuallyDisconnected=!0,this.autoReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.logger.debug("WebSocket disconnected")}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){let t=new Error("WebSocket is not connected");throw this.logger.error(t.message),this.emit("error",t),t}try{let t=JSON.stringify(e);this.logger.debug("Sending message:",e),this.ws.send(t)}catch(t){let i=t instanceof Error?t:new Error("Failed to send message");throw this.logger.error("Send error:",i),this.emit("error",i),i}}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getReconnectAttempts(){return this.reconnectAttempts}scheduleReconnect(){if(this.reconnectTimer||!this.token)return;this.reconnectAttempts++;let e=[1e3,2e3,5e3,1e4],t=e[Math.min(this.reconnectAttempts-1,e.length-1)];this.logger.debug(`Scheduling reconnect attempt ${this.reconnectAttempts} in ${t}ms`),this.emit("reconnecting",{attempt:this.reconnectAttempts,delay:t}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.attemptConnection().catch(()=>{})},t)}},lt=class{constructor(){this.token=null}setToken(e){if(!this.isValidFormat(e))throw new Error("Invalid token format");this.token=e}getToken(){return this.token}hasToken(){return this.token!==null&&this.token.length>0}clearToken(){this.token=null}rotateToken(e){if(!this.isValidFormat(e))throw new Error("Invalid token format");this.token=e}isValidFormat(e){return typeof e=="string"&&e.length>0}validateTokenPresence(){if(!this.hasToken())throw new Error("Token is required but not set")}},dt=new Set(["text","system","image","video","file"]);function je(e){return e&&dt.has(e)?e:"text"}var z=class{static createOptimistic(e,t,i,s="text",n,a){return{id:t,conversationId:e,content:i,messageType:s,optimistic:!0,receiptState:"sent",createdAt:new Date,metadata:n,attachments:a}}static fromServerPayload(e,t){var n,a;let i=(n=t.sender_id)!=null?n:t.senderId,s=(a=t.sender_type)!=null?a:t.senderType;return{id:t.message_id,conversationId:e,content:t.content,senderId:i,senderName:t.sender_name,senderType:s,messageType:je(t.message_type),optimistic:!1,receiptState:"sent",createdAt:t.sent_at?new Date(t.sent_at):new Date,attachments:t.attachments}}static confirmOptimistic(e,t){var n,a,r,c;let i=(n=t.sender_id)!=null?n:t.senderId,s=(a=t.sender_type)!=null?a:t.senderType;return{...e,optimistic:!1,senderId:i,senderName:t.sender_name,senderType:s,messageType:je(t.message_type),receiptState:(r=e.receiptState)!=null?r:"sent",createdAt:t.sent_at?new Date(t.sent_at):e.createdAt,attachments:(c=t.attachments)!=null?c:e.attachments}}static updateReceiptState(e,t){return{...e,receiptState:t}}},ht=class extends M.default{constructor(e=!1){super(),this.receiptState=new Map,this.logger=new j(e)}getReceiptState(e){return this.receiptState.get(e)}handleDelivered(e,t){var s;if(!e)return this.logger.warn("Invalid delivered receipt: missing messageId"),!1;let i=(s=this.receiptState.get(e))!=null?s:"sent";return this.compareStates(i,"delivered")<0?(this.receiptState.set(e,"delivered"),this.emit("receipt",{messageId:e,state:"delivered",userId:t}),this.logger.debug("Receipt delivered:",e),!0):(this.logger.debug("Delivered receipt ignored (already delivered or read):",e),!1)}handleRead(e,t){var s;if(!e)return this.logger.warn("Invalid read receipt: missing messageId"),!1;let i=(s=this.receiptState.get(e))!=null?s:"sent";return this.compareStates(i,"read")<0?(this.receiptState.set(e,"read"),this.emit("receipt",{messageId:e,state:"read",userId:t}),this.logger.debug("Receipt read:",e),!0):(this.logger.debug("Read receipt ignored (already read):",e),!1)}compareStates(e,t){let i=["sent","delivered","read"],s=i.indexOf(e),n=i.indexOf(t);return s===-1||n===-1?0:s-n}clearConversation(e,t){let i=0;for(let s of t)this.receiptState.has(s)&&(this.receiptState.delete(s),i++);i>0&&this.logger.debug("Cleared receipt state for conversation:",e,`(${i} messages)`)}clearMessage(e){this.receiptState.delete(e)&&this.logger.debug("Cleared receipt state for message:",e)}clear(){this.receiptState.clear(),this.logger.debug("Cleared all receipt state")}},pt=class extends M.default{constructor(e=!1){super(),this.seenMessageIds=new Map,this.optimisticMessages=new Map,this.confirmedMessages=new Map,this.warnedMissingSenderId=new Set,this.logger=new j(e),this.receiptManager=new ht(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,i,s="text",n,a){let r=z.createOptimistic(e,t,i,s,n,a);return this.trackOptimisticMessage(e,t,r),this.trackMessageId(e,t),this.emit("message",r),this.logger.debug("Created optimistic message:",t),r}handleIncomingMessage(e,t){let i=t.message_id,s=this.getOptimisticMessage(e,i);if(s){let a=this.reconcileOptimisticMessage(s,t);return a.senderId==null&&!this.warnedMissingSenderId.has(e)&&(this.warnedMissingSenderId.add(e),console.warn('[Vocantly SDK] Message payload missing sender_id (and sender_type). Clients cannot show "You" vs other participant. The realtime backend MUST include sender_id and sender_type in every type:"message" payload. See docs/REALTIME_WEBSOCKET_CONTRACT.md.')),this.removeOptimisticMessage(e,i),this.trackMessageId(e,i),this.trackConfirmedMessage(e,i,a),a}if(this.hasSeenMessage(e,i))return this.logger.debug("Duplicate message ignored:",i),null;this.trackMessageId(e,i);let n=z.fromServerPayload(e,t);return n.senderId==null&&!this.warnedMissingSenderId.has(e)&&(this.warnedMissingSenderId.add(e),console.warn('[Vocantly SDK] Message payload missing sender_id (and sender_type). Clients cannot show "You" vs other participant. The realtime backend MUST include sender_id and sender_type in every type:"message" payload. See docs/REALTIME_WEBSOCKET_CONTRACT.md.')),this.trackConfirmedMessage(e,i,n),this.emit("message",n),this.logger.debug("Handled incoming message:",i),n}handleReceipt(e,t,i,s){i==="delivered"?this.receiptManager.handleDelivered(t,s):i==="read"&&this.receiptManager.handleRead(t,s)}updateMessageReceiptState(e){for(let[,t]of this.confirmedMessages.entries()){let i=t.get(e.messageId);if(i){let s=z.updateReceiptState(i,e.state);t.set(e.messageId,s),this.emit("message",s),this.logger.debug("Updated message receipt state:",e.messageId,e.state);return}}for(let[,t]of this.optimisticMessages.entries()){let i=t.get(e.messageId);if(i){let s=z.updateReceiptState(i,e.state);t.set(e.messageId,s),this.emit("message",s),this.logger.debug("Updated optimistic message receipt state:",e.messageId,e.state);return}}this.logger.warn("Receipt for unknown message:",e.messageId)}reconcileOptimisticMessage(e,t){let i=z.confirmOptimistic(e,t);return this.logger.debug("Reconciled optimistic message (no second emit):",e.id),i}hasSeenMessage(e,t){var s;let i=this.seenMessageIds.get(e);return(s=i==null?void 0:i.has(t))!=null?s:!1}trackMessageIdsFromHistory(e,t){for(let i of t)this.trackMessageId(e,i)}trackMessageId(e,t){let i=this.seenMessageIds.get(e);i||(i=new Set,this.seenMessageIds.set(e,i)),i.add(t)}trackOptimisticMessage(e,t,i){let s=this.optimisticMessages.get(e);s||(s=new Map,this.optimisticMessages.set(e,s)),s.set(t,i)}getOptimisticMessage(e,t){let i=this.optimisticMessages.get(e);return i==null?void 0:i.get(t)}removeOptimisticMessage(e,t){let i=this.optimisticMessages.get(e);i&&(i.delete(t),i.size===0&&this.optimisticMessages.delete(e))}trackConfirmedMessage(e,t,i){let s=this.confirmedMessages.get(e);s||(s=new Map,this.confirmedMessages.set(e,s)),s.set(t,i)}getMessageIds(e){let t=this.confirmedMessages.get(e),i=this.optimisticMessages.get(e),s=new Set;if(t)for(let n of t.keys())s.add(n);if(i)for(let n of i.keys())s.add(n);return Array.from(s)}clearConversation(e){this.seenMessageIds.delete(e),this.optimisticMessages.delete(e);let t=this.getMessageIds(e);this.receiptManager.clearConversation(e,t),this.confirmedMessages.delete(e),this.logger.debug("Cleared message tracking for conversation:",e)}clear(){this.seenMessageIds.clear(),this.optimisticMessages.clear(),this.confirmedMessages.clear(),this.receiptManager.clear(),this.logger.debug("Cleared all message tracking")}},ft=class extends M.default{constructor(e=!1){super(),this.typingTimers=new Map,this.activeTyping=new Map,this.TYPING_TIMEOUT_MS=5e3,this.logger=new j(e)}handleTypingStart(e,t){if(!e||!t){this.logger.warn("Invalid typing_start: missing conversationId or userId");return}let i=this.activeTyping.get(e);i||(i=new Set,this.activeTyping.set(e,i));let s=this.typingTimers.get(e);s||(s=new Map,this.typingTimers.set(e,s));let n=i.has(t),a=s.get(t);a&&clearTimeout(a),i.add(t);let r=setTimeout(()=>{this.handleTypingStop(e,t)},this.TYPING_TIMEOUT_MS);s.set(t,r),n?this.logger.debug("Typing timer restarted:",e,t):(this.emit("typing",{conversationId:e,userId:t,state:"start"}),this.logger.debug("Typing started:",e,t))}handleTypingStop(e,t){if(!e||!t){this.logger.warn("Invalid typing_stop: missing conversationId or userId");return}let i=this.activeTyping.get(e),s=this.typingTimers.get(e);if(!i||!i.has(t)){this.logger.debug("Typing stop ignored (user not typing):",e,t);return}let n=s==null?void 0:s.get(t);n&&(clearTimeout(n),s==null||s.delete(t)),i.delete(t),i.size===0&&this.activeTyping.delete(e),s&&s.size===0&&this.typingTimers.delete(e),this.emit("typing",{conversationId:e,userId:t,state:"stop"}),this.logger.debug("Typing stopped:",e,t)}clearConversation(e){let t=this.activeTyping.get(e),i=this.typingTimers.get(e);if(t){for(let s of t)this.emit("typing",{conversationId:e,userId:s,state:"stop"});this.activeTyping.delete(e)}if(i){for(let s of i.values())clearTimeout(s);this.typingTimers.delete(e)}this.logger.debug("Cleared typing state for conversation:",e)}clear(){for(let e of this.typingTimers.values())for(let t of e.values())clearTimeout(t);this.typingTimers.clear(),this.activeTyping.clear(),this.logger.debug("Cleared all typing state")}getTypingUsers(e){let t=this.activeTyping.get(e);return t?Array.from(t):[]}},gt=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],He,Oe=typeof RTCPeerConnection!="undefined"&&typeof navigator!="undefined"&&typeof((He=navigator.mediaDevices)==null?void 0:He.getUserMedia)=="function",W=class extends M.default{constructor(e={}){var t;super(),this.peers=new Map,this.localStream=null,this.mediaOptions={},this.screenTrack=null,this.cameraTrack=null,this.options=e,this.iceServers=(t=e.iceServers)!=null?t:gt,this.getIceServers=e.getIceServers,this.iceServersResolved=!e.getIceServers}static isAvailable(){return Oe}static async enumerateDevices(){var e;if(!((e=navigator.mediaDevices)!=null&&e.enumerateDevices))return[];try{return await navigator.mediaDevices.enumerateDevices()}catch{return[]}}setMediaOptions(e){this.mediaOptions={...this.mediaOptions,...e}}async getMedia(e){if(this.localStream)return this.localStream;let t=this.mediaOptions,i={echoCancellation:!0,noiseSuppression:t.noiseSuppression!==!1};t.audioDeviceId&&(i.deviceId={exact:t.audioDeviceId});let s=!1;if(e==="video"){let a={};t.videoDeviceId&&(a.deviceId={exact:t.videoDeviceId}),t.lowBandwidth&&(a.width={ideal:640},a.height={ideal:360},a.frameRate={ideal:15,max:20}),s=Object.keys(a).length?a:!0}let n=await navigator.mediaDevices.getUserMedia({audio:i,video:s});return t.startMuted&&n.getAudioTracks().forEach(a=>a.enabled=!1),t.startVideoOff&&n.getVideoTracks().forEach(a=>a.enabled=!1),this.localStream=n,n}async createPeerConnection(e,t){if(!Oe)return null;if(!this.iceServersResolved&&this.getIceServers)try{this.iceServers=await this.getIceServers(),this.iceServersResolved=!0}catch(n){this.options.debug&&console.warn("Failed to fetch ICE servers, using defaults:",n),this.iceServersResolved=!0}let i=new RTCPeerConnection({iceServers:this.iceServers}),s={pc:i};return this.peers.set(e,s),i.ontrack=n=>{n.streams[0]&&(s.remoteStream=n.streams[0],this.emit("remote_stream",{userId:e,stream:n.streams[0]}))},i.onicecandidate=n=>{n.candidate&&this.emit("ice_candidate",{userId:e,candidate:n.candidate.toJSON()})},i.oniceconnectionstatechange=()=>{if(i.iceConnectionState==="connected"||i.iceConnectionState==="completed")this.mediaOptions.lowBandwidth&&this.setVideoBitrate(35e4),this.emit("peer_connected",{userId:e});else if(i.iceConnectionState==="failed"){let n=this.peers.get(e);n&&!n.hasRestartedIce&&typeof i.restartIce=="function"?(n.hasRestartedIce=!0,i.restartIce()):this.emit("ice_failed",{userId:e})}},i}async createOffer(e,t){let i=await this.getMedia(t),s=await this.createPeerConnection(e,t);if(!s)return null;i.getTracks().forEach(a=>s.addTrack(a,i));let n=await s.createOffer();return await s.setLocalDescription(n),n}async handleOffer(e,t,i){let s=await this.getMedia(i),n=await this.createPeerConnection(e,i);if(!n)return null;s.getTracks().forEach(r=>n.addTrack(r,s)),await n.setRemoteDescription(new RTCSessionDescription(t));let a=await n.createAnswer();return await n.setLocalDescription(a),a}async handleAnswer(e,t){let i=this.peers.get(e);i&&await i.pc.setRemoteDescription(new RTCSessionDescription(t))}async addIceCandidate(e,t){let i=this.peers.get(e);if(i)try{await i.pc.addIceCandidate(new RTCIceCandidate(t))}catch(s){this.options.debug&&console.warn("addIceCandidate failed:",s)}}getLocalStream(){return this.localStream}getRemoteStream(e){var t;return(t=this.peers.get(e))==null?void 0:t.remoteStream}getAllRemoteStreams(){let e=new Map;for(let[t,i]of this.peers)i.remoteStream&&e.set(t,i.remoteStream);return e}async applyVideoConstraints(e){var i;let t=(i=this.localStream)==null?void 0:i.getVideoTracks()[0];if(t)try{await t.applyConstraints(e)}catch{}}async applyAudioConstraints(e){var i;let t=(i=this.localStream)==null?void 0:i.getAudioTracks()[0];if(t)try{await t.applyConstraints(e)}catch{}}async setVideoBitrate(e){for(let[,t]of this.peers){let i=t.pc.getSenders().find(n=>{var a;return((a=n.track)==null?void 0:a.kind)==="video"});if(!i)continue;let s=i.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);for(let n of s.encodings)e==null?delete n.maxBitrate:n.maxBitrate=e;try{await i.setParameters(s)}catch{}}}async setLowBandwidth(e){this.mediaOptions.lowBandwidth=e,await this.applyVideoConstraints(e?{width:{max:640},height:{max:360},frameRate:{max:20}}:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}}),await this.setVideoBitrate(e?35e4:null)}async switchDevice(e,t){if(!this.localStream)return;let i=e==="video"?{video:{deviceId:{exact:t}}}:{audio:{deviceId:{exact:t}}},s=await navigator.mediaDevices.getUserMedia(i),n=e==="video"?s.getVideoTracks()[0]:s.getAudioTracks()[0];if(!n)return;let a=e==="video"?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];a&&(n.enabled=a.enabled);for(let[,r]of this.peers){let c=r.pc.getSenders().find(l=>{var p;return((p=l.track)==null?void 0:p.kind)===e});c&&await c.replaceTrack(n)}a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(n)}isScreenSharing(){return!!this.screenTrack}async startScreenShare(){var n,a;if(this.screenTrack)return!0;let e=navigator.mediaDevices;if(!e.getDisplayMedia)return!1;let t=await e.getDisplayMedia({video:!0,audio:!1}),i=t.getVideoTracks()[0];if(!i)return!1;this.cameraTrack=(a=(n=this.localStream)==null?void 0:n.getVideoTracks()[0])!=null?a:null;let s=!1;for(let[,r]of this.peers){let c=r.pc.getSenders().find(l=>{var p;return((p=l.track)==null?void 0:p.kind)==="video"});c&&(await c.replaceTrack(i),s=!0)}return s?(this.screenTrack=i,i.onended=()=>{this.stopScreenShare()},this.emit("screen_share_changed",{active:!0,stream:t}),!0):(i.stop(),!1)}async stopScreenShare(){var e;if(this.screenTrack){for(let[,t]of this.peers){let i=t.pc.getSenders().find(s=>{var n;return((n=s.track)==null?void 0:n.kind)==="video"||s.track===this.screenTrack});i&&await i.replaceTrack((e=this.cameraTrack)!=null?e:null)}this.screenTrack.stop(),this.screenTrack=null,this.emit("screen_share_changed",{active:!1})}}closePeer(e){let t=this.peers.get(e);t&&t.pc.signalingState!=="closed"&&t.pc.close(),this.peers.delete(e)}cleanup(){for(let[e]of this.peers)this.closePeer(e);this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.removeAllListeners()}async getCallStats(){let e={};for(let[,t]of this.peers)try{(await t.pc.getStats()).forEach(s=>{var a,r,c,l,p,m,f,y,v,d;let n=s;if(s.type==="inbound-rtp")e.packets_lost_in=((a=e.packets_lost_in)!=null?a:0)+((r=n.packetsLost)!=null?r:0),e.packets_received=((c=e.packets_received)!=null?c:0)+((l=n.packetsReceived)!=null?l:0),e.bytes_received=((p=e.bytes_received)!=null?p:0)+((m=n.bytesReceived)!=null?m:0),typeof n.jitter=="number"&&(e.jitter_ms=n.jitter*1e3);else if(s.type==="outbound-rtp")e.packets_sent=((f=e.packets_sent)!=null?f:0)+((y=n.packetsSent)!=null?y:0),e.bytes_sent=((v=e.bytes_sent)!=null?v:0)+((d=n.bytesSent)!=null?d:0);else if(s.type==="candidate-pair"&&s.state==="succeeded"){let T=s.currentRoundTripTime;typeof T=="number"&&(e.rtt_ms=T*1e3)}})}catch{}return e}setLocalAudioEnabled(e){this.localStream&&this.localStream.getAudioTracks().forEach(t=>t.enabled=e)}setLocalVideoEnabled(e){this.localStream&&this.localStream.getVideoTracks().forEach(t=>t.enabled=e)}},ut=6e4,mt=class extends M.default{constructor(e,t={}){var i,s;super(),this.ringTimeoutId=null,this.webRTC=null,this.callRole=null,this.currentCallType="video",this.participants=new Set,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.callConnectedEmitted=!1,this.conversationId=e,this.logger=new j((i=t.debug)!=null?i:!1),this.ringTimeoutMs=(s=t.ringTimeout)!=null?s:ut,this.submitCallQuality=t.submitCallQuality,W.isAvailable()&&(this.webRTC=new W({debug:t.debug,getIceServers:t.getIceServers}))}emitCallConnected(e,t,i){this.callConnectedEmitted||(this.callConnectedEmitted=!0,this.callStartedAt==null&&(this.callStartedAt=Date.now()),this.emit("call_connected",{localStream:e,remoteStream:t,remoteUserId:i}))}setSendCallHandler(e){this.sendCallHandler=e}setCallOptions(e){var t;(t=this.webRTC)==null||t.setMediaOptions(e)}listDevices(){return W.enumerateDevices()}applyVideoConstraints(e){return this.webRTC?this.webRTC.applyVideoConstraints(e):Promise.resolve()}applyAudioConstraints(e){return this.webRTC?this.webRTC.applyAudioConstraints(e):Promise.resolve()}switchDevice(e,t){return this.webRTC?this.webRTC.switchDevice(e,t):Promise.resolve()}setLowBandwidth(e){return this.webRTC?this.webRTC.setLowBandwidth(e):Promise.resolve()}startScreenShare(){return this.webRTC?this.webRTC.startScreenShare():Promise.resolve(!1)}stopScreenShare(){return this.webRTC?this.webRTC.stopScreenShare():Promise.resolve()}isScreenSharing(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.isScreenSharing())!=null?t:!1}setSubmitCallQuality(e){this.submitCallQuality=e}send(e){if(!this.sendCallHandler){let t=new Error("Call not connected. Join conversation first.");throw this.emit("call_error",{reason:"websocket_lost",message:t.message}),t}this.sendCallHandler(e)}clearRingTimeout(){this.ringTimeoutId&&(clearTimeout(this.ringTimeoutId),this.ringTimeoutId=null)}startCall(e="video"){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.callRole="caller",this.currentCallType=e;let t={type:"call_invite",conversation_id:this.conversationId,payload:{call_type:e}};this.send(t),this.logger.debug("call.invite sent",{conversation_id:this.conversationId,call_type:e}),this.ringTimeoutId=setTimeout(()=>{this.ringTimeoutId=null,this.logger.debug("call ring timeout - no answer"),this.endCall("no_answer"),this.emit("call_timeout",{reason:"no_answer"})},this.ringTimeoutMs)}acceptCall(){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.callRole="callee";let e={type:"call_accept",conversation_id:this.conversationId};this.send(e),this.logger.debug("call.accept sent",{conversation_id:this.conversationId})}joinCall(e="video"){this.callRole="joiner",this.currentCallType=e;let t={type:"call_join",conversation_id:this.conversationId};this.send(t),this.logger.debug("call.join sent",{conversation_id:this.conversationId})}rejectCall(e){this.clearRingTimeout();let t={type:"call_reject",conversation_id:this.conversationId,payload:e?{reason:e}:void 0};this.send(t),this.logger.debug("call.reject sent",{conversation_id:this.conversationId,reason:e})}endCall(e){this.clearRingTimeout();let t={type:"call_hangup",conversation_id:this.conversationId,payload:e?{reason:e}:void 0};this.send(t),this.logger.debug("call.hangup sent",{conversation_id:this.conversationId,reason:e})}handleCallInvite(e){this.currentCallType=e.call_type||"video",this.emit("call_invite",{callType:this.currentCallType,callerId:e.caller_id,callerName:e.caller_name})}async handleCallAccept(e){this.clearRingTimeout();let t=e==null?void 0:e.sender_id;if(this.participants.add(t!=null?t:"unknown"),this.webRTC&&t&&this.callRole==="caller")try{let i=await this.webRTC.createOffer(t,this.currentCallType);i&&(this.sendOffer(t,i),this.setupWebRTCEvents())}catch(i){this.logger.debug("WebRTC createOffer failed:",i),this.emit("call_error",{reason:"permission_denied",message:String(i)})}this.emit("call_accept",{accepterId:t})}async handleCallJoin(e){let t=e.joiner_id;if(t&&this.participants.add(t),this.webRTC&&t&&(this.callRole==="caller"||this.callRole==="callee"))try{let i=await this.webRTC.createOffer(t,this.currentCallType);i&&(this.sendOffer(t,i),this.setupWebRTCEvents())}catch(i){this.logger.debug("WebRTC createOffer for joiner failed:",i)}this.emit("call_join",{joinerId:e.joiner_id,joinerName:e.joiner_name})}handleCallReject(e){this.clearRingTimeout(),this.emit("call_reject",{reason:e==null?void 0:e.reason})}async handleCallHangup(e){var i;this.clearRingTimeout();let t=(i=e==null?void 0:e.reason)!=null?i:"user_hangup";await this.submitQualityAndCleanup(t),this.callRole=null,this.participants.clear(),this.emit("call_hangup",{endedBy:e==null?void 0:e.ended_by,reason:t})}handleCallParticipantLeft(e){var i;let t=e.left_user_id;t&&(this.participants.delete(t),(i=this.webRTC)==null||i.closePeer(t)),this.emit("peer_left",{userId:t})}handleCallError(e){this.clearRingTimeout(),this.emit("call_error",{code:e.code,message:e.message,details:e.details})}async handleCallOffer(e){var s;let t=(s=e.from_user_id)!=null?s:e.sender_id,i=e.sdp;if(!(!t||!i)){if(this.participants.add(t),this.webRTC&&(this.callRole==="callee"||this.callRole==="joiner"))try{this.setupWebRTCEvents();let n=await this.webRTC.handleOffer(t,i,this.currentCallType);if(n){this.sendAnswer(t,n);let a=this.webRTC.getLocalStream(),r=this.webRTC.getRemoteStream(t);a&&r&&this.emitCallConnected(a,r,t)}}catch(n){this.logger.debug("WebRTC handleOffer failed:",n),this.emit("call_error",{reason:"permission_denied",message:String(n)})}this.emit("call_offer",{sdp:i,fromUserId:t})}}async handleCallAnswer(e){var s;let t=(s=e.from_user_id)!=null?s:e.sender_id,i=e.sdp;if(!(!t||!i)){if(this.webRTC){await this.webRTC.handleAnswer(t,i);let n=this.webRTC.getLocalStream(),a=this.webRTC.getRemoteStream(t);n&&a&&this.emitCallConnected(n,a,t)}this.emit("call_answer",{sdp:i,fromUserId:t})}}async handleCallICECandidate(e){var s;let t=(s=e.from_user_id)!=null?s:e.sender_id,i=e.candidate;!t||!i||(this.webRTC&&await this.webRTC.addIceCandidate(t,i),this.emit("call_ice_candidate",{candidate:i,fromUserId:t}))}handleCallMute(e){this.emit("peer_mute",{userId:e==null?void 0:e.user_id})}handleCallUnmute(e){this.emit("peer_unmute",{userId:e==null?void 0:e.user_id})}handleVideoOff(e){this.emit("peer_video_off",{userId:e==null?void 0:e.user_id})}handleVideoOn(e){this.emit("peer_video_on",{userId:e==null?void 0:e.user_id})}setMuted(e){var i;(i=this.webRTC)==null||i.setLocalAudioEnabled(!e);let t=e?{type:"call_mute",conversation_id:this.conversationId}:{type:"call_unmute",conversation_id:this.conversationId};this.send(t),this.emit("local_mute_changed",{muted:e})}setVideoEnabled(e){var i;(i=this.webRTC)==null||i.setLocalVideoEnabled(e);let t=e?{type:"video_on",conversation_id:this.conversationId}:{type:"video_off",conversation_id:this.conversationId};this.send(t),this.emit("local_video_changed",{enabled:e})}getLocalStream(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.getLocalStream())!=null?t:null}getRemoteStream(e){var t;return(t=this.webRTC)==null?void 0:t.getRemoteStream(e)}getAllRemoteStreams(){var e,t;return(t=(e=this.webRTC)==null?void 0:e.getAllRemoteStreams())!=null?t:new Map}sendOffer(e,t){let i={sdp:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_offer",conversation_id:this.conversationId,payload:i})}sendAnswer(e,t){let i={sdp:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_answer",conversation_id:this.conversationId,payload:i})}setupWebRTCEvents(){!this.webRTC||this.webRTCEventsSetup||(this.webRTCEventsSetup=!0,this.webRTC.on("ice_candidate",({userId:e,candidate:t})=>{let i={candidate:t,target_user_id:this.participants.size>2?e:void 0};this.send({type:"call_ice_candidate",conversation_id:this.conversationId,payload:i})}),this.webRTC.on("remote_stream",({userId:e,stream:t})=>{var s;let i=(s=this.webRTC)==null?void 0:s.getLocalStream();i&&this.emitCallConnected(i,t,e)}),this.webRTC.on("ice_failed",async()=>{await this.submitQualityAndCleanup("ice_failed"),this.emit("call_error",{reason:"ice_failed",message:"ICE connection failed"})}),this.webRTC.on("screen_share_changed",e=>this.emit("screen_share_changed",e)))}async submitQualityAndCleanup(e,t=!1){let i=this.webRTC,s={end_reason:e};this.callStartedAt!=null&&(s.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3));try{if(i){let n=await i.getCallStats();Object.assign(s,n)}}catch{}if(this.submitCallQuality)try{await this.submitCallQuality(this.conversationId,s,e)}catch(n){this.logger.debug("submitCallQuality failed:",n)}i==null||i.cleanup(),this.webRTC=t?null:W.isAvailable()?new W({}):null,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.callConnectedEmitted=!1}async getCallStats(){let e={};if(this.callStartedAt!=null&&(e.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3)),this.webRTC){let t=await this.webRTC.getCallStats();Object.assign(e,t)}return e}cleanup(){this.clearRingTimeout(),this.submitQualityAndCleanup("user_left",!0),this.webRTC=null,this.webRTCEventsSetup=!1,this.callRole=null,this.participants.clear(),this.removeAllListeners()}};function wt(e,t,i,s){return new Promise((n,a)=>{let r=new XMLHttpRequest;r.open("POST",e);for(let[c,l]of Object.entries(i))r.setRequestHeader(c,l);r.upload.onprogress=c=>{s&&c.lengthComputable&&s(Math.round(c.loaded/c.total*100))},r.onload=()=>{if(r.status>=200&&r.status<300)try{n(r.responseText?JSON.parse(r.responseText):{})}catch{n({})}else{let c=`Upload failed: HTTP ${r.status}`;try{let l=JSON.parse(r.responseText);l!=null&&l.message&&(c=l.message)}catch{}a(new Error(c))}},r.onerror=()=>a(new Error("Upload failed: network error")),r.send(t)})}function bt(e){return new Promise((t,i)=>{let s=URL.createObjectURL(e),n=new Image;n.onload=()=>{URL.revokeObjectURL(s),t({width:n.naturalWidth,height:n.naturalHeight})},n.onerror=()=>{URL.revokeObjectURL(s),i(new Error("Failed to load image for dimension probing"))},n.src=s})}function vt(e){return new Promise((t,i)=>{let s=URL.createObjectURL(e),n=document.createElement("video");n.preload="metadata",n.onloadedmetadata=()=>{URL.revokeObjectURL(s),t({width:n.videoWidth,height:n.videoHeight,durationMs:Math.round(n.duration*1e3)})},n.onerror=()=>{URL.revokeObjectURL(s),i(new Error("Failed to load video for metadata probing"))},n.src=s})}var yt=class extends M.default{constructor(e,t=!1){var s,n,a;super(),this._isJoined=!1;let i=typeof t=="boolean"?{debug:t}:t;this.id=e,this.messageManager=new pt((s=i.debug)!=null?s:!1),this.typingManager=new ft((n=i.debug)!=null?n:!1),this.callManager=new mt(e,{debug:(a=i.debug)!=null?a:!1,getIceServers:i.getIceServers}),this.callManager.on("call_invite",r=>this.emit("call_invite",r)),this.callManager.on("call_accept",r=>this.emit("call_accept",r)),this.callManager.on("call_join",r=>this.emit("call_join",r)),this.callManager.on("call_reject",r=>this.emit("call_reject",r)),this.callManager.on("call_hangup",r=>this.emit("call_hangup",r)),this.callManager.on("peer_left",r=>this.emit("peer_left",r)),this.callManager.on("peer_mute",r=>this.emit("peer_mute",r)),this.callManager.on("peer_unmute",r=>this.emit("peer_unmute",r)),this.callManager.on("peer_video_off",r=>this.emit("peer_video_off",r)),this.callManager.on("peer_video_on",r=>this.emit("peer_video_on",r)),this.callManager.on("local_mute_changed",r=>this.emit("local_mute_changed",r)),this.callManager.on("local_video_changed",r=>this.emit("local_video_changed",r)),this.callManager.on("screen_share_changed",r=>this.emit("screen_share_changed",r)),this.callManager.on("call_connected",r=>this.emit("call_connected",r)),this.callManager.on("call_error",r=>this.emit("call_error",r)),this.callManager.on("call_timeout",r=>this.emit("call_timeout",r)),this.messageManager.on("message",r=>{r.conversationId===this.id&&this.emit("message",r)}),this.messageManager.on("receipt",r=>{this.emit("receipt",r)}),this.typingManager.on("typing",r=>{r.conversationId===this.id&&this.emit("typing",{userId:r.userId,state:r.state})})}get isJoined(){return this._isJoined}setSendMessageHandler(e){this.sendMessageHandler=e}setSendTypingHandler(e){this.sendTypingHandler=e}setSendReadHandler(e){this.sendReadHandler=e}setSendCallHandler(e){this.callManager.setSendCallHandler(e)}setSubmitCallQuality(e){this.callManager.setSubmitCallQuality(e)}setFetchMessagesCallback(e){this.fetchMessagesCallback=e}setUploadAttachmentCallback(e){this.uploadAttachmentCallback=e}async fetchMessages(e){var i;if(!this.fetchMessagesCallback)throw new Error("REST not configured. Set apiUrl in Vocantly config for fetchMessages() (token, API keys, or getRestHeaders).");let t=await this.fetchMessagesCallback({externalUserId:(i=e==null?void 0:e.externalUserId)!=null?i:"",cursor:e==null?void 0:e.cursor,limit:e==null?void 0:e.limit});return this.messageManager.trackMessageIdsFromHistory(this.id,t.messages.map(s=>s.id)),t}markJoined(){this._isJoined||(this._isJoined=!0,this.emit("joined",{conversation_id:this.id}))}markLeft(){this._isJoined&&(this._isJoined=!1,this.callManager.cleanup(),this.emit("left",{conversation_id:this.id}))}sendMessage(e,t="text",i){if(!this.sendMessageHandler){let a=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",a),a}if(!this._isJoined){let a=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",a),a}let s=te();this.messageManager.createOptimisticMessage(this.id,s,e,t,i);let n={type:"message",conversation_id:this.id,payload:{message_id:s,content:e,message_type:t}};try{this.sendMessageHandler(n)}catch(a){let r=a instanceof Error?a:new Error("Failed to send message");throw this.emit("error",r),r}}async sendMedia(e,t){var y,v;if(!this.sendMessageHandler){let d=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",d),d}if(!this._isJoined){let d=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",d),d}if(!this.uploadAttachmentCallback){let d=new Error("Media upload is not configured. Set apiUrl and appId in the Vocantly config to use sendMedia().");throw this.emit("error",d),d}let i=(y=t==null?void 0:t.fileName)!=null?y:e instanceof File?e.name:"upload",s=e.type||"application/octet-stream",n,a,r;if(s.startsWith("image/")){let d=await bt(e).catch(()=>{});n=d==null?void 0:d.width,a=d==null?void 0:d.height}else if(s.startsWith("video/")){let d=await vt(e).catch(()=>{});n=d==null?void 0:d.width,a=d==null?void 0:d.height,r=d==null?void 0:d.durationMs}let c;try{c=await this.uploadAttachmentCallback({conversationId:this.id,file:e,fileName:i,onProgress:t==null?void 0:t.onProgress})}catch(d){let T=d instanceof Error?d:new Error("Upload failed");throw this.emit("error",T),T}let l=te(),p=[{bucket:c.bucket,key:c.key,file_name:c.fileName,mime_type:c.mimeType,size_bytes:c.sizeBytes,width:n,height:a,duration_ms:r}],m=(v=t==null?void 0:t.caption)!=null?v:"";this.messageManager.createOptimisticMessage(this.id,l,m,c.category,t==null?void 0:t.metadata,p);let f={type:"message",conversation_id:this.id,payload:{message_id:l,content:m,message_type:c.category,attachments:p}};try{this.sendMessageHandler(f)}catch(d){let T=d instanceof Error?d:new Error("Failed to send media message");throw this.emit("error",T),T}}handleIncomingMessage(e){this.messageManager.handleIncomingMessage(this.id,e)}handleReceipt(e,t,i){this.messageManager.handleReceipt(this.id,e,t,i)}handleTyping(e){e.state==="start"?this.typingManager.handleTypingStart(this.id,e.user_id):e.state==="stop"&&this.typingManager.handleTypingStop(this.id,e.user_id)}emitPresence(e){this.emit("presence",{userId:e.user_id,state:e.state})}clearMessages(){this.messageManager.clearConversation(this.id)}clearTyping(){this.typingManager.clearConversation(this.id)}startCall(e="video"){this.ensureJoinedForCall(),this.callManager.startCall(e)}acceptCall(){this.ensureJoinedForCall(),this.callManager.acceptCall()}joinCall(e){this.ensureJoinedForCall(),this.callManager.joinCall(e!=null?e:"video")}rejectCall(e){this.ensureJoinedForCall(),this.callManager.rejectCall(e)}endCall(e){this.ensureJoinedForCall(),this.callManager.endCall(e)}setMuted(e){this.ensureJoinedForCall(),this.callManager.setMuted(e)}setVideoEnabled(e){this.ensureJoinedForCall(),this.callManager.setVideoEnabled(e)}setCallOptions(e){this.callManager.setCallOptions(e)}listDevices(){return this.callManager.listDevices()}applyVideoConstraints(e){return this.callManager.applyVideoConstraints(e)}applyAudioConstraints(e){return this.callManager.applyAudioConstraints(e)}switchDevice(e,t){return this.callManager.switchDevice(e,t)}setLowBandwidth(e){return this.callManager.setLowBandwidth(e)}startScreenShare(){return this.ensureJoinedForCall(),this.callManager.startScreenShare()}stopScreenShare(){return this.callManager.stopScreenShare()}isScreenSharing(){return this.callManager.isScreenSharing()}getLocalStream(){return this.callManager.getLocalStream()}getRemoteStream(e){return this.callManager.getRemoteStream(e)}getAllRemoteStreams(){return this.callManager.getAllRemoteStreams()}getCallStats(){return this.callManager.getCallStats()}handleIncomingCallMessage(e,t){switch(e){case"call_invite":this.callManager.handleCallInvite(t||{});break;case"call_accept":this.callManager.handleCallAccept(t);break;case"call_join":this.callManager.handleCallJoin(t||{});break;case"call_reject":this.callManager.handleCallReject(t);break;case"call_hangup":this.callManager.handleCallHangup(t);break;case"call_participant_left":this.callManager.handleCallParticipantLeft(t||{});break;case"call_error":this.callManager.handleCallError(t||{});break;case"call_offer":this.callManager.handleCallOffer(t||{});break;case"call_answer":this.callManager.handleCallAnswer(t||{});break;case"call_ice_candidate":this.callManager.handleCallICECandidate(t||{});break;case"call_mute":this.callManager.handleCallMute(t||{});break;case"call_unmute":this.callManager.handleCallUnmute(t||{});break;case"video_off":this.callManager.handleVideoOff(t||{});break;case"video_on":this.callManager.handleVideoOn(t||{});break}}ensureJoinedForCall(){if(!this._isJoined)throw new Error("Conversation is not joined. Call join() first.")}startTyping(){if(!this.sendTypingHandler){let t=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",t),t}if(!this._isJoined){let t=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",t),t}let e={type:"typing_start",conversation_id:this.id};try{this.sendTypingHandler(e)}catch(t){let i=t instanceof Error?t:new Error("Failed to send typing_start");throw this.emit("error",i),i}}stopTyping(){if(!this.sendTypingHandler){let t=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",t),t}if(!this._isJoined){let t=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",t),t}let e={type:"typing_stop",conversation_id:this.id};try{this.sendTypingHandler(e)}catch(t){let i=t instanceof Error?t:new Error("Failed to send typing_stop");throw this.emit("error",i),i}}markRead(e){if(!this.sendReadHandler){let i=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",i),i}if(!this._isJoined){let i=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",i),i}let t={type:"read",conversation_id:this.id,payload:{message_id:e}};try{this.sendReadHandler(t)}catch(i){let s=i instanceof Error?i:new Error("Failed to send read receipt");throw this.emit("error",s),s}}},xt=class extends M.default{constructor(e,t=!1,i,s,n){super(),this.conversations=new Map,this.restFetcher=null,this.appId=null,this.iceServersCache=null,this.sendMessageHandler=e,this.sendTypingHandler=s,this.sendCallHandler=n,this.supportMessageHandler=i,this.debug=t,this.logger=new j(t)}setRestFetcher(e){if(this.restFetcher=e,e)for(let t of this.conversations.values())t.setSubmitCallQuality((i,s,n)=>this.submitCallQualityToApi(i,s,n))}setAppId(e){this.appId=e&&e.trim()||null,this.iceServersCache=null}getIceServersFetcher(){if(!(!this.restFetcher||!this.appId))return async()=>{var r;if(this.iceServersCache)return this.iceServersCache;let t=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/apps/${encodeURIComponent(this.appId)}/ice-servers`,i=await this.restFetcher.getHeaders(),s=await fetch(t,{method:"GET",headers:i});if(!s.ok)throw new Error(`ICE servers fetch failed: ${s.status}`);let n=await s.json();if(!n.success||!((r=n.data)!=null&&r.iceServers))throw new Error("Invalid ICE servers response");let a=n.data.iceServers;return this.iceServersCache=a,a}}setSupportMessageHandler(e){this.supportMessageHandler=e}setSendTypingHandler(e){this.sendTypingHandler=e;for(let t of this.conversations.values())t.setSendTypingHandler(e)}setSendCallHandler(e){this.sendCallHandler=e;for(let t of this.conversations.values())t.setSendCallHandler(e)}setSendReadHandler(e){this.sendReadHandler=e;for(let t of this.conversations.values())t.setSendReadHandler(e)}async list(e){var v,d,T;if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for list() and fetchMessages() (token, API keys, or getRestHeaders).");let t=this.restFetcher.apiUrl.replace(/\/$/,""),i=(v=e==null?void 0:e.externalUserId)==null?void 0:v.trim(),s=Math.min(Math.max(1,(d=e==null?void 0:e.limit)!=null?d:20),100),n=new URLSearchParams({limit:String(s)});i&&n.set("external_user_id",i),e!=null&&e.cursor&&n.set("cursor",e.cursor);let a=n.toString(),r=`${t}/sdk/conversations${a?`?${a}`:""}`,c=await this.restFetcher.getHeaders(),l=await fetch(r,{method:"GET",headers:c});if(!l.ok){let U=await l.text(),O={};try{O=JSON.parse(U)}catch{O={message:U}}throw new Error(O.message||`HTTP ${l.status}: ${U}`)}let p=await l.json();if(!p.success||!p.data)throw new Error(p.message||"Invalid response");let m=p.data,f=Array.isArray(m.conversations)?m.conversations:[],y=(T=m.pagination)!=null?T:{has_next_page:!1,next_cursor:null,limit:s};return{conversations:f,pagination:y}}async getMessages(e,t,i={}){var f;if(!(e!=null&&e.trim()))throw new Error("conversationId is required");if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for list() and fetchMessages().");let s=Math.min(Math.max(1,(f=i.limit)!=null?f:20),100),n=new URLSearchParams({limit:String(s)});t!=null&&t.trim()&&n.set("external_user_id",t.trim()),i.cursor&&n.set("cursor",i.cursor);let a=this.restFetcher.apiUrl.replace(/\/$/,""),r=n.toString(),c=`${a}/sdk/conversations/${encodeURIComponent(e.trim())}/messages${r?`?${r}`:""}`,l=await this.restFetcher.getHeaders(),p=await fetch(c,{method:"GET",headers:l});if(!p.ok){let y=await p.text(),v={};try{v=JSON.parse(y)}catch{v={message:y}}throw new Error(v.message||`HTTP ${p.status}: ${y}`)}let m=await p.json();if(!m.success||!m.data)throw new Error(m.message||"Invalid response");return{messages:m.data.messages||[],pagination:m.data.pagination||{has_next_page:!1,next_cursor:null,limit:s}}}async uploadAttachment(e){if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for sendMedia().");if(!this.appId)throw new Error("appId is required in Vocantly config for sendMedia().");let i=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/apps/${encodeURIComponent(this.appId)}/uploads`,n={...await this.restFetcher.getHeaders()};delete n["Content-Type"],delete n["content-type"];let a=new FormData;a.append("conversation_id",e.conversationId),a.append("file",e.file,e.fileName);let r=await wt(i,a,n,e.onProgress);if(!r.success||!r.data)throw new Error(r.message||"Invalid upload response");return{bucket:r.data.bucket,key:r.data.key,category:r.data.category,fileName:r.data.file_name,mimeType:r.data.mime_type,sizeBytes:r.data.size_bytes}}async getAttachmentDownloadUrl(e,t){if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for media downloads.");if(!this.appId)throw new Error("appId is required in Vocantly config for media downloads.");let i=this.restFetcher.apiUrl.replace(/\/$/,""),s=new URLSearchParams({bucket:e,key:t}),n=`${i}/apps/${encodeURIComponent(this.appId)}/uploads/url?${s.toString()}`,a=await this.restFetcher.getHeaders(),r=await fetch(n,{method:"GET",headers:a});if(!r.ok){let l=await r.text(),p={};try{p=JSON.parse(l)}catch{p={message:l}}throw new Error(p.message||`HTTP ${r.status}: ${l}`)}let c=await r.json();if(!c.success||!c.data)throw new Error(c.message||"Invalid download URL response");return{url:c.data.url,expiresInSeconds:c.data.expires_in_seconds}}async submitCallQualityToApi(e,t,i){if(!this.restFetcher)return;let n=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/conversations/${encodeURIComponent(e)}/call-quality`,a=await this.restFetcher.getHeaders(),r={end_reason:i};typeof t.duration_seconds=="number"&&(r.duration_seconds=t.duration_seconds),typeof t.packets_lost_in=="number"&&(r.packets_lost_in=t.packets_lost_in),typeof t.packets_lost_out=="number"&&(r.packets_lost_out=t.packets_lost_out),typeof t.packets_received=="number"&&(r.packets_received=t.packets_received),typeof t.packets_sent=="number"&&(r.packets_sent=t.packets_sent),typeof t.bytes_received=="number"&&(r.bytes_received=t.bytes_received),typeof t.bytes_sent=="number"&&(r.bytes_sent=t.bytes_sent),typeof t.jitter_ms=="number"&&(r.jitter_ms=t.jitter_ms),typeof t.rtt_ms=="number"&&(r.rtt_ms=t.rtt_ms);let c=await fetch(n,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!c.ok){let l=await c.text();throw this.logger.debug("submitCallQuality failed:",c.status,l),new Error(`Call quality submit failed: ${c.status}`)}}get(e){if(!e||e.length===0)throw new Error("Conversation ID is required");let t=this.conversations.get(e);return t||(t=new yt(e,{debug:this.debug,getIceServers:this.getIceServersFetcher()}),this.sendMessageHandler&&t.setSendMessageHandler(this.sendMessageHandler),this.sendTypingHandler&&t.setSendTypingHandler(this.sendTypingHandler),this.sendCallHandler&&t.setSendCallHandler(this.sendCallHandler),this.sendReadHandler&&t.setSendReadHandler(this.sendReadHandler),this.conversations.set(e,t),this.logger.debug("Created conversation instance:",e)),this.restFetcher&&(t.setFetchMessagesCallback(i=>this.getMessages(e,i.externalUserId,{cursor:i.cursor,limit:i.limit})),t.setSubmitCallQuality((i,s,n)=>this.submitCallQualityToApi(i,s,n)),this.appId&&t.setUploadAttachmentCallback(i=>this.uploadAttachment(i))),t}has(e){return this.conversations.has(e)}async join(e,t){if(!e||e.length===0)throw new Error("Conversation ID is required");this.get(e),await t(e),this.logger.debug("Join requested for conversation:",e)}async leave(e,t){if(!e||e.length===0)throw new Error("Conversation ID is required");let i=this.conversations.get(e);i?(i.clearTyping(),await t(e),i.markLeft(),this.logger.debug("Left conversation:",e)):(await t(e),this.logger.warn("Attempted to leave unknown conversation:",e))}routeIncomingMessage(e){var i;let t;switch(e.type){case"joined":t=((i=e.payload)==null?void 0:i.conversation_id)||e.conversation_id,t&&this.get(t).markJoined();break;case"message":if(t=e.conversation_id,t){let s=this.conversations.get(t);s?s.isJoined?s.handleIncomingMessage(e.payload):this.logger.warn("Received message for conversation that is not joined:",t):this.logger.warn("Received message for unknown conversation:",t)}break;case"typing":if(t=e.conversation_id,t){let s=this.conversations.get(t);s?s.isJoined?s.handleTyping(e.payload):this.logger.warn("Received typing indicator for conversation that is not joined:",t):this.logger.warn("Received typing indicator for unknown conversation:",t)}break;case"receipt":if(t=e.conversation_id,t){let s=this.conversations.get(t);if(s)if(s.isJoined){let n=e;s.handleReceipt(n.payload.message_id,n.payload.state,n.payload.user_id)}else this.logger.warn("Received receipt for conversation that is not joined:",t);else this.logger.warn("Received receipt for unknown conversation:",t)}break;case"support":break;case"presence":if(t=e.conversation_id,t){let s=this.conversations.get(t);s&&s.isJoined&&s.emitPresence(e.payload)}break;case"error":this.logger.error("Received error message:",e.error);break;case"call_invite":case"call_accept":case"call_join":case"call_reject":case"call_hangup":case"call_participant_left":case"call_error":case"call_offer":case"call_answer":case"call_ice_candidate":case"call_mute":case"call_unmute":case"video_off":case"video_on":if(t=e.conversation_id,t){let s=this.get(t),n="payload"in e?e.payload:void 0;s.handleIncomingCallMessage(e.type,n)}break}}routeSupportMessage(e){var s;if(!this.supportMessageHandler){this.logger.warn("Support message handler not set, ignoring support message");return}let t=e.conversation_id;if(!t){this.logger.warn("Support message missing conversation_id");return}let i=(s=e.payload)==null?void 0:s.event;if(!i){this.logger.warn("Support message missing event type");return}this.supportMessageHandler(t,i,e.payload)}remove(e){let t=this.conversations.get(e);t&&(t.markLeft(),t.clearMessages(),t.clearTyping(),this.conversations.delete(e),this.logger.debug("Removed conversation instance:",e))}getAllIds(){return Array.from(this.conversations.keys())}clear(){for(let e of this.conversations.values())e.markLeft(),e.clearMessages(),e.clearTyping();this.conversations.clear(),this.logger.debug("Cleared all conversations")}},kt=class extends M.default{constructor(e=!1){super(),this.presenceState=new Map,this.logger=new j(e)}handlePresence(e,t){if(!e){this.logger.warn("Invalid presence event: missing userId");return}if(t!=="online"&&t!=="offline"){this.logger.warn("Invalid presence state:",t);return}this.presenceState.get(e)!==t?(this.presenceState.set(e,t),this.emit("presence",{userId:e,state:t}),this.logger.debug("Presence changed:",e,t)):this.logger.debug("Duplicate presence event ignored:",e,t)}getPresence(e){return this.presenceState.get(e)}getPresences(e){let t=new Map;for(let i of e){let s=this.presenceState.get(i);s&&t.set(i,s)}return t}clearPresence(e){let t=this.presenceState.has(e);this.presenceState.delete(e),t&&this.logger.debug("Cleared presence for user:",e)}clear(){this.presenceState.clear(),this.logger.debug("Cleared all presence state")}},St=class extends M.default{constructor(e,t,i,s=!1){super(),this.botActive=!1,this.status="queued",this.conversationId=e,this.conversation=t,this.role=i,this.logger=new j(s),this.conversation.on("message",n=>this.emit("message",n)),this.conversation.on("typing",n=>this.emit("typing",n)),this.conversation.on("presence",n=>this.emit("presence",n)),this.conversation.on("joined",n=>this.emit("joined",n)),this.conversation.on("left",n=>this.emit("left",n)),this.conversation.on("error",n=>this.emit("error",n))}getConversation(){return this.conversation}isCustomer(){return this.role==="customer"}isAgent(){return this.role==="agent"}getRole(){return this.role}isBotActive(){return this.botActive}getAssignedAgent(){return this.assignedAgentId}getStatus(){return this.status}handleAssigned(e){if(this.assignedAgentId===e)return;let t=this.assignedAgentId,i=t!==void 0;this.assignedAgentId=e,this.status==="queued"?this.status="assigned":this.status==="assigned"||this.status,i?(this.emit("assigned",{agentId:e,previousAgentId:t}),this.logger.debug("Support session reassigned:",this.conversationId,e,"from",t)):(this.emit("assigned",{agentId:e}),this.logger.debug("Support session assigned:",this.conversationId,e))}handleUnassigned(){if(this.assignedAgentId===void 0)return;let e=this.assignedAgentId;this.assignedAgentId=void 0,(this.status==="assigned"||this.status==="active")&&(this.status="queued"),this.emit("unassigned",{previousAgentId:e}),this.logger.debug("Support session unassigned:",this.conversationId)}handleBotTakeover(){this.botActive||(this.botActive=!0,this.emit("bot_takeover",{}),this.logger.debug("Bot took over support session:",this.conversationId))}handleBotReleased(){this.botActive&&(this.botActive=!1,this.emit("bot_released",{}),this.logger.debug("Bot released support session:",this.conversationId))}handleClosed(){if(this.status==="closed")return;let e=this.status;this.status="closed",this.emit("closed",{previousStatus:e}),this.logger.debug("Support session closed:",this.conversationId)}handleReopened(){this.status==="closed"&&(this.status=this.assignedAgentId?"assigned":"queued",this.emit("reopened",{}),this.logger.debug("Support session reopened:",this.conversationId))}sendMessage(e,t="text",i){this.conversation.sendMessage(e,t,i)}async join(){}async leave(){}},Ct=class extends M.default{constructor(e,t=!1){super(),this.sessions=new Map,this.getConversationHandler=e,this.debug=t,this.logger=new j(t)}get(e,t="customer"){if(!e||e.length===0)throw new Error("Conversation ID is required");let i=this.sessions.get(e);if(!i){let s=this.getConversationHandler(e);i=new St(e,s,t,this.debug),i.on("assigned",n=>this.emit("assigned",{conversationId:e,...n})),i.on("unassigned",n=>this.emit("unassigned",{conversationId:e,...n})),i.on("bot_takeover",()=>this.emit("bot_takeover",{conversationId:e})),i.on("bot_released",()=>this.emit("bot_released",{conversationId:e})),i.on("closed",n=>this.emit("closed",{conversationId:e,...n})),i.on("reopened",()=>this.emit("reopened",{conversationId:e})),this.sessions.set(e,i),this.logger.debug("Created support session:",e,t)}return i}has(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}handleSupportEvent(e,t,i){let s=this.sessions.get(e);if(!s){t==="assigned"&&(i!=null&&i.agent_id)?this.logger.debug("Support event for unknown session, will be handled when session is created:",e):this.logger.warn("Support event for unknown session:",e,t);return}switch(t){case"assigned":i!=null&&i.agent_id&&typeof i.agent_id=="string"&&s.handleAssigned(i.agent_id);break;case"unassigned":s.handleUnassigned();break;case"bot_takeover":s.handleBotTakeover();break;case"bot_released":s.handleBotReleased();break;case"closed":s.handleClosed();break;case"reopened":s.handleReopened();break}}remove(e){this.sessions.get(e)&&(this.sessions.delete(e),this.logger.debug("Removed support session:",e))}clear(){this.sessions.clear(),this.logger.debug("Cleared all support sessions")}},Ue=class extends M.default{constructor(e){var a,r;super(),this.connectionState="disconnected",this.wsClient=null,this.config={autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,debug:!1,apiUrl:"",...e},this.tokenManager=new lt,this.tokenManager.setToken(e.token),this.logger=new j(this.config.debug),this.wsClient=new ct(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new Ct(c=>this.conversationManager.get(c),this.config.debug),this.conversationManager=new xt(c=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(c)},this.config.debug,void 0,c=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(c)},c=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(c)}),this.conversationManager.setSendReadHandler(c=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(c)}),this.presenceManager=new kt(this.config.debug),this.presenceManager.on("presence",c=>{this.emit("presence",c)});let t=(a=this.config.apiUrl)==null?void 0:a.trim(),i=(r=this.config.appId)==null?void 0:r.trim(),s=this.config.apiKey&&this.config.apiSecret,n=typeof this.config.getRestHeaders=="function";if(t){let c=async()=>{if(n&&this.config.getRestHeaders)return this.config.getRestHeaders();if(s)return{"X-Api-Key":this.config.apiKey,"X-Api-Secret":this.config.apiSecret,"Content-Type":"application/json"};let l=this.tokenManager.getToken();if(!l)throw new Error("Token required for list() and fetchMessages() when API keys are not set");return{Authorization:`Bearer ${l}`,"Content-Type":"application/json"}};this.conversationManager.setRestFetcher({apiUrl:t,getHeaders:c}),i&&this.conversationManager.setAppId(i)}this.setupWebSocketHandlers()}setupWebSocketHandlers(){this.wsClient&&(this.wsClient.on("connected",()=>{this.connectionState="connected",this.emit("connected"),this.emit("state",this.connectionState),this.logger.debug("SDK connected")}),this.wsClient.on("disconnected",e=>{this.connectionState="disconnected",this.emit("disconnected",e),this.emit("state",this.connectionState),this.logger.debug("SDK disconnected")}),this.wsClient.on("reconnecting",e=>{this.connectionState="reconnecting",this.emit("reconnecting",e),this.emit("state",this.connectionState),this.logger.debug("SDK reconnecting",e)}),this.wsClient.on("message",e=>{if(this.emit("message",e),this.conversationManager.routeIncomingMessage(e),e.type==="presence"){let t=e;t.payload&&this.presenceManager.handlePresence(t.payload.user_id,t.payload.state)}switch(e.type==="support"&&this.conversationManager.routeSupportMessage(e),e.type){case"joined":this.emit("joined",e);break;case"message":this.emit("message",e);break;case"typing":this.emit("typing",e);break;case"receipt":break;case"support":break;case"presence":break;case"error":this.emit("error",e);break}}),this.wsClient.on("error",e=>{this.connectionState="error";let t=e instanceof Error?e.message:"";(e instanceof Error?e.name:"")==="TokenExpiredError"||t&&t.includes("Token expired")?(this.logger.error("Token expired:",t),this.logger.warn("To reconnect, call sdk.updateToken(newToken) then sdk.connect()")):this.logger.error("SDK error:",e);let s=e instanceof Error?e:new Error("WebSocket connection error");this.emit("error",s),this.emit("state",this.connectionState)}))}getState(){return this.connectionState}getConfig(){return{...this.config}}async connect(){if(this.connectionState==="connected"){this.logger.warn("Already connected");return}if(this.connectionState==="connecting"){this.logger.warn("Connection already in progress");return}this.tokenManager.validateTokenPresence();let e=this.tokenManager.getToken();if(!e)throw new Error("Token is required for connection");this.connectionState="connecting",this.emit("state",this.connectionState),this.logger.debug("Connecting...");try{if(!this.wsClient)throw new Error("WebSocket client not initialized");await this.wsClient.connect(e)}catch(t){this.connectionState="error",this.emit("state",this.connectionState);let i=t instanceof Error?t:new Error("Connection failed");throw this.emit("error",i),i}}async disconnect(){this.connectionState!=="disconnected"&&(this.logger.debug("Disconnecting..."),this.conversationManager.clear(),this.presenceManager.clear(),this.supportManager.clear(),this.wsClient&&this.wsClient.disconnect(),this.connectionState="disconnected",this.emit("disconnected"),this.emit("state",this.connectionState))}isConnected(){var e;return this.connectionState==="connected"&&((e=this.wsClient)==null?void 0:e.isConnected())===!0}updateToken(e){if(!e||e.length===0)throw new Error("Token cannot be empty");this.tokenManager.setToken(e),this.logger.debug("Token updated"),this.isConnected()&&(this.logger.warn("Token updated while connected. Disconnecting to reconnect with new token..."),this.disconnect())}get conversations(){return{get:e=>this.conversationManager.get(e),has:e=>this.conversationManager.has(e),join:e=>this.conversationManager.join(e,t=>this.joinConversation(t)),leave:e=>this.conversationManager.leave(e,t=>this.leaveConversation(t)),list:e=>this.conversationManager.list(e),getAttachmentDownloadUrl:(e,t)=>this.conversationManager.getAttachmentDownloadUrl(e,t)}}get support(){return{get:(e,t="customer")=>this.supportManager.get(e,t),has:e=>this.supportManager.has(e)}}async joinConversation(e){if(!this.isConnected())throw new Error("Must be connected before joining a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"join",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Join conversation sent:",e)}catch(i){let s=i instanceof Error?i:new Error("Failed to join conversation");throw this.emit("error",s),s}}async leaveConversation(e){if(!this.isConnected())throw new Error("Must be connected before leaving a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"leave",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Leave conversation sent:",e)}catch(i){let s=i instanceof Error?i:new Error("Failed to leave conversation");throw this.emit("error",s),s}}rotateToken(e){this.tokenManager.rotateToken(e),this.logger.debug("Token rotated"),this.isConnected()&&this.logger.warn("Token rotated while connected. Reconnect may be required.")}getTokenManager(){return this.tokenManager}};var Tt={wsUrl:"",token:"",conversationId:"",publicKey:"",title:"Support",subtitle:"We typically reply in a few minutes",greeting:"Hi! \u{1F44B} How can we help you today?",placeholder:"Type your message\u2026",primaryColor:"#195EFF",position:"bottom-right",launcher:"\u{1F4AC}",autoOpen:!1,debug:!1,collectContact:!1,requireEmail:!1,contactPrompt:"Let\u2019s get you connected",csat:!0,csatPrompt:"How would you rate the support you received?",csatThanks:"Thanks for the feedback!",calls:!1,callBundleUrl:"https://cdn.jsdelivr.net/npm/@vocantly/widget@0.1.13/dist/vocantly-widget-call.js"},R=null;function De(e){try{return JSON.parse(atob(e.split(".")[1]))}catch{return null}}function Le(e){let t=De(e);return(t==null?void 0:t.user_id)||(t==null?void 0:t.sub)||null}function Mt(e){return typeof e!="number"?"":e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+" KB":(e/(1024*1024)).toFixed(1)+" MB"}function E(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function le(e){return E(e).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>").replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\n/g,"<br>")}var q=null;function Et(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;q=q||new e,q.resume&&q.resume();let t=q,i=t.currentTime,s=t.createOscillator(),n=t.createGain();s.type="sine",s.frequency.setValueAtTime(880,i),s.frequency.exponentialRampToValueAtTime(1320,i+.08),n.gain.setValueAtTime(1e-4,i),n.gain.exponentialRampToValueAtTime(.16,i+.02),n.gain.exponentialRampToValueAtTime(1e-4,i+.34),s.connect(n).connect(t.destination),s.start(i),s.stop(i+.36)}catch{}}function Rt(e,t){if(document.getElementById("caf-widget-styles"))return;let a=`
2
2
  /* Deliberately scoped, high-specificity reset. The widget is injected into arbitrary
3
3
  sites, so host button/input rules must never change its geometry. */
4
4
  .caf-root,.caf-root *{box-sizing:border-box;}
@@ -56,7 +56,34 @@ var $e=Object.create;var K=Object.defineProperty;var Ve=Object.getOwnPropertyDes
56
56
  .caf-root .caf-csat-b{border:1px solid #e1e6ee!important;background:#fff!important;border-radius:10px!important;padding:5px 8px!important;font-size:17px!important;line-height:1.2!important;cursor:pointer;}
57
57
  .caf-root .caf-csat-b:hover{border-color:${e}!important;background:#f8faff!important;transform:translateY(-1px);}
58
58
 
59
- .caf-composer{border-top:1px solid #e8ecf2;padding:12px 14px;display:flex;gap:9px;align-items:flex-end;background:#fff;}
59
+ .caf-m.caf-media{padding:6px;overflow:hidden;}
60
+ .caf-media-body img{display:block;width:100%;max-width:260px;border-radius:11px;cursor:pointer;}
61
+ .caf-media-body video{display:block;width:100%;max-width:260px;border-radius:11px;background:#000;}
62
+ .caf-media-skeleton{width:100%;max-width:260px;min-height:120px;background:linear-gradient(90deg,#eef1f6 25%,#e4e8ee 37%,#eef1f6 63%);
63
+ background-size:400% 100%;border-radius:11px;animation:caf-shimmer 1.4s ease infinite;}
64
+ @keyframes caf-shimmer{0%{background-position:100% 50%}100%{background-position:0 50%}}
65
+ .caf-media-error{padding:8px 4px;font-size:12.5px;opacity:.75;}
66
+ .caf-media-caption{padding:6px 7px 2px;font-size:13.5px;line-height:1.5;}
67
+ .caf-file-chip{display:flex;align-items:center;gap:9px;padding:10px 12px;border-radius:11px;background:rgba(255,255,255,.16);color:inherit;text-decoration:none;}
68
+ .caf-other .caf-file-chip{background:#f5f7fa;}
69
+ .caf-file-chip svg{width:20px;height:20px;flex:none;}
70
+ .caf-file-meta{min-width:0;}
71
+ .caf-file-name{display:block;font-weight:650;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:150px;}
72
+ .caf-file-size{display:block;font-size:11px;opacity:.7;white-space:nowrap;}
73
+
74
+ .caf-upload{display:none;align-items:center;gap:10px;padding:8px 14px;border-top:1px solid #e8ecf2;background:#fff;}
75
+ .caf-upload.show{display:flex;}
76
+ .caf-upload-label{flex:none;font-size:11.5px;color:#667085;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
77
+ .caf-upload-track{flex:1;height:4px;border-radius:999px;background:#e8ecf2;overflow:hidden;}
78
+ .caf-upload-bar{height:100%;width:0%;background:${e};border-radius:999px;transition:width .12s ease;}
79
+
80
+ .caf-composer{border-top:1px solid #e8ecf2;padding:12px 14px;display:flex;gap:6px;align-items:flex-end;background:#fff;}
81
+ .caf-root .caf-attach{width:40px!important;height:44px!important;padding:0!important;flex:none;background:transparent!important;color:#8792a3!important;
82
+ border:0!important;border-radius:12px!important;display:flex!important;align-items:center;justify-content:center;cursor:pointer;
83
+ transition:background .15s ease,color .15s ease;}
84
+ .caf-attach svg{width:20px;height:20px;}
85
+ .caf-root .caf-attach:hover{background:#f0f2f6!important;color:${e}!important;}
86
+ .caf-root .caf-attach:disabled{opacity:.38;cursor:not-allowed;}
60
87
  .caf-input{flex:1;resize:none;min-height:44px;max-height:100px;border:1px solid transparent!important;border-radius:14px!important;background:#f5f7fa!important;
61
88
  color:#172033!important;padding:11px 13px!important;font-size:13.5px!important;line-height:20px!important;outline:none;box-shadow:inset 0 0 0 1px #e7ebf1;transition:background .15s,border-color .15s,box-shadow .15s;}
62
89
  .caf-input::placeholder{color:#98a2b3;opacity:1;}
@@ -110,15 +137,15 @@ var $e=Object.create;var K=Object.defineProperty;var Ve=Object.getOwnPropertyDes
110
137
  .caf-panel.caf-prechat .caf-msgs{padding:16px}.caf-form{padding:20px;border-radius:18px;}
111
138
  }
112
139
  @media (max-height:620px) and (min-width:481px){.caf-panel{height:calc(100vh - 96px);bottom:70px}.caf-header{min-height:82px}.caf-form{padding:18px}.caf-form-d{margin-bottom:13px}}
113
- @media (prefers-reduced-motion:reduce){.caf-panel,.caf-launcher,.caf-send,.caf-fbtn{transition:none!important;}}
114
- `,r=document.createElement("style");r.id="caf-widget-styles",r.textContent=a,document.head.appendChild(r)}function ft(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
140
+ @media (prefers-reduced-motion:reduce){.caf-panel,.caf-launcher,.caf-send,.caf-fbtn{transition:none!important;}.caf-media-skeleton{animation:none!important;}}
141
+ `,r=document.createElement("style");r.id="caf-widget-styles",r.textContent=a,document.head.appendChild(r)}function At(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
115
142
  <div class="caf-panel" id="caf-support-panel" role="dialog" aria-labelledby="caf-support-title" aria-hidden="true">
116
143
  <div class="caf-header">
117
144
  <div class="caf-headmark" aria-hidden="true">
118
145
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/></svg>
119
146
  <span class="caf-dot" data-caf="dot"></span>
120
147
  </div>
121
- <div class="caf-headcopy"><div class="caf-t" id="caf-support-title">${R(e.title)}</div><div class="caf-s">${R(e.subtitle)}</div></div>
148
+ <div class="caf-headcopy"><div class="caf-t" id="caf-support-title">${E(e.title)}</div><div class="caf-s">${E(e.subtitle)}</div></div>
122
149
  <button class="caf-callbtn" data-caf="call" title="Start a voice call" aria-label="Start a voice call">
123
150
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.9.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
124
151
  </button>
@@ -127,20 +154,27 @@ var $e=Object.create;var K=Object.defineProperty;var Ve=Object.getOwnPropertyDes
127
154
  </button>
128
155
  </div>
129
156
  <div class="caf-msgs" data-caf="msgs"></div>
157
+ <div class="caf-upload" data-caf="upload">
158
+ <span class="caf-upload-label" data-caf="upload-label"></span>
159
+ <div class="caf-upload-track"><div class="caf-upload-bar" data-caf="upload-bar"></div></div>
160
+ </div>
130
161
  <div class="caf-composer">
131
- <textarea class="caf-input" data-caf="input" rows="1" placeholder="${R(e.placeholder)}"></textarea>
162
+ <input type="file" class="caf-file-input" data-caf="file" hidden accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime,application/pdf,text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/zip" />
163
+ <button class="caf-attach" data-caf="attach" type="button" aria-label="Attach a file" title="Attach a file"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66L9.41 17.41a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg></button>
164
+ <textarea class="caf-input" data-caf="input" rows="1" placeholder="${E(e.placeholder)}"></textarea>
132
165
  <button class="caf-send" data-caf="send" aria-label="Send" title="Send"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg></button>
133
166
  </div>
134
167
  <div class="caf-foot">powered by Vocantly</div>
135
168
  </div>
136
169
  <button class="caf-launcher" data-caf="launcher" aria-label="Open support chat" aria-controls="caf-support-panel" aria-expanded="false">
137
- <span data-caf="launcher-icon">${e.launcher==="\u{1F4AC}"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>':R(e.launcher)}</span>
170
+ <span data-caf="launcher-icon">${e.launcher==="\u{1F4AC}"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>':E(e.launcher)}</span>
138
171
  <span class="caf-badge" data-caf="badge" style="display:none">0</span>
139
- </button>`,document.body.appendChild(t),{root:t,$:i=>t.querySelector(`[data-caf="${i}"]`)}}function mt(e){if(_)return _.open(),_.api;let t={...gt,...e||{}};if(!t.wsUrl)throw new Error("VocantlyWidget.init requires wsUrl");if(!t.publicKey&&!(t.token&&t.conversationId))throw new Error("VocantlyWidget.init requires either { publicKey } (anonymous) or { token, conversationId }");if(t.publicKey&&!t.apiUrl)throw new Error("VocantlyWidget.init with publicKey also requires apiUrl");ut(t.primaryColor,t.position);let{root:s,$:i}=ft(t),n={panel:s.querySelector(".caf-panel"),msgs:i("msgs"),input:i("input"),send:i("send"),dot:i("dot"),badge:i("badge"),launcher:i("launcher"),call:i("call")},a=null,r=!1,l=()=>t.calls===!0||r;function c(){a&&D&&n.call&&(n.call.style.display="flex")}function h(){return new Promise((o,p)=>{if(window.VocantlyWidgetCall)return o();let g=document.createElement("script");g.src=t.callBundleUrl,g.async=!0,g.onload=()=>o(),g.onerror=()=>p(new Error("call bundle load failed")),document.head.appendChild(g)})}async function u(){if(!(a||!j))try{if(await h(),!window.VocantlyWidgetCall)return;let o=document.createElement("div");document.body.appendChild(o),a=window.VocantlyWidgetCall.mount(o,j,{logoText:"CA",sessionTitle:t.title||"Call",sessionSubtitle:t.subtitle||"Secured via Vocantly",primaryColor:t.primaryColor,self:{name:"You",role:"Visitor"},peer:{name:t.title||"Support",role:"Agent"},voiceOnly:!0,simple:!0}),n.call&&(n.call.onclick=()=>a.startCall("voice")),c()}catch(o){t.debug&&console.error("[caf] call setup failed",o)}}let d=t.token||"",y=t.conversationId||"",m=d?Ae(d):null,w=null,A=new Set,H=!1,O=!1,ce=0,le=!1,D=!t.collectContact,de=!1,L=o=>{n.dot.className="caf-dot"+(o?" "+o:"")},X=()=>{n.msgs.scrollTop=n.msgs.scrollHeight},he=o=>{ce=o,n.badge.textContent=String(o),n.badge.style.display=o>0?"flex":"none"};function Z(o,p){let g=document.createElement("div");g.className="caf-m "+o,g.innerHTML=p,n.msgs.appendChild(g),X()}function ge(o){var I,C,M,V,we,ve;if(o.optimistic)return;let p=(I=o.id)!=null?I:o.message_id,g=(M=(C=o.senderId)!=null?C:o.sender_id)!=null?M:"",f=(we=(V=o.content)!=null?V:o.text)!=null?we:"",b=p||`${g}:${f}`;if(A.has(b))return;if(A.add(b),((ve=o.messageType)!=null?ve:o.message_type)==="system"){Z("caf-note",Oe(f)),t.csat&&je();return}let T=m&&g===m;Z(T?"caf-self":"caf-other",Oe(f)),!T&&H&&pt(),!T&&!O&&he(ce+1)}let pe=!1;function je(){if(pe||!t.apiUrl||!y)return;pe=!0;let o=document.createElement("div");o.className="caf-csat",o.innerHTML=`<div>${R(t.csatPrompt)}</div><div class="caf-csat-row"></div>`;let p=o.querySelector(".caf-csat-row");[["1","\u{1F61E}"],["2","\u{1F641}"],["3","\u{1F610}"],["4","\u{1F642}"],["5","\u{1F600}"]].forEach(([g,f])=>{let b=document.createElement("button");b.className="caf-csat-b",b.type="button",b.textContent=f,b.setAttribute("aria-label",g+" out of 5"),b.onclick=()=>Ie(Number(g),o),p.appendChild(b)}),n.msgs.appendChild(o),X()}async function Ie(o,p){p.innerHTML=`<div>${R(t.csatThanks)}</div>`,X();try{await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/conversations/"+y+"/rating",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+d},body:JSON.stringify({rating:o})})}catch(g){t.debug&&console.error("[caf] csat failed",g)}}function ue(o){n.input.disabled=!o,n.send.disabled=!o,n.input.placeholder=o?t.placeholder:"\u2026"}function fe(){!le&&t.greeting&&(Z("caf-sys",R(t.greeting)),le=!0)}async function He(o,p){if(t.apiUrl)try{if(await B(),!d)return;let g=await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/customers/me",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:"Bearer "+d},body:JSON.stringify({name:o||void 0,email:p||void 0})});!g.ok&&t.debug&&console.error("[caf] saveContact HTTP "+g.status)}catch(g){t.debug&&console.error("[caf] saveContact failed",g)}}function De(){de=!0,n.panel.classList.add("caf-prechat");let o=document.createElement("form");o.className="caf-form",o.noValidate=!0,o.innerHTML=`
172
+ </button>`,document.body.appendChild(t),{root:t,$:s=>t.querySelector(`[data-caf="${s}"]`)}}function It(e){if(R)return R.open(),R.api;let t={...Tt,...e||{}};if(!t.wsUrl)throw new Error("VocantlyWidget.init requires wsUrl");if(!t.publicKey&&!(t.token&&t.conversationId))throw new Error("VocantlyWidget.init requires either { publicKey } (anonymous) or { token, conversationId }");if(t.publicKey&&!t.apiUrl)throw new Error("VocantlyWidget.init with publicKey also requires apiUrl");Rt(t.primaryColor,t.position);let{root:i,$:s}=At(t),n={panel:i.querySelector(".caf-panel"),msgs:s("msgs"),input:s("input"),send:s("send"),dot:s("dot"),badge:s("badge"),launcher:s("launcher"),call:s("call"),file:s("file"),attach:s("attach"),upload:s("upload"),uploadBar:s("upload-bar"),uploadLabel:s("upload-label")},a=null,r=!1,c=()=>t.calls===!0||r;function l(){a&&H&&n.call&&(n.call.style.display="flex")}function p(){return new Promise((o,h)=>{if(window.VocantlyWidgetCall)return o();let u=document.createElement("script");u.src=t.callBundleUrl,u.async=!0,u.onload=()=>o(),u.onerror=()=>h(new Error("call bundle load failed")),document.head.appendChild(u)})}async function m(){if(!(a||!A))try{if(await p(),!window.VocantlyWidgetCall)return;let o=document.createElement("div");document.body.appendChild(o),a=window.VocantlyWidgetCall.mount(o,A,{logoText:"CA",sessionTitle:t.title||"Call",sessionSubtitle:t.subtitle||"Secured via Vocantly",primaryColor:t.primaryColor,self:{name:"You",role:"Visitor"},peer:{name:t.title||"Support",role:"Agent"},voiceOnly:!0,simple:!0}),n.call&&(n.call.onclick=()=>a.startCall("voice")),l()}catch(o){t.debug&&console.error("[caf] call setup failed",o)}}let f=t.token||"",y=t.conversationId||"",v=f?Le(f):null,d=null,T=new Set,U=!1,O=!1,de=0,he=!1,H=!t.collectContact,pe=!1,L=o=>{n.dot.className="caf-dot"+(o?" "+o:"")},$=()=>{n.msgs.scrollTop=n.msgs.scrollHeight},fe=o=>{de=o,n.badge.textContent=String(o),n.badge.style.display=o>0?"flex":"none"};function B(o,h){let u=document.createElement("div");u.className="caf-m "+o,u.innerHTML=h,n.msgs.appendChild(u),$()}function ge(o){var I,P,xe,ke,Se,Ce;if(o.optimistic)return;let h=(I=o.id)!=null?I:o.message_id,u=(xe=(P=o.senderId)!=null?P:o.sender_id)!=null?xe:"",w=(Se=(ke=o.content)!=null?ke:o.text)!=null?Se:"",g=(Ce=o.messageType)!=null?Ce:o.message_type,b=o.attachments,C=h||`${u}:${w}`;if(T.has(C))return;if(T.add(C),g==="system"){B("caf-note",le(w)),t.csat&&Pe();return}let k=v&&u===v;(g==="image"||g==="video"||g==="file")&&b&&b.length?Fe(k,w,g,b[0]):B(k?"caf-self":"caf-other",le(w)),!k&&U&&Et(),!k&&!O&&fe(de+1)}function $e(o,h){return`<div class="caf-media-skeleton" style="${o!=="file"&&h.width&&h.height?`aspect-ratio:${h.width}/${h.height};`:"aspect-ratio:4/3;"}"></div>`}function ue(o,h){let u=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>
173
+ <span class="caf-file-meta"><span class="caf-file-name">${E(o.file_name)}</span><span class="caf-file-size">${E(Mt(o.size_bytes))}</span></span>`;return h?`<a class="caf-file-chip" href="${h}" target="_blank" rel="noopener noreferrer" download="${E(o.file_name)}">${u}</a>`:`<div class="caf-file-chip">${u}</div>`}function Fe(o,h,u,w){let g=document.createElement("div");if(g.className="caf-m caf-media "+(o?"caf-self":"caf-other"),g.innerHTML=`<div class="caf-media-body" data-media>${u==="file"?ue(w):$e(u,w)}</div>`,h){let b=document.createElement("div");b.className="caf-media-caption",b.innerHTML=le(h),g.appendChild(b)}n.msgs.appendChild(g),$(),d&&d.conversations.getAttachmentDownloadUrl(w.bucket,w.key).then(b=>{let C=g.querySelector("[data-media]");C&&(u==="image"?C.innerHTML=`<a href="${b.url}" target="_blank" rel="noopener noreferrer"><img src="${b.url}" alt="${E(w.file_name)}" loading="lazy" /></a>`:u==="video"?C.innerHTML=`<video src="${b.url}" controls preload="metadata"></video>`:C.innerHTML=ue(w,b.url),$())}).catch(b=>{t.debug&&console.error("[caf] attachment load failed",b);let C=g.querySelector("[data-media]");C&&(C.innerHTML=`<div class="caf-media-error">Couldn't load ${E(w.file_name)}</div>`)})}let me=!1;function Pe(){if(me||!t.apiUrl||!y)return;me=!0;let o=document.createElement("div");o.className="caf-csat",o.innerHTML=`<div>${E(t.csatPrompt)}</div><div class="caf-csat-row"></div>`;let h=o.querySelector(".caf-csat-row");[["1","\u{1F61E}"],["2","\u{1F641}"],["3","\u{1F610}"],["4","\u{1F642}"],["5","\u{1F600}"]].forEach(([u,w])=>{let g=document.createElement("button");g.className="caf-csat-b",g.type="button",g.textContent=w,g.setAttribute("aria-label",u+" out of 5"),g.onclick=()=>Ve(Number(u),o),h.appendChild(g)}),n.msgs.appendChild(o),$()}async function Ve(o,h){h.innerHTML=`<div>${E(t.csatThanks)}</div>`,$();try{await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/conversations/"+y+"/rating",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+f},body:JSON.stringify({rating:o})})}catch(u){t.debug&&console.error("[caf] csat failed",u)}}function J(o){n.input.disabled=!o,n.send.disabled=!o,n.attach.disabled=!o,n.input.placeholder=o?t.placeholder:"\u2026"}function we(){!he&&t.greeting&&(B("caf-sys",E(t.greeting)),he=!0)}async function Ne(o,h){if(t.apiUrl)try{if(await Y(),!f)return;let u=await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/customers/me",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:"Bearer "+f},body:JSON.stringify({name:o||void 0,email:h||void 0})});!u.ok&&t.debug&&console.error("[caf] saveContact HTTP "+u.status)}catch(u){t.debug&&console.error("[caf] saveContact failed",u)}}function ze(){pe=!0,n.panel.classList.add("caf-prechat");let o=document.createElement("form");o.className="caf-form",o.noValidate=!0,o.innerHTML=`
140
174
  <div class="caf-form-icon" aria-hidden="true">
141
175
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M20 15a4 4 0 0 1-4 4H8l-5 3v-7a4 4 0 0 1-1-2.65V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4v8Z"/><path d="M7 9h10M7 13h6"/></svg>
142
176
  </div>
143
- <div class="caf-form-t">${R(t.contactPrompt)}</div>
177
+ <div class="caf-form-t">${E(t.contactPrompt)}</div>
144
178
  <p class="caf-form-d">Share a few details so our team can give you more personal support.</p>
145
179
  <label class="caf-fl" for="caf-contact-name">Name
146
180
  <input class="caf-fi" id="caf-contact-name" data-caf="f-name" name="name" type="text" autocomplete="name" placeholder="How should we address you?" />
@@ -151,4 +185,4 @@ var $e=Object.create;var K=Object.defineProperty;var Ve=Object.getOwnPropertyDes
151
185
  <div class="caf-ferr" id="caf-contact-error" data-caf="f-err" role="alert" aria-live="polite"></div>
152
186
  <button class="caf-fbtn" data-caf="f-go" type="submit"><span>Start conversation</span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button>
153
187
  ${t.requireEmail?"":'<button class="caf-fskip" data-caf="f-skip" type="button">Continue without details</button>'}
154
- <p class="caf-form-privacy">Your details are only used to support this conversation.</p>`,n.msgs.appendChild(o);let p=T=>o.querySelector(`[data-caf="${T}"]`),g=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,f=async T=>{let I=p("f-name").value.trim(),C=p("f-email").value.trim(),M=p("f-email");if(p("f-err").textContent="",M.setAttribute("aria-invalid","false"),T){if(t.requireEmail&&!C){p("f-err").textContent="Email is required.",M.setAttribute("aria-invalid","true"),M.focus();return}if(C&&!g.test(C)){p("f-err").textContent="Enter a valid email.",M.setAttribute("aria-invalid","true"),M.focus();return}let V=p("f-go");V.disabled=!0,V.querySelector("span").textContent="Starting\u2026",await He(I,C)}o.remove(),n.panel.classList.remove("caf-prechat"),D=!0,c(),ue(!0),fe(),setTimeout(()=>n.input.focus(),30)};o.onsubmit=T=>{T.preventDefault(),f(!0)};let b=p("f-skip");b&&(b.onclick=()=>f(!1)),setTimeout(()=>p("f-name").focus(),40)}function z(){if(O=!0,n.panel.classList.add("open"),n.panel.setAttribute("aria-hidden","false"),n.launcher.setAttribute("aria-expanded","true"),n.launcher.setAttribute("aria-label","Close support chat"),he(0),B(),!D&&!de){De();return}D&&(fe(),setTimeout(()=>n.input.focus(),50))}function J(){O=!1,n.panel.classList.remove("open"),n.panel.setAttribute("aria-hidden","true"),n.launcher.setAttribute("aria-expanded","false"),n.launcher.setAttribute("aria-label","Open support chat"),n.launcher.focus()}n.launcher.onclick=()=>O?J():z(),i("close").onclick=J;let j=null;function ee(){if(!D)return;let o=n.input.value.trim();if(!(!o||!j))try{j.sendMessage(o),n.input.value="",n.input.style.height="auto"}catch(p){t.debug&&console.error("[caf] send failed",p)}}n.send.onclick=ee,ue(D),n.input.addEventListener("input",()=>{n.input.style.height="auto",n.input.style.height=Math.min(n.input.scrollHeight,96)+"px"}),n.input.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),ee())});let te=t.publicKey?"caf_session_"+t.publicKey.slice(-10):"",Le=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";function me(){if(!te)return null;try{let o=JSON.parse(localStorage.getItem(te)||"null");if(o&&o.token&&o.conversationId&&o.exp>Date.now())return o}catch{}return null}async function Ue(){let o=t.apiUrl.replace(/\/$/,""),p=te,g=Le,f=me();if(f)return r=!!f.calls_enabled,{token:f.token,conversationId:f.conversationId};let b=null;try{b=localStorage.getItem(g)}catch{}if(!b){b="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(g,b)}catch{}}let T=await fetch(o+"/sdk/anonymous-session",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({visitor_id:b})});if(!T.ok)throw new Error("anonymous-session HTTP "+T.status);let I=await T.json(),C=I.data||I;r=!!C.calls_enabled;let M=Date.now()+Math.max(0,(C.expires_in||3600)*1e3-6e4);try{localStorage.setItem(p,JSON.stringify({token:C.token,conversationId:C.conversation_id,exp:M,calls_enabled:r}))}catch{}return{token:C.token,conversationId:C.conversation_id}}let $=null;function B(){return $||($=(async()=>{var o,p,g;try{if(L(""),t.publicKey){let f=await Ue();d=f.token,y=f.conversationId,m=Ae(d)}if(w=new Re({wsUrl:t.wsUrl,token:d,apiUrl:t.apiUrl,autoReconnect:!0,debug:t.debug}),w.on("connected",()=>L("on")),w.on("disconnected",()=>L("")),w.on("reconnecting",()=>L("")),w.on("error",()=>L("err")),await w.connect(),await w.conversations.join(y),j=w.conversations.get(y),j.on("message",ge),t.apiUrl&&typeof j.fetchMessages=="function")try{let f=await j.fetchMessages({limit:30});((g=(p=f==null?void 0:f.messages)!=null?p:(o=f==null?void 0:f.data)==null?void 0:o.messages)!=null?g:[]).forEach(ge)}catch{}H=!0,l()&&u()}catch(f){L("err"),$=null,t.debug&&console.error("[caf] connect/provision failed",f)}})(),$)}(!t.publicKey||me())&&B(),t.autoOpen&&z();let be={open:z,close:J,send:async o=>{await B(),n.input.value=o,ee()},destroy:()=>{try{w==null||w.disconnect()}catch{}s.remove(),_=null}};return _={open:z,close:J,api:be},be}function bt(){_==null||_.open()}function wt(){_==null||_.close()}function vt(){_==null||_.api.destroy()}
188
+ <p class="caf-form-privacy">Your details are only used to support this conversation.</p>`,n.msgs.appendChild(o);let h=b=>o.querySelector(`[data-caf="${b}"]`),u=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,w=async b=>{let C=h("f-name").value.trim(),k=h("f-email").value.trim(),I=h("f-email");if(h("f-err").textContent="",I.setAttribute("aria-invalid","false"),b){if(t.requireEmail&&!k){h("f-err").textContent="Email is required.",I.setAttribute("aria-invalid","true"),I.focus();return}if(k&&!u.test(k)){h("f-err").textContent="Enter a valid email.",I.setAttribute("aria-invalid","true"),I.focus();return}let P=h("f-go");P.disabled=!0,P.querySelector("span").textContent="Starting\u2026",await Ne(C,k)}o.remove(),n.panel.classList.remove("caf-prechat"),H=!0,l(),J(!0),we(),setTimeout(()=>n.input.focus(),30)};o.onsubmit=b=>{b.preventDefault(),w(!0)};let g=h("f-skip");g&&(g.onclick=()=>w(!1)),setTimeout(()=>h("f-name").focus(),40)}function K(){if(O=!0,n.panel.classList.add("open"),n.panel.setAttribute("aria-hidden","false"),n.launcher.setAttribute("aria-expanded","true"),n.launcher.setAttribute("aria-label","Close support chat"),fe(0),Y(),!H&&!pe){ze();return}H&&(we(),setTimeout(()=>n.input.focus(),50))}function Q(){O=!1,n.panel.classList.remove("open"),n.panel.setAttribute("aria-hidden","true"),n.launcher.setAttribute("aria-expanded","false"),n.launcher.setAttribute("aria-label","Open support chat"),n.launcher.focus()}n.launcher.onclick=()=>O?Q():K(),s("close").onclick=Q;let A=null;function ie(){if(!H)return;let o=n.input.value.trim();if(!(!o||!A))try{A.sendMessage(o),n.input.value="",n.input.style.height="auto"}catch(h){t.debug&&console.error("[caf] send failed",h)}}function be(o,h){n.upload.classList.add("show"),n.uploadBar.style.width=h+"%",n.uploadLabel.textContent=`Sending ${o}\u2026 ${h}%`}function We(){n.upload.classList.remove("show")}async function qe(o){if(!(!H||!A)){J(!1),be(o.name,0);try{await A.sendMedia(o,{onProgress:h=>be(o.name,h)})}catch(h){t.debug&&console.error("[caf] sendMedia failed",h),B("caf-note","Couldn\u2019t send that file. Please try again.")}finally{We(),J(H)}}}n.attach.onclick=()=>n.file.click(),n.file.addEventListener("change",()=>{let o=n.file.files&&n.file.files[0];n.file.value="",o&&qe(o)}),n.send.onclick=ie,J(H),n.input.addEventListener("input",()=>{n.input.style.height="auto",n.input.style.height=Math.min(n.input.scrollHeight,96)+"px"}),n.input.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),ie())});let se=t.publicKey?"caf_session_"+t.publicKey.slice(-10):"",Be=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";function ve(){if(!se)return null;try{let o=JSON.parse(localStorage.getItem(se)||"null");if(o&&o.token&&o.conversationId&&o.exp>Date.now())return o}catch{}return null}async function Je(){let o=t.apiUrl.replace(/\/$/,""),h=se,u=Be,w=ve();if(w)return r=!!w.calls_enabled,{token:w.token,conversationId:w.conversationId};let g=null;try{g=localStorage.getItem(u)}catch{}if(!g){g="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(u,g)}catch{}}let b=await fetch(o+"/sdk/anonymous-session",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({visitor_id:g})});if(!b.ok)throw new Error("anonymous-session HTTP "+b.status);let C=await b.json(),k=C.data||C;r=!!k.calls_enabled;let I=Date.now()+Math.max(0,(k.expires_in||3600)*1e3-6e4);try{localStorage.setItem(h,JSON.stringify({token:k.token,conversationId:k.conversation_id,exp:I,calls_enabled:r}))}catch{}return{token:k.token,conversationId:k.conversation_id}}let F=null;function Y(){return F||(F=(async()=>{var o,h,u,w;try{if(L(""),t.publicKey){let g=await Je();f=g.token,y=g.conversationId,v=Le(f)}if(d=new Ue({wsUrl:t.wsUrl,token:f,apiUrl:t.apiUrl,appId:f?(o=De(f))==null?void 0:o.app_id:void 0,autoReconnect:!0,debug:t.debug}),d.on("connected",()=>L("on")),d.on("disconnected",()=>L("")),d.on("reconnecting",()=>L("")),d.on("error",()=>L("err")),await d.connect(),await d.conversations.join(y),A=d.conversations.get(y),A.on("message",ge),t.apiUrl&&typeof A.fetchMessages=="function")try{let g=await A.fetchMessages({limit:30});((w=(u=g==null?void 0:g.messages)!=null?u:(h=g==null?void 0:g.data)==null?void 0:h.messages)!=null?w:[]).forEach(ge)}catch{}U=!0,c()&&m()}catch(g){L("err"),F=null,t.debug&&console.error("[caf] connect/provision failed",g)}})(),F)}(!t.publicKey||ve())&&Y(),t.autoOpen&&K();let ye={open:K,close:Q,send:async o=>{await Y(),n.input.value=o,ie()},destroy:()=>{try{d==null||d.disconnect()}catch{}i.remove(),R=null}};return R={open:K,close:Q,api:ye},ye}function jt(){R==null||R.open()}function Ot(){R==null||R.close()}function Ht(){R==null||R.api.destroy()}