@vocantly/widget 0.1.13 → 0.1.15

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var U=(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 _e=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Ze=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ye(t))!Xe.call(e,n)&&n!==i&&Ce(e,n,{get:()=>t[n],enumerable:!(s=Qe(t,n))||s.enumerable});return e};var Te=(e,t,i)=>(i=e!=null?Ke(Ge(e)):{},Ze(t||!e||!e.__esModule?Ce(i,"default",{value:e,enumerable:!0}):i,e));var Ee=_e((It,ne)=>{"use strict";var et=Object.prototype.hasOwnProperty,_="~";function N(){}Object.create&&(N.prototype=Object.create(null),new N().__proto__||(_=!1));function tt(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 tt(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 N:delete e._events[t]}function S(){this._events=new N,this._eventsCount=0}S.prototype.eventNames=function(){var t=[],i,s;if(this._eventsCount===0)return t;for(s in i=this._events)et.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 N,this._eventsCount=0),this};S.prototype.off=S.prototype.removeListener;S.prototype.addListener=S.prototype.on;S.prefixed=_;S.EventEmitter=S;typeof ne!="undefined"&&(ne.exports=S)});var Ie=_e((Nt,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 M=Te(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,it=new Uint8Array(16);function re(){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(it)}var st=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ae={randomUUID:st};function nt(e,t,i){if(ae.randomUUID&&!t&&!e)return ae.randomUUID();e=e||{};var s=e.random||(e.rng||re)();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=nt;var Ct={};var rt=(e=>typeof U!="undefined"?U:typeof Proxy!="undefined"?new Proxy(e,{get:(t,i)=>(typeof U!="undefined"?U:t)[i]}):e)(function(e){if(typeof U!="undefined")return U.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)}},oe=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,$=null,z=null;async function at(){return oe?$||z||(z=(async()=>{try{try{return $=await Promise.resolve().then(()=>Te(Ie(),1)),$}catch(e){if(typeof rt!="undefined"){let{createRequire:t}=await import("module");return $=t(Ct.url||__filename)("ws"),$}throw e}}catch{return null}finally{z=null}})(),z):null}var ot=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(oe){let s=await at();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"),oe&&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)}},ct=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")}},lt=new Set(["text","system","image","video","file"]);function je(e){return e&&lt.has(e)?e:"text"}var W=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}}},dt=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")}},ht=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 dt(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,i,s="text",n,a){let r=W.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=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,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=W.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=W.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=W.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")}},pt=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):[]}},ft=[{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",q=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:ft,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)}},gt=6e4,ut=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:gt,this.submitCallQuality=t.submitCallQuality,q.isAvailable()&&(this.webRTC=new q({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 q.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:q.isAvailable()?new q({}):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 mt(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 wt(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 bt(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 vt=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 ht((s=i.debug)!=null?s:!1),this.typingManager=new pt((n=i.debug)!=null?n:!1),this.callManager=new ut(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 wt(e).catch(()=>{});n=d==null?void 0:d.width,a=d==null?void 0:d.height}else if(s.startsWith("video/")){let d=await bt(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}}},yt=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 L=await l.text(),O={};try{O=JSON.parse(L)}catch{O={message:L}}throw new Error(O.message||`HTTP ${l.status}: ${L}`)}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 mt(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 vt(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")}},xt=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")}},kt=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(){}},St=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 kt(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 ct,this.tokenManager.setToken(e.token),this.logger=new j(this.config.debug),this.wsClient=new ot(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new St(c=>this.conversationManager.get(c),this.config.debug),this.conversationManager=new yt(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 xt(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 _t={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 Tt(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 ce(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 B=null;function Mt(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;B=B||new e,B.resume&&B.resume();let t=B,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 Et(e,t){if(document.getElementById("caf-widget-styles"))return;let a=`
1
+ var Xe=Object.create;var Me=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var I=(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 Ee=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var nt=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of et(t))!it.call(e,s)&&s!==i&&Me(e,s,{get:()=>t[s],enumerable:!(n=Ze(t,s))||n.enumerable});return e};var Re=(e,t,i)=>(i=e!=null?Xe(tt(e)):{},nt(t||!e||!e.__esModule?Me(i,"default",{value:e,enumerable:!0}):i,e));var je=Ee((It,ae)=>{"use strict";var st=Object.prototype.hasOwnProperty,_="~";function z(){}Object.create&&(z.prototype=Object.create(null),new z().__proto__||(_=!1));function rt(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function Ae(e,t,i,n,s){if(typeof i!="function")throw new TypeError("The listener must be a function");var a=new rt(i,n||e,s),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 ee(e,t){--e._eventsCount===0?e._events=new z:delete e._events[t]}function S(){this._events=new z,this._eventsCount=0}S.prototype.eventNames=function(){var t=[],i,n;if(this._eventsCount===0)return t;for(n in i=this._events)st.call(i,n)&&t.push(_?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(i)):t};S.prototype.listeners=function(t){var i=_?_+t:t,n=this._events[i];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,r=new Array(a);s<a;s++)r[s]=n[s].fn;return r};S.prototype.listenerCount=function(t){var i=_?_+t:t,n=this._events[i];return n?n.fn?1:n.length:0};S.prototype.emit=function(t,i,n,s,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,n),!0;case 4:return l.fn.call(l.context,i,n,s),!0;case 5:return l.fn.call(l.context,i,n,s,a),!0;case 6:return l.fn.call(l.context,i,n,s,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,n);break;case 4:l[f].fn.call(l[f].context,i,n,s);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,n){return Ae(this,t,i,n,!1)};S.prototype.once=function(t,i,n){return Ae(this,t,i,n,!0)};S.prototype.removeListener=function(t,i,n,s){var a=_?_+t:t;if(!this._events[a])return this;if(!i)return ee(this,a),this;var r=this._events[a];if(r.fn)r.fn===i&&(!s||r.once)&&(!n||r.context===n)&&ee(this,a);else{for(var c=0,l=[],p=r.length;c<p;c++)(r[c].fn!==i||s&&!r[c].once||n&&r[c].context!==n)&&l.push(r[c]);l.length?this._events[a]=l.length===1?l[0]:l:ee(this,a)}return this};S.prototype.removeAllListeners=function(t){var i;return t?(i=_?_+t:t,this._events[i]&&ee(this,i)):(this._events=new z,this._eventsCount=0),this};S.prototype.off=S.prototype.removeListener;S.prototype.addListener=S.prototype.on;S.prefixed=_;S.EventEmitter=S;typeof ae!="undefined"&&(ae.exports=S)});var Ue=Ee((Bt,Oe)=>{"use strict";Oe.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var M=Re(je(),1);var x=[];for(te=0;te<256;++te)x.push((te+256).toString(16).slice(1));var te;function He(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 ie,at=new Uint8Array(16);function oe(){if(!ie&&(ie=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ie))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ie(at)}var ot=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ce={randomUUID:ot};function ct(e,t,i){if(ce.randomUUID&&!t&&!e)return ce.randomUUID();e=e||{};var n=e.random||(e.rng||oe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){i=i||0;for(var s=0;s<16;++s)t[i+s]=n[s];return t}return He(n)}var ne=ct;var Et={};var lt=(e=>typeof I!="undefined"?I:typeof Proxy!="undefined"?new Proxy(e,{get:(t,i)=>(typeof I!="undefined"?I:t)[i]}):e)(function(e){if(typeof I!="undefined")return I.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var H=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)}},le=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,D=null,W=null;async function dt(){return le?D||W||(W=(async()=>{try{try{return D=await Promise.resolve().then(()=>Re(Ue(),1)),D}catch(e){if(typeof lt!="undefined"){let{createRequire:t}=await import("module");return D=t(Et.url||__filename)("ws"),D}throw e}}catch{return null}finally{W=null}})(),W):null}var ht=class extends M.default{constructor(e,t={}){var i,n,s;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=(n=t.maxReconnectAttempts)!=null?n:5,this.logger=new H((s=t.debug)!=null?s:!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(le){let n=await dt();if(this.logger.debug("ws module loaded:",!!n),n&&n.WebSocket)return this.logger.debug("Using ws package with Authorization header"),new Promise((s,a)=>{try{let r=new n.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(s,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((n,s)=>{try{if(!t||t.length===0){let c=new Error("Token is required for WebSocket connection");this.logger.error(c.message),s(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(n,s),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),s(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 n=JSON.parse(i.data);this.logger.debug("Received message:",n),this.emit("message",n)}catch(n){let s=n instanceof Error?n:new Error("Failed to parse message");this.logger.error("Failed to parse message:",s),this.emit("error",s)}},this.ws.onerror=i=>{this.logger.error("WebSocket error:",i);let n;if(i instanceof Error?n=i:i&&i.message?n=i instanceof Error?i:new Error(String(i.message)):n=new Error("WebSocket connection error"),le&&i&&i.message){let s=String(i.message).toLowerCase();if(s.includes("401")||s.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",n)},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 s=new Error("Token expired or invalid. Please refresh your token and reconnect.");s.name="TokenExpiredError",this.emit("error",s),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)}},pt=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")}},ft=new Set(["text","system","image","video","file"]);function Ie(e){return e&&ft.has(e)?e:"text"}var q=class{static createOptimistic(e,t,i,n="text",s,a){return{id:t,conversationId:e,content:i,messageType:n,optimistic:!0,receiptState:"sent",createdAt:new Date,metadata:s,attachments:a}}static fromServerPayload(e,t){var s,a;let i=(s=t.sender_id)!=null?s:t.senderId,n=(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:n,messageType:Ie(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 s,a,r,c;let i=(s=t.sender_id)!=null?s:t.senderId,n=(a=t.sender_type)!=null?a:t.senderType;return{...e,optimistic:!1,senderId:i,senderName:t.sender_name,senderType:n,messageType:Ie(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}}},gt=class extends M.default{constructor(e=!1){super(),this.receiptState=new Map,this.logger=new H(e)}getReceiptState(e){return this.receiptState.get(e)}handleDelivered(e,t){var n;if(!e)return this.logger.warn("Invalid delivered receipt: missing messageId"),!1;let i=(n=this.receiptState.get(e))!=null?n:"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 n;if(!e)return this.logger.warn("Invalid read receipt: missing messageId"),!1;let i=(n=this.receiptState.get(e))!=null?n:"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"],n=i.indexOf(e),s=i.indexOf(t);return n===-1||s===-1?0:n-s}clearConversation(e,t){let i=0;for(let n of t)this.receiptState.has(n)&&(this.receiptState.delete(n),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")}},ut=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 H(e),this.receiptManager=new gt(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,i,n="text",s,a){let r=q.createOptimistic(e,t,i,n,s,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,n=this.getOptimisticMessage(e,i);if(n){let a=this.reconcileOptimisticMessage(n,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 s=q.fromServerPayload(e,t);return s.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,s),this.emit("message",s),this.logger.debug("Handled incoming message:",i),s}handleReceipt(e,t,i,n){i==="delivered"?this.receiptManager.handleDelivered(t,n):i==="read"&&this.receiptManager.handleRead(t,n)}updateMessageReceiptState(e){for(let[,t]of this.confirmedMessages.entries()){let i=t.get(e.messageId);if(i){let n=q.updateReceiptState(i,e.state);t.set(e.messageId,n),this.emit("message",n),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 n=q.updateReceiptState(i,e.state);t.set(e.messageId,n),this.emit("message",n),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=q.confirmOptimistic(e,t);return this.logger.debug("Reconciled optimistic message (no second emit):",e.id),i}hasSeenMessage(e,t){var n;let i=this.seenMessageIds.get(e);return(n=i==null?void 0:i.has(t))!=null?n:!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 n=this.optimisticMessages.get(e);n||(n=new Map,this.optimisticMessages.set(e,n)),n.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 n=this.confirmedMessages.get(e);n||(n=new Map,this.confirmedMessages.set(e,n)),n.set(t,i)}getMessageIds(e){let t=this.confirmedMessages.get(e),i=this.optimisticMessages.get(e),n=new Set;if(t)for(let s of t.keys())n.add(s);if(i)for(let s of i.keys())n.add(s);return Array.from(n)}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")}},mt=class extends M.default{constructor(e=!1){super(),this.typingTimers=new Map,this.activeTyping=new Map,this.TYPING_TIMEOUT_MS=5e3,this.logger=new H(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 n=this.typingTimers.get(e);n||(n=new Map,this.typingTimers.set(e,n));let s=i.has(t),a=n.get(t);a&&clearTimeout(a),i.add(t);let r=setTimeout(()=>{this.handleTypingStop(e,t)},this.TYPING_TIMEOUT_MS);n.set(t,r),s?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),n=this.typingTimers.get(e);if(!i||!i.has(t)){this.logger.debug("Typing stop ignored (user not typing):",e,t);return}let s=n==null?void 0:n.get(t);s&&(clearTimeout(s),n==null||n.delete(t)),i.delete(t),i.size===0&&this.activeTyping.delete(e),n&&n.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 n of t)this.emit("typing",{conversationId:e,userId:n,state:"stop"});this.activeTyping.delete(e)}if(i){for(let n of i.values())clearTimeout(n);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):[]}},wt=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],$e,Le=typeof RTCPeerConnection!="undefined"&&typeof navigator!="undefined"&&typeof(($e=navigator.mediaDevices)==null?void 0:$e.getUserMedia)=="function",B=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:wt,this.getIceServers=e.getIceServers,this.iceServersResolved=!e.getIceServers}static isAvailable(){return Le}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 n=!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}),n=Object.keys(a).length?a:!0}let s=await navigator.mediaDevices.getUserMedia({audio:i,video:n});return t.startMuted&&s.getAudioTracks().forEach(a=>a.enabled=!1),t.startVideoOff&&s.getVideoTracks().forEach(a=>a.enabled=!1),this.localStream=s,s}async createPeerConnection(e,t){if(!Le)return null;if(!this.iceServersResolved&&this.getIceServers)try{this.iceServers=await this.getIceServers(),this.iceServersResolved=!0}catch(s){this.options.debug&&console.warn("Failed to fetch ICE servers, using defaults:",s),this.iceServersResolved=!0}let i=new RTCPeerConnection({iceServers:this.iceServers}),n={pc:i};return this.peers.set(e,n),i.ontrack=s=>{s.streams[0]&&(n.remoteStream=s.streams[0],this.emit("remote_stream",{userId:e,stream:s.streams[0]}))},i.onicecandidate=s=>{s.candidate&&this.emit("ice_candidate",{userId:e,candidate:s.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 s=this.peers.get(e);s&&!s.hasRestartedIce&&typeof i.restartIce=="function"?(s.hasRestartedIce=!0,i.restartIce()):this.emit("ice_failed",{userId:e})}},i}async createOffer(e,t){let i=await this.getMedia(t),n=await this.createPeerConnection(e,t);if(!n)return null;i.getTracks().forEach(a=>n.addTrack(a,i));let s=await n.createOffer();return await n.setLocalDescription(s),s}async handleOffer(e,t,i){let n=await this.getMedia(i),s=await this.createPeerConnection(e,i);if(!s)return null;n.getTracks().forEach(r=>s.addTrack(r,n)),await s.setRemoteDescription(new RTCSessionDescription(t));let a=await s.createAnswer();return await s.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(n){this.options.debug&&console.warn("addIceCandidate failed:",n)}}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(s=>{var a;return((a=s.track)==null?void 0:a.kind)==="video"});if(!i)continue;let n=i.getParameters();(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]);for(let s of n.encodings)e==null?delete s.maxBitrate:s.maxBitrate=e;try{await i.setParameters(n)}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}}},n=await navigator.mediaDevices.getUserMedia(i),s=e==="video"?n.getVideoTracks()[0]:n.getAudioTracks()[0];if(!s)return;let a=e==="video"?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];a&&(s.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(s)}a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(s)}isScreenSharing(){return!!this.screenTrack}async startScreenShare(){var s,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=(s=this.localStream)==null?void 0:s.getVideoTracks()[0])!=null?a:null;let n=!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),n=!0)}return n?(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(n=>{var s;return((s=n.track)==null?void 0:s.kind)==="video"||n.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(n=>{var a,r,c,l,p,m,f,y,v,d;let s=n;if(n.type==="inbound-rtp")e.packets_lost_in=((a=e.packets_lost_in)!=null?a:0)+((r=s.packetsLost)!=null?r:0),e.packets_received=((c=e.packets_received)!=null?c:0)+((l=s.packetsReceived)!=null?l:0),e.bytes_received=((p=e.bytes_received)!=null?p:0)+((m=s.bytesReceived)!=null?m:0),typeof s.jitter=="number"&&(e.jitter_ms=s.jitter*1e3);else if(n.type==="outbound-rtp")e.packets_sent=((f=e.packets_sent)!=null?f:0)+((y=s.packetsSent)!=null?y:0),e.bytes_sent=((v=e.bytes_sent)!=null?v:0)+((d=s.bytesSent)!=null?d:0);else if(n.type==="candidate-pair"&&n.state==="succeeded"){let T=n.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)}},bt=6e4,vt=class extends M.default{constructor(e,t={}){var i,n;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 H((i=t.debug)!=null?i:!1),this.ringTimeoutMs=(n=t.ringTimeout)!=null?n:bt,this.submitCallQuality=t.submitCallQuality,B.isAvailable()&&(this.webRTC=new B({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 B.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 n;let t=(n=e.from_user_id)!=null?n: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 s=await this.webRTC.handleOffer(t,i,this.currentCallType);if(s){this.sendAnswer(t,s);let a=this.webRTC.getLocalStream(),r=this.webRTC.getRemoteStream(t);a&&r&&this.emitCallConnected(a,r,t)}}catch(s){this.logger.debug("WebRTC handleOffer failed:",s),this.emit("call_error",{reason:"permission_denied",message:String(s)})}this.emit("call_offer",{sdp:i,fromUserId:t})}}async handleCallAnswer(e){var n;let t=(n=e.from_user_id)!=null?n:e.sender_id,i=e.sdp;if(!(!t||!i)){if(this.webRTC){await this.webRTC.handleAnswer(t,i);let s=this.webRTC.getLocalStream(),a=this.webRTC.getRemoteStream(t);s&&a&&this.emitCallConnected(s,a,t)}this.emit("call_answer",{sdp:i,fromUserId:t})}}async handleCallICECandidate(e){var n;let t=(n=e.from_user_id)!=null?n: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 n;let i=(n=this.webRTC)==null?void 0:n.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,n={end_reason:e};this.callStartedAt!=null&&(n.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3));try{if(i){let s=await i.getCallStats();Object.assign(n,s)}}catch{}if(this.submitCallQuality)try{await this.submitCallQuality(this.conversationId,n,e)}catch(s){this.logger.debug("submitCallQuality failed:",s)}i==null||i.cleanup(),this.webRTC=t?null:B.isAvailable()?new B({}):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 yt(e,t,i,n){return new Promise((s,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=>{n&&c.lengthComputable&&n(Math.round(c.loaded/c.total*100))},r.onload=()=>{if(r.status>=200&&r.status<300)try{s(r.responseText?JSON.parse(r.responseText):{})}catch{s({})}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 xt(e){return new Promise((t,i)=>{let n=URL.createObjectURL(e),s=new Image;s.onload=()=>{URL.revokeObjectURL(n),t({width:s.naturalWidth,height:s.naturalHeight})},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to load image for dimension probing"))},s.src=n})}function kt(e){return new Promise((t,i)=>{let n=URL.createObjectURL(e),s=document.createElement("video");s.preload="metadata",s.onloadedmetadata=()=>{URL.revokeObjectURL(n),t({width:s.videoWidth,height:s.videoHeight,durationMs:Math.round(s.duration*1e3)})},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to load video for metadata probing"))},s.src=n})}var St=class extends M.default{constructor(e,t=!1){var n,s,a;super(),this._isJoined=!1;let i=typeof t=="boolean"?{debug:t}:t;this.id=e,this.messageManager=new ut((n=i.debug)!=null?n:!1),this.typingManager=new mt((s=i.debug)!=null?s:!1),this.callManager=new vt(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(n=>n.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 n=ne();this.messageManager.createOptimisticMessage(this.id,n,e,t,i);let s={type:"message",conversation_id:this.id,payload:{message_id:n,content:e,message_type:t}};try{this.sendMessageHandler(s)}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",n=e.type||"application/octet-stream",s,a,r;if(n.startsWith("image/")){let d=await xt(e).catch(()=>{});s=d==null?void 0:d.width,a=d==null?void 0:d.height}else if(n.startsWith("video/")){let d=await kt(e).catch(()=>{});s=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=ne(),p=[{bucket:c.bucket,key:c.key,file_name:c.fileName,mime_type:c.mimeType,size_bytes:c.sizeBytes,width:s,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 n=i instanceof Error?i:new Error("Failed to send read receipt");throw this.emit("error",n),n}}},Ct=class extends M.default{constructor(e,t=!1,i,n,s){super(),this.conversations=new Map,this.restFetcher=null,this.appId=null,this.iceServersCache=null,this.sendMessageHandler=e,this.sendTypingHandler=n,this.sendCallHandler=s,this.supportMessageHandler=i,this.debug=t,this.logger=new H(t)}setRestFetcher(e){if(this.restFetcher=e,e)for(let t of this.conversations.values())t.setSubmitCallQuality((i,n,s)=>this.submitCallQualityToApi(i,n,s))}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(),n=await fetch(t,{method:"GET",headers:i});if(!n.ok)throw new Error(`ICE servers fetch failed: ${n.status}`);let s=await n.json();if(!s.success||!((r=s.data)!=null&&r.iceServers))throw new Error("Invalid ICE servers response");let a=s.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(),n=Math.min(Math.max(1,(d=e==null?void 0:e.limit)!=null?d:20),100),s=new URLSearchParams({limit:String(n)});i&&s.set("external_user_id",i),e!=null&&e.cursor&&s.set("cursor",e.cursor);let a=s.toString(),r=`${t}/sdk/conversations${a?`?${a}`:""}`,c=await this.restFetcher.getHeaders(),l=await fetch(r,{method:"GET",headers:c});if(!l.ok){let L=await l.text(),O={};try{O=JSON.parse(L)}catch{O={message:L}}throw new Error(O.message||`HTTP ${l.status}: ${L}`)}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:n};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 n=Math.min(Math.max(1,(f=i.limit)!=null?f:20),100),s=new URLSearchParams({limit:String(n)});t!=null&&t.trim()&&s.set("external_user_id",t.trim()),i.cursor&&s.set("cursor",i.cursor);let a=this.restFetcher.apiUrl.replace(/\/$/,""),r=s.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:n}}}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`,s={...await this.restFetcher.getHeaders()};delete s["Content-Type"],delete s["content-type"];let a=new FormData;a.append("conversation_id",e.conversationId),a.append("file",e.file,e.fileName);let r=await yt(i,a,s,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(/\/$/,""),n=new URLSearchParams({bucket:e,key:t}),s=`${i}/apps/${encodeURIComponent(this.appId)}/uploads/url?${n.toString()}`,a=await this.restFetcher.getHeaders(),r=await fetch(s,{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 s=`${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(s,{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 St(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,n,s)=>this.submitCallQualityToApi(i,n,s)),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 n=this.conversations.get(t);n?n.isJoined?n.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 n=this.conversations.get(t);n?n.isJoined?n.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 n=this.conversations.get(t);if(n)if(n.isJoined){let s=e;n.handleReceipt(s.payload.message_id,s.payload.state,s.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 n=this.conversations.get(t);n&&n.isJoined&&n.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 n=this.get(t),s="payload"in e?e.payload:void 0;n.handleIncomingCallMessage(e.type,s)}break}}routeSupportMessage(e){var n;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=(n=e.payload)==null?void 0:n.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")}},_t=class extends M.default{constructor(e=!1){super(),this.presenceState=new Map,this.logger=new H(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 n=this.presenceState.get(i);n&&t.set(i,n)}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")}},Tt=class extends M.default{constructor(e,t,i,n=!1){super(),this.botActive=!1,this.status="queued",this.conversationId=e,this.conversation=t,this.role=i,this.logger=new H(n),this.conversation.on("message",s=>this.emit("message",s)),this.conversation.on("typing",s=>this.emit("typing",s)),this.conversation.on("presence",s=>this.emit("presence",s)),this.conversation.on("joined",s=>this.emit("joined",s)),this.conversation.on("left",s=>this.emit("left",s)),this.conversation.on("error",s=>this.emit("error",s))}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(){}},Mt=class extends M.default{constructor(e,t=!1){super(),this.sessions=new Map,this.getConversationHandler=e,this.debug=t,this.logger=new H(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 n=this.getConversationHandler(e);i=new Tt(e,n,t,this.debug),i.on("assigned",s=>this.emit("assigned",{conversationId:e,...s})),i.on("unassigned",s=>this.emit("unassigned",{conversationId:e,...s})),i.on("bot_takeover",()=>this.emit("bot_takeover",{conversationId:e})),i.on("bot_released",()=>this.emit("bot_released",{conversationId:e})),i.on("closed",s=>this.emit("closed",{conversationId:e,...s})),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 n=this.sessions.get(e);if(!n){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"&&n.handleAssigned(i.agent_id);break;case"unassigned":n.handleUnassigned();break;case"bot_takeover":n.handleBotTakeover();break;case"bot_released":n.handleBotReleased();break;case"closed":n.handleClosed();break;case"reopened":n.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")}},De=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 pt,this.tokenManager.setToken(e.token),this.logger=new H(this.config.debug),this.wsClient=new ht(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new Mt(c=>this.conversationManager.get(c),this.config.debug),this.conversationManager=new Ct(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 _t(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(),n=this.config.apiKey&&this.config.apiSecret,s=typeof this.config.getRestHeaders=="function";if(t){let c=async()=>{if(s&&this.config.getRestHeaders)return this.config.getRestHeaders();if(n)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 n=e instanceof Error?e:new Error("WebSocket connection error");this.emit("error",n),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 n=i instanceof Error?i:new Error("Failed to join conversation");throw this.emit("error",n),n}}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 n=i instanceof Error?i:new Error("Failed to leave conversation");throw this.emit("error",n),n}}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 Rt={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.15/dist/vocantly-widget-call.js"},R=null;function Pe(e){try{return JSON.parse(atob(e.split(".")[1]))}catch{return null}}function Fe(e){let t=Pe(e);return(t==null?void 0:t.user_id)||(t==null?void 0:t.sub)||null}function At(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 de(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 J=null;function jt(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;J=J||new e,J.resume&&J.resume();let t=J,i=t.currentTime,n=t.createOscillator(),s=t.createGain();n.type="sine",n.frequency.setValueAtTime(880,i),n.frequency.exponentialRampToValueAtTime(1320,i+.08),s.gain.setValueAtTime(1e-4,i),s.gain.exponentialRampToValueAtTime(.16,i+.02),s.gain.exponentialRampToValueAtTime(1e-4,i+.34),n.connect(s).connect(t.destination),n.start(i),n.stop(i+.36)}catch{}}function Ht(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;}
@@ -71,6 +71,17 @@ var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDe
71
71
  .caf-file-name{display:block;font-weight:650;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:150px;}
72
72
  .caf-file-size{display:block;font-size:11px;opacity:.7;white-space:nowrap;}
73
73
 
74
+ .caf-pending{display:none;align-items:center;gap:9px;padding:9px 14px;border-top:1px solid #e8ecf2;background:#fff;}
75
+ .caf-pending.show{display:flex;}
76
+ .caf-pending-thumb{width:38px;height:38px;border-radius:9px;background:#f1f3f7;flex:none;overflow:hidden;display:flex;align-items:center;justify-content:center;color:#8792a3;}
77
+ .caf-pending-thumb img{width:100%;height:100%;object-fit:cover;display:block;}
78
+ .caf-pending-thumb svg{width:18px;height:18px;}
79
+ .caf-pending-name{flex:1;min-width:0;font-size:12.5px;color:#344054;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
80
+ .caf-root .caf-pending-remove{width:26px!important;height:26px!important;padding:0!important;border-radius:999px!important;background:#f1f3f7!important;
81
+ color:#667085!important;border:0!important;flex:none;display:flex!important;align-items:center;justify-content:center;font-size:12px;cursor:pointer;
82
+ transition:background .15s ease,color .15s ease;}
83
+ .caf-root .caf-pending-remove:hover{background:#e6e9ee!important;color:#172033!important;}
84
+
74
85
  .caf-upload{display:none;align-items:center;gap:10px;padding:8px 14px;border-top:1px solid #e8ecf2;background:#fff;}
75
86
  .caf-upload.show{display:flex;}
76
87
  .caf-upload-label{flex:none;font-size:11.5px;color:#667085;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
@@ -138,7 +149,7 @@ var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDe
138
149
  }
139
150
  @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}}
140
151
  @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 Rt(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
152
+ `,r=document.createElement("style");r.id="caf-widget-styles",r.textContent=a,document.head.appendChild(r)}function Ot(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
142
153
  <div class="caf-panel" id="caf-support-panel" role="dialog" aria-labelledby="caf-support-title" aria-hidden="true">
143
154
  <div class="caf-header">
144
155
  <div class="caf-headmark" aria-hidden="true">
@@ -154,6 +165,11 @@ var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDe
154
165
  </button>
155
166
  </div>
156
167
  <div class="caf-msgs" data-caf="msgs"></div>
168
+ <div class="caf-pending" data-caf="pending">
169
+ <div class="caf-pending-thumb" data-caf="pending-thumb"></div>
170
+ <span class="caf-pending-name" data-caf="pending-name"></span>
171
+ <button class="caf-pending-remove" data-caf="pending-remove" type="button" aria-label="Remove attachment" title="Remove">\u2715</button>
172
+ </div>
157
173
  <div class="caf-upload" data-caf="upload">
158
174
  <span class="caf-upload-label" data-caf="upload-label"></span>
159
175
  <div class="caf-upload-track"><div class="caf-upload-bar" data-caf="upload-bar"></div></div>
@@ -169,8 +185,8 @@ var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDe
169
185
  <button class="caf-launcher" data-caf="launcher" aria-label="Open support chat" aria-controls="caf-support-panel" aria-expanded="false">
170
186
  <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>
171
187
  <span class="caf-badge" data-caf="badge" style="display:none">0</span>
172
- </button>`,document.body.appendChild(t),{root:t,$:s=>t.querySelector(`[data-caf="${s}"]`)}}function li(e){if(R)return R.open(),R.api;let t={..._t,...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");Et(t.primaryColor,t.position);let{root:i,$:s}=Rt(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,L=!1,O=!1,le=0,de=!1,H=!t.collectContact,he=!1,D=o=>{n.dot.className="caf-dot"+(o?" "+o:"")},F=()=>{n.msgs.scrollTop=n.msgs.scrollHeight},pe=o=>{le=o,n.badge.textContent=String(o),n.badge.style.display=o>0?"flex":"none"};function J(o,h){let u=document.createElement("div");u.className="caf-m "+o,u.innerHTML=h,n.msgs.appendChild(u),F()}function fe(o){var I,V,ye,xe,ke,Se;if(o.optimistic)return;let h=(I=o.id)!=null?I:o.message_id,u=(ye=(V=o.senderId)!=null?V:o.sender_id)!=null?ye:"",w=(ke=(xe=o.content)!=null?xe:o.text)!=null?ke:"",g=(Se=o.messageType)!=null?Se:o.message_type,b=o.attachments,C=h||`${u}:${w}`;if(T.has(C))return;if(T.add(C),g==="system"){J("caf-note",ce(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]):J(k?"caf-self":"caf-other",ce(w)),!k&&L&&Mt(),!k&&!O&&pe(le+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 ge(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(Tt(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"?ge(w):$e(u,w)}</div>`,h){let b=document.createElement("div");b.className="caf-media-caption",b.innerHTML=ce(h),g.appendChild(b)}n.msgs.appendChild(g),F(),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=ge(w,b.url),F())}).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 ue=!1;function Pe(){if(ue||!t.apiUrl||!y)return;ue=!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),F()}async function Ve(o,h){h.innerHTML=`<div>${E(t.csatThanks)}</div>`,F();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 K(o){n.input.disabled=!o,n.send.disabled=!o,n.attach.disabled=!o,n.input.placeholder=o?t.placeholder:"\u2026"}function me(){!de&&t.greeting&&(J("caf-sys",E(t.greeting)),de=!0)}async function Ne(o,h){if(t.apiUrl)try{if(await G(),!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(){he=!0,n.panel.classList.add("caf-prechat");let o=document.createElement("form");o.className="caf-form",o.noValidate=!0,o.innerHTML=`
188
+ </button>`,document.body.appendChild(t),{root:t,$:n=>t.querySelector(`[data-caf="${n}"]`)}}function fi(e){if(R)return R.open(),R.api;let t={...Rt,...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");Ht(t.primaryColor,t.position);let{root:i,$:n}=Ot(t),s={panel:i.querySelector(".caf-panel"),msgs:n("msgs"),input:n("input"),send:n("send"),dot:n("dot"),badge:n("badge"),launcher:n("launcher"),call:n("call"),file:n("file"),attach:n("attach"),upload:n("upload"),uploadBar:n("upload-bar"),uploadLabel:n("upload-label"),pending:n("pending"),pendingThumb:n("pending-thumb"),pendingName:n("pending-name"),pendingRemove:n("pending-remove")},a=null,r=!1,c=()=>t.calls===!0||r;function l(){a&&U&&s.call&&(s.call.style.display="flex")}function p(){return new Promise((o,h)=>{if(window.VocantlyWidgetCall)return o();let g=document.createElement("script");g.src=t.callBundleUrl,g.async=!0,g.onload=()=>o(),g.onerror=()=>h(new Error("call bundle load failed")),document.head.appendChild(g)})}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}),s.call&&(s.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?Fe(f):null,d=null,T=new Set,L=!1,O=!1,he=0,pe=!1,U=!t.collectContact,fe=!1,$=o=>{s.dot.className="caf-dot"+(o?" "+o:"")},F=()=>{s.msgs.scrollTop=s.msgs.scrollHeight},ge=o=>{he=o,s.badge.textContent=String(o),s.badge.style.display=o>0?"flex":"none"};function K(o,h){let g=document.createElement("div");g.className="caf-m "+o,g.innerHTML=h,s.msgs.appendChild(g),F()}function ue(o){var j,N,Se,Ce,_e,Te;if(o.optimistic)return;let h=(j=o.id)!=null?j:o.message_id,g=(Se=(N=o.senderId)!=null?N:o.sender_id)!=null?Se:"",w=(_e=(Ce=o.content)!=null?Ce:o.text)!=null?_e:"",u=(Te=o.messageType)!=null?Te:o.message_type,b=o.attachments,C=h||`${g}:${w}`;if(T.has(C))return;if(T.add(C),u==="system"){K("caf-note",de(w)),t.csat&&ze();return}let k=v&&g===v;(u==="image"||u==="video"||u==="file")&&b&&b.length?Ne(k,w,u,b[0]):K(k?"caf-self":"caf-other",de(w)),!k&&L&&jt(),!k&&!O&&ge(he+1)}function Ve(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 me(o,h){let g=`<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>
189
+ <span class="caf-file-meta"><span class="caf-file-name">${E(o.file_name)}</span><span class="caf-file-size">${E(At(o.size_bytes))}</span></span>`;return h?`<a class="caf-file-chip" href="${h}" target="_blank" rel="noopener noreferrer" download="${E(o.file_name)}">${g}</a>`:`<div class="caf-file-chip">${g}</div>`}function Ne(o,h,g,w){let u=document.createElement("div");if(u.className="caf-m caf-media "+(o?"caf-self":"caf-other"),u.innerHTML=`<div class="caf-media-body" data-media>${g==="file"?me(w):Ve(g,w)}</div>`,h){let b=document.createElement("div");b.className="caf-media-caption",b.innerHTML=de(h),u.appendChild(b)}s.msgs.appendChild(u),F(),d&&d.conversations.getAttachmentDownloadUrl(w.bucket,w.key).then(b=>{let C=u.querySelector("[data-media]");C&&(g==="image"?C.innerHTML=`<a href="${b.url}" target="_blank" rel="noopener noreferrer"><img src="${b.url}" alt="${E(w.file_name)}" loading="lazy" /></a>`:g==="video"?C.innerHTML=`<video src="${b.url}" controls preload="metadata"></video>`:C.innerHTML=me(w,b.url),F())}).catch(b=>{t.debug&&console.error("[caf] attachment load failed",b);let C=u.querySelector("[data-media]");C&&(C.innerHTML=`<div class="caf-media-error">Couldn't load ${E(w.file_name)}</div>`)})}let we=!1;function ze(){if(we||!t.apiUrl||!y)return;we=!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(([g,w])=>{let u=document.createElement("button");u.className="caf-csat-b",u.type="button",u.textContent=w,u.setAttribute("aria-label",g+" out of 5"),u.onclick=()=>We(Number(g),o),h.appendChild(u)}),s.msgs.appendChild(o),F()}async function We(o,h){h.innerHTML=`<div>${E(t.csatThanks)}</div>`,F();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(g){t.debug&&console.error("[caf] csat failed",g)}}function Q(o){s.input.disabled=!o,s.send.disabled=!o,s.attach.disabled=!o,s.input.placeholder=o?t.placeholder:"\u2026"}function be(){!pe&&t.greeting&&(K("caf-sys",E(t.greeting)),pe=!0)}async function qe(o,h){if(t.apiUrl)try{if(await Z(),!f)return;let g=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})});!g.ok&&t.debug&&console.error("[caf] saveContact HTTP "+g.status)}catch(g){t.debug&&console.error("[caf] saveContact failed",g)}}function Be(){fe=!0,s.panel.classList.add("caf-prechat");let o=document.createElement("form");o.className="caf-form",o.noValidate=!0,o.innerHTML=`
174
190
  <div class="caf-form-icon" aria-hidden="true">
175
191
  <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>
176
192
  </div>
@@ -185,4 +201,4 @@ var Ke=Object.create;var Ce=Object.defineProperty;var Qe=Object.getOwnPropertyDe
185
201
  <div class="caf-ferr" id="caf-contact-error" data-caf="f-err" role="alert" aria-live="polite"></div>
186
202
  <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>
187
203
  ${t.requireEmail?"":'<button class="caf-fskip" data-caf="f-skip" type="button">Continue without details</button>'}
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 V=h("f-go");V.disabled=!0,V.querySelector("span").textContent="Starting\u2026",await Ne(C,k)}o.remove(),n.panel.classList.remove("caf-prechat"),H=!0,l(),K(!0),me(),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 Q(){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"),pe(0),G(),!H&&!he){ze();return}H&&(me(),setTimeout(()=>n.input.focus(),50))}function Y(){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?Y():Q(),s("close").onclick=Y;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 we(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)){K(!1),we(o.name,0);try{await A.sendMedia(o,{onProgress:h=>we(o.name,h)})}catch(h){t.debug&&console.error("[caf] sendMedia failed",h),J("caf-note","Couldn\u2019t send that file. Please try again.")}finally{We(),K(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,K(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 be(){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=be();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 P=null;function G(){return P||(P=(async()=>{var o,h,u,w;try{if(D(""),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",()=>D("on")),d.on("disconnected",()=>D("")),d.on("reconnecting",()=>D("")),d.on("error",()=>D("err")),await d.connect(),await d.conversations.join(y),A=d.conversations.get(y),A.on("message",fe),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(fe)}catch{}L=!0,c()&&m()}catch(g){D("err"),P=null,t.debug&&console.error("[caf] connect/provision failed",g)}})(),P)}(!t.publicKey||be())&&G(),t.autoOpen&&Q();let ve={open:Q,close:Y,send:async o=>{await G(),n.input.value=o,ie()},destroy:()=>{try{d==null||d.disconnect()}catch{}i.remove(),R=null}};return R={open:Q,close:Y,api:ve},ve}function di(){R==null||R.open()}function hi(){R==null||R.close()}function pi(){R==null||R.api.destroy()}export{hi as close,pi as destroy,li as init,di as open};
204
+ <p class="caf-form-privacy">Your details are only used to support this conversation.</p>`,s.msgs.appendChild(o);let h=b=>o.querySelector(`[data-caf="${b}"]`),g=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,w=async b=>{let C=h("f-name").value.trim(),k=h("f-email").value.trim(),j=h("f-email");if(h("f-err").textContent="",j.setAttribute("aria-invalid","false"),b){if(t.requireEmail&&!k){h("f-err").textContent="Email is required.",j.setAttribute("aria-invalid","true"),j.focus();return}if(k&&!g.test(k)){h("f-err").textContent="Enter a valid email.",j.setAttribute("aria-invalid","true"),j.focus();return}let N=h("f-go");N.disabled=!0,N.querySelector("span").textContent="Starting\u2026",await qe(C,k)}o.remove(),s.panel.classList.remove("caf-prechat"),U=!0,l(),Q(!0),be(),setTimeout(()=>s.input.focus(),30)};o.onsubmit=b=>{b.preventDefault(),w(!0)};let u=h("f-skip");u&&(u.onclick=()=>w(!1)),setTimeout(()=>h("f-name").focus(),40)}function Y(){if(O=!0,s.panel.classList.add("open"),s.panel.setAttribute("aria-hidden","false"),s.launcher.setAttribute("aria-expanded","true"),s.launcher.setAttribute("aria-label","Close support chat"),ge(0),Z(),!U&&!fe){Be();return}U&&(be(),setTimeout(()=>s.input.focus(),50))}function G(){O=!1,s.panel.classList.remove("open"),s.panel.setAttribute("aria-hidden","true"),s.launcher.setAttribute("aria-expanded","false"),s.launcher.setAttribute("aria-label","Open support chat"),s.launcher.focus()}s.launcher.onclick=()=>O?G():Y(),n("close").onclick=G;let A=null,X=null,P=null;function ve(){P&&(URL.revokeObjectURL(P),P=null),X=null,s.pending.classList.remove("show"),s.pendingThumb.innerHTML="",s.pendingName.textContent=""}function Je(o){X=o,s.pendingName.textContent=o.name,o.type&&o.type.startsWith("image/")?(P=URL.createObjectURL(o),s.pendingThumb.innerHTML=`<img src="${P}" alt="" />`):s.pendingThumb.innerHTML='<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>',s.pending.classList.add("show"),setTimeout(()=>s.input.focus(),30)}function se(){if(!U)return;let o=s.input.value.trim();if(X){let h=X;ve(),s.input.value="",s.input.style.height="auto",Qe(h,o);return}if(!(!o||!A))try{A.sendMessage(o),s.input.value="",s.input.style.height="auto"}catch(h){t.debug&&console.error("[caf] send failed",h)}}function ye(o,h){s.upload.classList.add("show"),s.uploadBar.style.width=h+"%",s.uploadLabel.textContent=`Sending ${o}\u2026 ${h}%`}function Ke(){s.upload.classList.remove("show")}async function Qe(o,h){if(!(!U||!A)){Q(!1),ye(o.name,0);try{await A.sendMedia(o,{caption:h||void 0,onProgress:g=>ye(o.name,g)})}catch(g){t.debug&&console.error("[caf] sendMedia failed",g),K("caf-note","Couldn\u2019t send that file. Please try again.")}finally{Ke(),Q(U)}}}s.attach.onclick=()=>s.file.click(),s.file.addEventListener("change",()=>{let o=s.file.files&&s.file.files[0];s.file.value="",o&&Je(o)}),s.pendingRemove.onclick=()=>ve(),s.send.onclick=se,Q(U),s.input.addEventListener("input",()=>{s.input.style.height="auto",s.input.style.height=Math.min(s.input.scrollHeight,96)+"px"}),s.input.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),se())});let re=t.publicKey?"caf_session_"+t.publicKey.slice(-10):"",Ye=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";function xe(){if(!re)return null;try{let o=JSON.parse(localStorage.getItem(re)||"null");if(o&&o.token&&o.conversationId&&o.exp>Date.now())return o}catch{}return null}async function Ge(){let o=t.apiUrl.replace(/\/$/,""),h=re,g=Ye,w=xe();if(w)return r=!!w.calls_enabled,{token:w.token,conversationId:w.conversationId};let u=null;try{u=localStorage.getItem(g)}catch{}if(!u){u="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(g,u)}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:u})});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 j=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:j,calls_enabled:r}))}catch{}return{token:k.token,conversationId:k.conversation_id}}let V=null;function Z(){return V||(V=(async()=>{var o,h,g,w;try{if($(""),t.publicKey){let u=await Ge();f=u.token,y=u.conversationId,v=Fe(f)}if(d=new De({wsUrl:t.wsUrl,token:f,apiUrl:t.apiUrl,appId:f?(o=Pe(f))==null?void 0:o.app_id:void 0,autoReconnect:!0,debug:t.debug}),d.on("connected",()=>$("on")),d.on("disconnected",()=>$("")),d.on("reconnecting",()=>$("")),d.on("error",()=>$("err")),await d.connect(),await d.conversations.join(y),A=d.conversations.get(y),A.on("message",ue),t.apiUrl&&typeof A.fetchMessages=="function")try{let u=await A.fetchMessages({limit:30});((w=(g=u==null?void 0:u.messages)!=null?g:(h=u==null?void 0:u.data)==null?void 0:h.messages)!=null?w:[]).forEach(ue)}catch{}L=!0,c()&&m()}catch(u){$("err"),V=null,t.debug&&console.error("[caf] connect/provision failed",u)}})(),V)}(!t.publicKey||xe())&&Z(),t.autoOpen&&Y();let ke={open:Y,close:G,send:async o=>{await Z(),s.input.value=o,se()},destroy:()=>{try{d==null||d.disconnect()}catch{}i.remove(),R=null}};return R={open:Y,close:G,api:ke},ke}function gi(){R==null||R.open()}function ui(){R==null||R.close()}function mi(){R==null||R.api.destroy()}export{ui as close,mi as destroy,fi as init,gi as open};