@vocantly/widget 0.1.23 → 0.1.24

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 xt=Object.create;var Ne=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var B=(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 ze=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Tt=(e,t,i,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ct(t))!_t.call(e,n)&&n!==i&&Ne(e,n,{get:()=>t[n],enumerable:!(a=kt(t,n))||a.enumerable});return e};var We=(e,t,i)=>(i=e!=null?xt(St(e)):{},Tt(t||!e||!e.__esModule?Ne(i,"default",{value:e,enumerable:!0}):i,e));var Je=ze((si,ve)=>{"use strict";var Mt=Object.prototype.hasOwnProperty,A="~";function G(){}Object.create&&(G.prototype=Object.create(null),new G().__proto__||(A=!1));function Et(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function Be(e,t,i,a,n){if(typeof i!="function")throw new TypeError("The listener must be a function");var o=new Et(i,a||e,n),r=A?A+t:t;return e._events[r]?e._events[r].fn?e._events[r]=[e._events[r],o]:e._events[r].push(o):(e._events[r]=o,e._eventsCount++),e}function he(e,t){--e._eventsCount===0?e._events=new G:delete e._events[t]}function E(){this._events=new G,this._eventsCount=0}E.prototype.eventNames=function(){var t=[],i,a;if(this._eventsCount===0)return t;for(a in i=this._events)Mt.call(i,a)&&t.push(A?a.slice(1):a);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(i)):t};E.prototype.listeners=function(t){var i=A?A+t:t,a=this._events[i];if(!a)return[];if(a.fn)return[a.fn];for(var n=0,o=a.length,r=new Array(o);n<o;n++)r[n]=a[n].fn;return r};E.prototype.listenerCount=function(t){var i=A?A+t:t,a=this._events[i];return a?a.fn?1:a.length:0};E.prototype.emit=function(t,i,a,n,o,r){var l=A?A+t:t;if(!this._events[l])return!1;var d=this._events[l],f=arguments.length,v,b;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),f){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,a),!0;case 4:return d.fn.call(d.context,i,a,n),!0;case 5:return d.fn.call(d.context,i,a,n,o),!0;case 6:return d.fn.call(d.context,i,a,n,o,r),!0}for(b=1,v=new Array(f-1);b<f;b++)v[b-1]=arguments[b];d.fn.apply(d.context,v)}else{var R=d.length,k;for(b=0;b<R;b++)switch(d[b].once&&this.removeListener(t,d[b].fn,void 0,!0),f){case 1:d[b].fn.call(d[b].context);break;case 2:d[b].fn.call(d[b].context,i);break;case 3:d[b].fn.call(d[b].context,i,a);break;case 4:d[b].fn.call(d[b].context,i,a,n);break;default:if(!v)for(k=1,v=new Array(f-1);k<f;k++)v[k-1]=arguments[k];d[b].fn.apply(d[b].context,v)}}return!0};E.prototype.on=function(t,i,a){return Be(this,t,i,a,!1)};E.prototype.once=function(t,i,a){return Be(this,t,i,a,!0)};E.prototype.removeListener=function(t,i,a,n){var o=A?A+t:t;if(!this._events[o])return this;if(!i)return he(this,o),this;var r=this._events[o];if(r.fn)r.fn===i&&(!n||r.once)&&(!a||r.context===a)&&he(this,o);else{for(var l=0,d=[],f=r.length;l<f;l++)(r[l].fn!==i||n&&!r[l].once||a&&r[l].context!==a)&&d.push(r[l]);d.length?this._events[o]=d.length===1?d[0]:d:he(this,o)}return this};E.prototype.removeAllListeners=function(t){var i;return t?(i=A?A+t:t,this._events[i]&&he(this,i)):(this._events=new G,this._eventsCount=0),this};E.prototype.off=E.prototype.removeListener;E.prototype.addListener=E.prototype.on;E.prefixed=A;E.EventEmitter=E;typeof ve!="undefined"&&(ve.exports=E)});var Qe=ze((bi,Ye)=>{"use strict";Ye.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var $=We(Je(),1);var M=[];for(pe=0;pe<256;++pe)M.push((pe+256).toString(16).slice(1));var pe;function Ke(e,t=0){return(M[e[t+0]]+M[e[t+1]]+M[e[t+2]]+M[e[t+3]]+"-"+M[e[t+4]]+M[e[t+5]]+"-"+M[e[t+6]]+M[e[t+7]]+"-"+M[e[t+8]]+M[e[t+9]]+"-"+M[e[t+10]]+M[e[t+11]]+M[e[t+12]]+M[e[t+13]]+M[e[t+14]]+M[e[t+15]]).toLowerCase()}var fe,Rt=new Uint8Array(16);function ye(){if(!fe&&(fe=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!fe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return fe(Rt)}var At=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),xe={randomUUID:At};function $t(e,t,i){if(xe.randomUUID&&!t&&!e)return xe.randomUUID();e=e||{};var a=e.random||(e.rng||ye)();if(a[6]=a[6]&15|64,a[8]=a[8]&63|128,t){i=i||0;for(var n=0;n<16;++n)t[i+n]=a[n];return t}return Ke(a)}var X=$t;var Zt={};var Ut=(e=>typeof B!="undefined"?B:typeof Proxy!="undefined"?new Proxy(e,{get:(t,i)=>(typeof B!="undefined"?B:t)[i]}):e)(function(e){if(typeof B!="undefined")return B.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var D=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)}},ke=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,K=null,Z=null;async function It(){return ke?K||Z||(Z=(async()=>{try{try{return K=await Promise.resolve().then(()=>We(Qe(),1)),K}catch(e){if(typeof Ut!="undefined"){let{createRequire:t}=await import("module");return K=t(Zt.url||__filename)("ws"),K}throw e}}catch{return null}finally{Z=null}})(),Z):null}var jt=class extends $.default{constructor(e,t={}){var i,a,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=(a=t.maxReconnectAttempts)!=null?a:5,this.logger=new D((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(ke){let a=await It();if(this.logger.debug("ws module loaded:",!!a),a&&a.WebSocket)return this.logger.debug("Using ws package with Authorization header"),new Promise((n,o)=>{try{let r=new a.WebSocket(e.toString(),{headers:{Authorization:`Bearer ${t}`}});this.ws=r;let l=!1,d=f=>{if(l)return;l=!0;let v=String((f==null?void 0:f.message)||f||"").toLowerCase();if(v.includes("401")||v.includes("unauthorized")||f!=null&&f.code&&String(f.code).includes("401")){this.handleTokenExpiration();let b=new Error("Token expired or invalid. Please refresh your token and reconnect.");b.name="TokenExpiredError",this.emit("error",b),o(b);return}};typeof r.addEventListener=="function"?(r.addEventListener("error",d),r.addEventListener("open",()=>{r.removeEventListener("error",d)})):typeof r.once=="function"&&(r.once("error",d),r.once("open",()=>{})),this.setupEventHandlers(n,o)}catch(r){this.logger.error("Failed to create ws.WebSocket:",r),o(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((a,n)=>{try{if(!t||t.length===0){let l=new Error("Token is required for WebSocket connection");this.logger.error(l.message),n(l);return}let o=new URL(e.toString());o.searchParams.set("token",t),this.ws=new globalThis.WebSocket(o.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(a,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(o){this.logger.error("Failed to create native WebSocket:",o),n(o)}})}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 a=JSON.parse(i.data);this.logger.debug("Received message:",a),this.emit("message",a)}catch(a){let n=a instanceof Error?a: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 a;if(i instanceof Error?a=i:i&&i.message?a=i instanceof Error?i:new Error(String(i.message)):a=new Error("WebSocket connection error"),ke&&i&&i.message){let n=String(i.message).toLowerCase();if(n.includes("401")||n.includes("unauthorized")){this.handleTokenExpiration();let o=new Error("Token expired or invalid. Please refresh your token and reconnect.");o.name="TokenExpiredError",this.emit("error",o),t(o);return}}this.emit("error",a)},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)}},Ot=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")}},Ht=new Set(["text","system","image","video","file"]);function Ge(e){return e&&Ht.has(e)?e:"text"}var ee=class{static createOptimistic(e,t,i,a="text",n,o){return{id:t,conversationId:e,content:i,messageType:a,optimistic:!0,receiptState:"sent",createdAt:new Date,metadata:n,attachments:o}}static fromServerPayload(e,t){var n,o;let i=(n=t.sender_id)!=null?n:t.senderId,a=(o=t.sender_type)!=null?o:t.senderType;return{id:t.message_id,conversationId:e,content:t.content,senderId:i,senderName:t.sender_name,senderType:a,messageType:Ge(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,o,r,l;let i=(n=t.sender_id)!=null?n:t.senderId,a=(o=t.sender_type)!=null?o:t.senderType;return{...e,optimistic:!1,senderId:i,senderName:t.sender_name,senderType:a,messageType:Ge(t.message_type),receiptState:(r=e.receiptState)!=null?r:"sent",createdAt:t.sent_at?new Date(t.sent_at):e.createdAt,attachments:(l=t.attachments)!=null?l:e.attachments}}static updateReceiptState(e,t){return{...e,receiptState:t}}},Lt=class extends $.default{constructor(e=!1){super(),this.receiptState=new Map,this.logger=new D(e)}getReceiptState(e){return this.receiptState.get(e)}handleDelivered(e,t){var a;if(!e)return this.logger.warn("Invalid delivered receipt: missing messageId"),!1;let i=(a=this.receiptState.get(e))!=null?a:"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 a;if(!e)return this.logger.warn("Invalid read receipt: missing messageId"),!1;let i=(a=this.receiptState.get(e))!=null?a:"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"],a=i.indexOf(e),n=i.indexOf(t);return a===-1||n===-1?0:a-n}clearConversation(e,t){let i=0;for(let a of t)this.receiptState.has(a)&&(this.receiptState.delete(a),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")}},qt=class extends $.default{constructor(e=!1){super(),this.seenMessageIds=new Map,this.optimisticMessages=new Map,this.confirmedMessages=new Map,this.warnedMissingSenderId=new Set,this.logger=new D(e),this.receiptManager=new Lt(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,i,a="text",n,o){let r=ee.createOptimistic(e,t,i,a,n,o);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,a=this.getOptimisticMessage(e,i);if(a){let o=this.reconcileOptimisticMessage(a,t);return o.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,o),o}if(this.hasSeenMessage(e,i))return this.logger.debug("Duplicate message ignored:",i),null;this.trackMessageId(e,i);let n=ee.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,a){i==="delivered"?this.receiptManager.handleDelivered(t,a):i==="read"&&this.receiptManager.handleRead(t,a)}updateMessageReceiptState(e){for(let[,t]of this.confirmedMessages.entries()){let i=t.get(e.messageId);if(i){let a=ee.updateReceiptState(i,e.state);t.set(e.messageId,a),this.emit("message",a),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 a=ee.updateReceiptState(i,e.state);t.set(e.messageId,a),this.emit("message",a),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=ee.confirmOptimistic(e,t);return this.logger.debug("Reconciled optimistic message (no second emit):",e.id),i}hasSeenMessage(e,t){var a;let i=this.seenMessageIds.get(e);return(a=i==null?void 0:i.has(t))!=null?a:!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 a=this.optimisticMessages.get(e);a||(a=new Map,this.optimisticMessages.set(e,a)),a.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 a=this.confirmedMessages.get(e);a||(a=new Map,this.confirmedMessages.set(e,a)),a.set(t,i)}getMessageIds(e){let t=this.confirmedMessages.get(e),i=this.optimisticMessages.get(e),a=new Set;if(t)for(let n of t.keys())a.add(n);if(i)for(let n of i.keys())a.add(n);return Array.from(a)}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")}},Dt=class extends $.default{constructor(e=!1){super(),this.typingTimers=new Map,this.activeTyping=new Map,this.TYPING_TIMEOUT_MS=5e3,this.logger=new D(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 a=this.typingTimers.get(e);a||(a=new Map,this.typingTimers.set(e,a));let n=i.has(t),o=a.get(t);o&&clearTimeout(o),i.add(t);let r=setTimeout(()=>{this.handleTypingStop(e,t)},this.TYPING_TIMEOUT_MS);a.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),a=this.typingTimers.get(e);if(!i||!i.has(t)){this.logger.debug("Typing stop ignored (user not typing):",e,t);return}let n=a==null?void 0:a.get(t);n&&(clearTimeout(n),a==null||a.delete(t)),i.delete(t),i.size===0&&this.activeTyping.delete(e),a&&a.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 a of t)this.emit("typing",{conversationId:e,userId:a,state:"stop"});this.activeTyping.delete(e)}if(i){for(let a of i.values())clearTimeout(a);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):[]}},Pt=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Ze,Xe=typeof RTCPeerConnection!="undefined"&&typeof navigator!="undefined"&&typeof((Ze=navigator.mediaDevices)==null?void 0:Ze.getUserMedia)=="function",te=class extends $.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:Pt,this.getIceServers=e.getIceServers,this.iceServersResolved=!e.getIceServers}static isAvailable(){return Xe}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 a=!1;if(e==="video"){let o={};t.videoDeviceId&&(o.deviceId={exact:t.videoDeviceId}),t.lowBandwidth&&(o.width={ideal:640},o.height={ideal:360},o.frameRate={ideal:15,max:20}),a=Object.keys(o).length?o:!0}let n=await navigator.mediaDevices.getUserMedia({audio:i,video:a});return t.startMuted&&n.getAudioTracks().forEach(o=>o.enabled=!1),t.startVideoOff&&n.getVideoTracks().forEach(o=>o.enabled=!1),this.localStream=n,n}async createPeerConnection(e,t){if(!Xe)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}),a={pc:i};return this.peers.set(e,a),i.ontrack=n=>{n.streams[0]&&(a.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),a=await this.createPeerConnection(e,t);if(!a)return null;i.getTracks().forEach(o=>a.addTrack(o,i));let n=await a.createOffer();return await a.setLocalDescription(n),n}async handleOffer(e,t,i){let a=await this.getMedia(i),n=await this.createPeerConnection(e,i);if(!n)return null;a.getTracks().forEach(r=>n.addTrack(r,a)),await n.setRemoteDescription(new RTCSessionDescription(t));let o=await n.createAnswer();return await n.setLocalDescription(o),o}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(a){this.options.debug&&console.warn("addIceCandidate failed:",a)}}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 o;return((o=n.track)==null?void 0:o.kind)==="video"});if(!i)continue;let a=i.getParameters();(!a.encodings||a.encodings.length===0)&&(a.encodings=[{}]);for(let n of a.encodings)e==null?delete n.maxBitrate:n.maxBitrate=e;try{await i.setParameters(a)}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}}},a=await navigator.mediaDevices.getUserMedia(i),n=e==="video"?a.getVideoTracks()[0]:a.getAudioTracks()[0];if(!n)return;let o=e==="video"?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];o&&(n.enabled=o.enabled);for(let[,r]of this.peers){let l=r.pc.getSenders().find(d=>{var f;return((f=d.track)==null?void 0:f.kind)===e});l&&await l.replaceTrack(n)}o&&(this.localStream.removeTrack(o),o.stop()),this.localStream.addTrack(n)}isScreenSharing(){return!!this.screenTrack}async startScreenShare(){var n,o;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=(o=(n=this.localStream)==null?void 0:n.getVideoTracks()[0])!=null?o:null;let a=!1;for(let[,r]of this.peers){let l=r.pc.getSenders().find(d=>{var f;return((f=d.track)==null?void 0:f.kind)==="video"});l&&(await l.replaceTrack(i),a=!0)}return a?(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(a=>{var n;return((n=a.track)==null?void 0:n.kind)==="video"||a.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(a=>{var o,r,l,d,f,v,b,R,k,u;let n=a;if(a.type==="inbound-rtp")e.packets_lost_in=((o=e.packets_lost_in)!=null?o:0)+((r=n.packetsLost)!=null?r:0),e.packets_received=((l=e.packets_received)!=null?l:0)+((d=n.packetsReceived)!=null?d:0),e.bytes_received=((f=e.bytes_received)!=null?f:0)+((v=n.bytesReceived)!=null?v:0),typeof n.jitter=="number"&&(e.jitter_ms=n.jitter*1e3);else if(a.type==="outbound-rtp")e.packets_sent=((b=e.packets_sent)!=null?b:0)+((R=n.packetsSent)!=null?R:0),e.bytes_sent=((k=e.bytes_sent)!=null?k:0)+((u=n.bytesSent)!=null?u:0);else if(a.type==="candidate-pair"&&a.state==="succeeded"){let _=a.currentRoundTripTime;typeof _=="number"&&(e.rtt_ms=_*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)}},Ft=6e4,Vt=class extends $.default{constructor(e,t={}){var i,a;super(),this.ringTimeoutId=null,this.webRTC=null,this.webRTCOptions={},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 D((i=t.debug)!=null?i:!1),this.ringTimeoutMs=(a=t.ringTimeout)!=null?a:Ft,this.submitCallQuality=t.submitCallQuality,this.webRTCOptions={debug:t.debug,getIceServers:t.getIceServers},te.isAvailable()&&(this.webRTC=new te(this.webRTCOptions))}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 te.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",t){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.callRole="caller",this.currentCallType=e;let i={type:"call_invite",conversation_id:this.conversationId,payload:{call_type:e,target_user_id:t}};this.send(i),this.logger.debug("call.invite sent",{conversation_id:this.conversationId,call_type:e,target_user_id:t}),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 a;let t=(a=e.from_user_id)!=null?a: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 o=this.webRTC.getLocalStream(),r=this.webRTC.getRemoteStream(t);o&&r&&this.emitCallConnected(o,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 a;let t=(a=e.from_user_id)!=null?a:e.sender_id,i=e.sdp;if(!(!t||!i)){if(this.webRTC){await this.webRTC.handleAnswer(t,i);let n=this.webRTC.getLocalStream(),o=this.webRTC.getRemoteStream(t);n&&o&&this.emitCallConnected(n,o,t)}this.emit("call_answer",{sdp:i,fromUserId:t})}}async handleCallICECandidate(e){var a;let t=(a=e.from_user_id)!=null?a: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:e};this.send({type:"call_offer",conversation_id:this.conversationId,payload:i})}sendAnswer(e,t){let i={sdp:t,target_user_id:e};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:e};this.send({type:"call_ice_candidate",conversation_id:this.conversationId,payload:i})}),this.webRTC.on("remote_stream",({userId:e,stream:t})=>{var a;let i=(a=this.webRTC)==null?void 0:a.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,a={end_reason:e};this.callStartedAt!=null&&(a.duration_seconds=Math.max(0,(Date.now()-this.callStartedAt)/1e3));try{if(i){let n=await i.getCallStats();Object.assign(a,n)}}catch{}if(this.submitCallQuality)try{await this.submitCallQuality(this.conversationId,a,e)}catch(n){this.logger.debug("submitCallQuality failed:",n)}i==null||i.cleanup(),this.webRTC=t?null:te.isAvailable()?new te(this.webRTCOptions):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 Nt(e,t,i,a){return new Promise((n,o)=>{let r=new XMLHttpRequest;r.open("POST",e);for(let[l,d]of Object.entries(i))r.setRequestHeader(l,d);r.upload.onprogress=l=>{a&&l.lengthComputable&&a(Math.round(l.loaded/l.total*100))},r.onload=()=>{if(r.status>=200&&r.status<300)try{n(r.responseText?JSON.parse(r.responseText):{})}catch{n({})}else{let l=`Upload failed: HTTP ${r.status}`;try{let d=JSON.parse(r.responseText);d!=null&&d.message&&(l=d.message)}catch{}o(new Error(l))}},r.onerror=()=>o(new Error("Upload failed: network error")),r.send(t)})}function zt(e){return new Promise((t,i)=>{let a=URL.createObjectURL(e),n=new Image;n.onload=()=>{URL.revokeObjectURL(a),t({width:n.naturalWidth,height:n.naturalHeight})},n.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load image for dimension probing"))},n.src=a})}function Wt(e){return new Promise((t,i)=>{let a=URL.createObjectURL(e),n=document.createElement("video");n.preload="metadata",n.onloadedmetadata=()=>{URL.revokeObjectURL(a),t({width:n.videoWidth,height:n.videoHeight,durationMs:Math.round(n.duration*1e3)})},n.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load video for metadata probing"))},n.src=a})}var Bt=class extends $.default{constructor(e,t=!1){var a,n,o;super(),this._isJoined=!1;let i=typeof t=="boolean"?{debug:t}:t;this.id=e,this.messageManager=new qt((a=i.debug)!=null?a:!1),this.typingManager=new Dt((n=i.debug)!=null?n:!1),this.callManager=new Vt(e,{debug:(o=i.debug)!=null?o:!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(a=>a.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 o=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",o),o}if(!this._isJoined){let o=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",o),o}let a=X();this.messageManager.createOptimisticMessage(this.id,a,e,t,i);let n={type:"message",conversation_id:this.id,payload:{message_id:a,content:e,message_type:t}};try{this.sendMessageHandler(n)}catch(o){let r=o instanceof Error?o:new Error("Failed to send message");throw this.emit("error",r),r}}async sendMedia(e,t){var R,k;if(!this.sendMessageHandler){let u=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",u),u}if(!this._isJoined){let u=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",u),u}if(!this.uploadAttachmentCallback){let u=new Error("Media upload is not configured. Set apiUrl and appId in the Vocantly config to use sendMedia().");throw this.emit("error",u),u}let i=(R=t==null?void 0:t.fileName)!=null?R:e instanceof File?e.name:"upload",a=e.type||"application/octet-stream",n,o,r;if(a.startsWith("image/")){let u=await zt(e).catch(()=>{});n=u==null?void 0:u.width,o=u==null?void 0:u.height}else if(a.startsWith("video/")){let u=await Wt(e).catch(()=>{});n=u==null?void 0:u.width,o=u==null?void 0:u.height,r=u==null?void 0:u.durationMs}let l;try{l=await this.uploadAttachmentCallback({conversationId:this.id,file:e,fileName:i,onProgress:t==null?void 0:t.onProgress})}catch(u){let _=u instanceof Error?u:new Error("Upload failed");throw this.emit("error",_),_}let d=X(),f=[{bucket:l.bucket,key:l.key,file_name:l.fileName,mime_type:l.mimeType,size_bytes:l.sizeBytes,width:n,height:o,duration_ms:r}],v=(k=t==null?void 0:t.caption)!=null?k:"";this.messageManager.createOptimisticMessage(this.id,d,v,l.category,t==null?void 0:t.metadata,f);let b={type:"message",conversation_id:this.id,payload:{message_id:d,content:v,message_type:l.category,attachments:f}};try{this.sendMessageHandler(b)}catch(u){let _=u instanceof Error?u:new Error("Failed to send media message");throw this.emit("error",_),_}}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",t){this.ensureJoinedForCall(),this.callManager.startCall(e,t)}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 a=i instanceof Error?i:new Error("Failed to send read receipt");throw this.emit("error",a),a}}},Jt=class extends $.default{constructor(e,t=!1,i,a,n){super(),this.conversations=new Map,this.restFetcher=null,this.appId=null,this.iceServersCache=null,this.sendMessageHandler=e,this.sendTypingHandler=a,this.sendCallHandler=n,this.supportMessageHandler=i,this.debug=t,this.logger=new D(t)}setRestFetcher(e){if(this.restFetcher=e,e)for(let t of this.conversations.values())t.setSubmitCallQuality((i,a,n)=>this.submitCallQualityToApi(i,a,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(),a=await fetch(t,{method:"GET",headers:i});if(!a.ok)throw new Error(`ICE servers fetch failed: ${a.status}`);let n=await a.json();if(!n.success||!((r=n.data)!=null&&r.iceServers))throw new Error("Invalid ICE servers response");let o=n.data.iceServers;return this.iceServersCache=o,o}}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 k,u,_;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=(k=e==null?void 0:e.externalUserId)==null?void 0:k.trim(),a=Math.min(Math.max(1,(u=e==null?void 0:e.limit)!=null?u:20),100),n=new URLSearchParams({limit:String(a)});i&&n.set("external_user_id",i),e!=null&&e.cursor&&n.set("cursor",e.cursor);let o=n.toString(),r=`${t}/sdk/conversations${o?`?${o}`:""}`,l=await this.restFetcher.getHeaders(),d=await fetch(r,{method:"GET",headers:l});if(!d.ok){let P=await d.text(),S={};try{S=JSON.parse(P)}catch{S={message:P}}throw new Error(S.message||`HTTP ${d.status}: ${P}`)}let f=await d.json();if(!f.success||!f.data)throw new Error(f.message||"Invalid response");let v=f.data,b=Array.isArray(v.conversations)?v.conversations:[],R=(_=v.pagination)!=null?_:{has_next_page:!1,next_cursor:null,limit:a};return{conversations:b,pagination:R}}async getMessages(e,t,i={}){var b;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 a=Math.min(Math.max(1,(b=i.limit)!=null?b:20),100),n=new URLSearchParams({limit:String(a)});t!=null&&t.trim()&&n.set("external_user_id",t.trim()),i.cursor&&n.set("cursor",i.cursor);let o=this.restFetcher.apiUrl.replace(/\/$/,""),r=n.toString(),l=`${o}/sdk/conversations/${encodeURIComponent(e.trim())}/messages${r?`?${r}`:""}`,d=await this.restFetcher.getHeaders(),f=await fetch(l,{method:"GET",headers:d});if(!f.ok){let R=await f.text(),k={};try{k=JSON.parse(R)}catch{k={message:R}}throw new Error(k.message||`HTTP ${f.status}: ${R}`)}let v=await f.json();if(!v.success||!v.data)throw new Error(v.message||"Invalid response");return{messages:v.data.messages||[],pagination:v.data.pagination||{has_next_page:!1,next_cursor:null,limit:a}}}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 o=new FormData;o.append("conversation_id",e.conversationId),o.append("file",e.file,e.fileName);let r=await Nt(i,o,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(/\/$/,""),a=new URLSearchParams({bucket:e,key:t}),n=`${i}/apps/${encodeURIComponent(this.appId)}/uploads/url?${a.toString()}`,o=await this.restFetcher.getHeaders(),r=await fetch(n,{method:"GET",headers:o});if(!r.ok){let d=await r.text(),f={};try{f=JSON.parse(d)}catch{f={message:d}}throw new Error(f.message||`HTTP ${r.status}: ${d}`)}let l=await r.json();if(!l.success||!l.data)throw new Error(l.message||"Invalid download URL response");return{url:l.data.url,expiresInSeconds:l.data.expires_in_seconds}}async submitCallQualityToApi(e,t,i){if(!this.restFetcher)return;let n=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/conversations/${encodeURIComponent(e)}/call-quality`,o=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 l=await fetch(n,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok){let d=await l.text();throw this.logger.debug("submitCallQuality failed:",l.status,d),new Error(`Call quality submit failed: ${l.status}`)}}get(e){if(!e||e.length===0)throw new Error("Conversation ID is required");let t=this.conversations.get(e);return t||(t=new Bt(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,a,n)=>this.submitCallQualityToApi(i,a,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 a=this.conversations.get(t);a?a.isJoined?a.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 a=this.conversations.get(t);a?a.isJoined?a.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 a=this.conversations.get(t);if(a)if(a.isJoined){let n=e;a.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 a=this.conversations.get(t);a&&a.isJoined&&a.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 a=this.get(t),n="payload"in e?e.payload:void 0;a.handleIncomingCallMessage(e.type,n)}break}}routeSupportMessage(e){var a;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=(a=e.payload)==null?void 0:a.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())}getJoinedIds(){return Array.from(this.conversations.entries()).filter(([,e])=>e.isJoined).map(([e])=>e)}clear(){for(let e of this.conversations.values())e.markLeft(),e.clearMessages(),e.clearTyping();this.conversations.clear(),this.logger.debug("Cleared all conversations")}},Kt=class extends $.default{constructor(e=!1){super(),this.presenceState=new Map,this.logger=new D(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 a=this.presenceState.get(i);a&&t.set(i,a)}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")}},Yt=class extends $.default{constructor(e,t,i,a=!1){super(),this.botActive=!1,this.status="queued",this.conversationId=e,this.conversation=t,this.role=i,this.logger=new D(a),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(){}},Qt=class extends $.default{constructor(e,t=!1){super(),this.sessions=new Map,this.getConversationHandler=e,this.debug=t,this.logger=new D(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 a=this.getConversationHandler(e);i=new Yt(e,a,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 a=this.sessions.get(e);if(!a){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"&&a.handleAssigned(i.agent_id);break;case"unassigned":a.handleUnassigned();break;case"bot_takeover":a.handleBotTakeover();break;case"bot_released":a.handleBotReleased();break;case"closed":a.handleClosed();break;case"reopened":a.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")}};async function N(e,t){let i=await fetch(e,t),a=await i.text(),n={};try{n=a?JSON.parse(a):{}}catch{n={message:a}}if(!i.ok)throw new Error(n.message||`HTTP ${i.status}: ${a}`);return n}var Gt=class extends $.default{constructor(e=!1){super(),this.restFetcher=null,this.sendVoiceCapableHandler=null,this.voiceCapableSent=!1,this.logger=new D(e)}setRestFetcher(e){this.restFetcher=e}setSendVoiceCapableHandler(e){this.sendVoiceCapableHandler=e}sendVoiceCapable(){if(!this.voiceCapableSent){if(!this.sendVoiceCapableHandler){this.logger.warn("sendVoiceCapable called before the WebSocket send handler was wired");return}this.sendVoiceCapableHandler({type:"voice_capable"}),this.voiceCapableSent=!0}}resetVoiceCapableState(){this.voiceCapableSent=!1}handleNotification(e){let t=e.type;switch(t){case"support_call_reservation_offered":this.emit("reservation_offered",e);break;case"support_call_reservation_rescinded":this.emit("reservation_rescinded",e);break;case"support_call_reservation_won":this.emit("reservation_won",e);break;case"support_call_fallback_available":this.emit("fallback_available",e);break;case"support_call_cancelled":this.emit("cancelled",e);break;case"support_call_request_updated":this.emit("request_updated",e);break;default:this.logger.debug("Ignoring unknown notification payload type:",t)}}requireRestFetcher(){if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for call-reservation methods.");return this.restFetcher}async requestCall(e,t,i){let a=this.requireRestFetcher(),n=a.apiUrl.replace(/\/$/,""),o=await a.getHeaders();return(await N(`${n}/conversations/${encodeURIComponent(e)}/calls/requests`,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({call_type:t,idempotency_key:i})})).data.request}async cancelCallRequest(e,t){let i=this.requireRestFetcher(),a=i.apiUrl.replace(/\/$/,""),n=await i.getHeaders();return(await N(`${a}/conversations/${encodeURIComponent(e)}/calls/requests/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:n})).data.request}async getCallRequest(e,t){let i=this.requireRestFetcher(),a=i.apiUrl.replace(/\/$/,""),n=await i.getHeaders();return(await N(`${a}/conversations/${encodeURIComponent(e)}/calls/requests/${encodeURIComponent(t)}`,{method:"GET",headers:n})).data.request}async listOffers(){var n;let e=this.requireRestFetcher(),t=e.apiUrl.replace(/\/$/,""),i=await e.getHeaders();return(n=(await N(`${t}/support/calls/reservations/mine`,{method:"GET",headers:i})).data.reservations)!=null?n:[]}async acceptReservation(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),a=await t.getHeaders();return(await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/accept`,{method:"POST",headers:a})).data}async declineReservation(e,t){let i=this.requireRestFetcher(),a=i.apiUrl.replace(/\/$/,""),n=await i.getHeaders();await N(`${a}/support/calls/reservations/${encodeURIComponent(e)}/decline`,{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({reason:t})})}async acknowledgeOffer(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),a=await t.getHeaders();await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/ack`,{method:"POST",headers:a})}async confirmReady(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),a=await t.getHeaders();await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/ready`,{method:"POST",headers:a})}},Xt=class{constructor(e,t){this.apiUrl=e,this.publicKey=t}resolveForm(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([i,a])=>a&&t.set(i,a)),this.request(`/tickets/public/form${t.size?`?${t}`:""}`)}create(e){return this.request("/tickets/public",{method:"POST",body:JSON.stringify(e)})}getStatus(e,t){return this.request(`/tickets/public/${encodeURIComponent(e)}?token=${encodeURIComponent(t)}`,{},!1)}async reply(e,t,i,a=X()){await this.request(`/tickets/public/${encodeURIComponent(e)}/reply?token=${encodeURIComponent(t)}`,{method:"POST",body:JSON.stringify({body:i,idempotency_key:a})},!1)}async request(e,t={},i=!0){var o,r;let a=await fetch(this.apiUrl.replace(/\/$/,"")+e,{...t,headers:{"Content-Type":"application/json",...i?{"X-Api-Key":this.publicKey}:{},...(o=t.headers)!=null?o:{}}}),n=await a.json().catch(()=>({}));if(!a.ok)throw new Error(n.message||`Ticket request failed (${a.status})`);return(r=n.data)!=null?r:n}},et=class extends $.default{constructor(e){var o,r;super(),this.connectionState="disconnected",this.wsClient=null,this.config={autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,debug:!1,apiUrl:"",...e},this.tokenManager=new Ot,this.tokenManager.setToken(e.token),this.logger=new D(this.config.debug),this.wsClient=new jt(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new Qt(l=>this.conversationManager.get(l),this.config.debug),this.conversationManager=new Jt(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},this.config.debug,void 0,l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.conversationManager.setSendReadHandler(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.presenceManager=new Kt(this.config.debug),this.presenceManager.on("presence",l=>{this.emit("presence",l)}),this.reservationManager=new Gt(this.config.debug),this.reservationManager.setSendVoiceCapableHandler(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)});for(let l of["reservation_offered","reservation_rescinded","reservation_won","fallback_available","cancelled","request_updated"])this.reservationManager.on(l,d=>this.emit(l,d));let t=(o=this.config.apiUrl)==null?void 0:o.trim(),i=(r=this.config.appId)==null?void 0:r.trim(),a=this.config.apiKey&&this.config.apiSecret,n=typeof this.config.getRestHeaders=="function";if(t){let l=async()=>{if(n&&this.config.getRestHeaders)return this.config.getRestHeaders();if(a)return{"X-Api-Key":this.config.apiKey,"X-Api-Secret":this.config.apiSecret,"Content-Type":"application/json"};let d=this.tokenManager.getToken();if(!d)throw new Error("Token required for list() and fetchMessages() when API keys are not set");return{Authorization:`Bearer ${d}`,"Content-Type":"application/json"}};this.conversationManager.setRestFetcher({apiUrl:t,getHeaders:l}),this.reservationManager.setRestFetcher({apiUrl:t,getHeaders:l}),i&&this.conversationManager.setAppId(i),this.config.publicKey&&(this.ticketManager=new Xt(t,this.config.publicKey))}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.rejoinActiveConversations(),this.config.declareVoiceCapable&&this.reservationManager.sendVoiceCapable()}),this.wsClient.on("disconnected",e=>{this.connectionState="disconnected",this.emit("disconnected",e),this.emit("state",this.connectionState),this.logger.debug("SDK disconnected"),this.reservationManager.resetVoiceCapableState()}),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)}if(e.type==="support"&&this.conversationManager.routeSupportMessage(e),e.type==="notification"){let t=e;t.payload&&this.reservationManager.handleNotification(t.payload)}switch(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"notification":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 a=e instanceof Error?e:new Error("WebSocket connection error");this.emit("error",a),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)}}get tickets(){if(!this.ticketManager)throw new Error("tickets requires both apiUrl and publicKey");return this.ticketManager}get reservations(){return this.reservationManager}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 a=i instanceof Error?i:new Error("Failed to join conversation");throw this.emit("error",a),a}}async rejoinActiveConversations(){let e=this.conversationManager.getJoinedIds();for(let t of e)try{await this.joinConversation(t)}catch(i){this.logger.warn("Failed to rejoin conversation after reconnect:",t,i)}}async leaveConversation(e){if(!this.isConnected())throw new Error("Must be connected before leaving a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"leave",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Leave conversation sent:",e)}catch(i){let a=i instanceof Error?i:new Error("Failed to leave conversation");throw this.emit("error",a),a}}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 ei={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,tickets:!0,ticketLabel:"Raise a ticket",callBundleUrl:"https://cdn.jsdelivr.net/npm/@vocantly/widget@0.1.23/dist/vocantly-widget-call.js"},I=null;function at(e){try{return JSON.parse(atob(e.split(".")[1]))}catch{return null}}function tt(e){let t=at(e);return(t==null?void 0:t.user_id)||(t==null?void 0:t.sub)||null}function ti(e){return typeof e!="number"?"":e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+" KB":(e/(1024*1024)).toFixed(1)+" MB"}function y(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Ce(e){return y(e).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>").replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\n/g,"<br>")}var ie=null;function ii(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;ie=ie||new e,ie.resume&&ie.resume();let t=ie,i=t.currentTime,a=t.createOscillator(),n=t.createGain();a.type="sine",a.frequency.setValueAtTime(880,i),a.frequency.exponentialRampToValueAtTime(1320,i+.08),n.gain.setValueAtTime(1e-4,i),n.gain.exponentialRampToValueAtTime(.16,i+.02),n.gain.exponentialRampToValueAtTime(1e-4,i+.34),a.connect(n).connect(t.destination),a.start(i),a.stop(i+.36)}catch{}}function it(e,t){let i=String(e).replace("#",""),a=i.length===3?i.split("").map(l=>l+l).join(""):i,n=parseInt(a.slice(0,2),16)||0,o=parseInt(a.slice(2,4),16)||0,r=parseInt(a.slice(4,6),16)||0;return`rgba(${n},${o},${r},${t})`}function ai(e,t){if(document.getElementById("caf-widget-styles"))return;let o=`
1
+ var xt=Object.create;var Ne=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var B=(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 ze=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Tt=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ct(t))!_t.call(e,a)&&a!==i&&Ne(e,a,{get:()=>t[a],enumerable:!(n=kt(t,a))||n.enumerable});return e};var We=(e,t,i)=>(i=e!=null?xt(St(e)):{},Tt(t||!e||!e.__esModule?Ne(i,"default",{value:e,enumerable:!0}):i,e));var Je=ze((ri,ve)=>{"use strict";var Mt=Object.prototype.hasOwnProperty,A="~";function G(){}Object.create&&(G.prototype=Object.create(null),new G().__proto__||(A=!1));function Et(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function Be(e,t,i,n,a){if(typeof i!="function")throw new TypeError("The listener must be a function");var o=new Et(i,n||e,a),s=A?A+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],o]:e._events[s].push(o):(e._events[s]=o,e._eventsCount++),e}function he(e,t){--e._eventsCount===0?e._events=new G:delete e._events[t]}function E(){this._events=new G,this._eventsCount=0}E.prototype.eventNames=function(){var t=[],i,n;if(this._eventsCount===0)return t;for(n in i=this._events)Mt.call(i,n)&&t.push(A?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(i)):t};E.prototype.listeners=function(t){var i=A?A+t:t,n=this._events[i];if(!n)return[];if(n.fn)return[n.fn];for(var a=0,o=n.length,s=new Array(o);a<o;a++)s[a]=n[a].fn;return s};E.prototype.listenerCount=function(t){var i=A?A+t:t,n=this._events[i];return n?n.fn?1:n.length:0};E.prototype.emit=function(t,i,n,a,o,s){var l=A?A+t:t;if(!this._events[l])return!1;var d=this._events[l],f=arguments.length,v,b;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),f){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,n),!0;case 4:return d.fn.call(d.context,i,n,a),!0;case 5:return d.fn.call(d.context,i,n,a,o),!0;case 6:return d.fn.call(d.context,i,n,a,o,s),!0}for(b=1,v=new Array(f-1);b<f;b++)v[b-1]=arguments[b];d.fn.apply(d.context,v)}else{var R=d.length,k;for(b=0;b<R;b++)switch(d[b].once&&this.removeListener(t,d[b].fn,void 0,!0),f){case 1:d[b].fn.call(d[b].context);break;case 2:d[b].fn.call(d[b].context,i);break;case 3:d[b].fn.call(d[b].context,i,n);break;case 4:d[b].fn.call(d[b].context,i,n,a);break;default:if(!v)for(k=1,v=new Array(f-1);k<f;k++)v[k-1]=arguments[k];d[b].fn.apply(d[b].context,v)}}return!0};E.prototype.on=function(t,i,n){return Be(this,t,i,n,!1)};E.prototype.once=function(t,i,n){return Be(this,t,i,n,!0)};E.prototype.removeListener=function(t,i,n,a){var o=A?A+t:t;if(!this._events[o])return this;if(!i)return he(this,o),this;var s=this._events[o];if(s.fn)s.fn===i&&(!a||s.once)&&(!n||s.context===n)&&he(this,o);else{for(var l=0,d=[],f=s.length;l<f;l++)(s[l].fn!==i||a&&!s[l].once||n&&s[l].context!==n)&&d.push(s[l]);d.length?this._events[o]=d.length===1?d[0]:d:he(this,o)}return this};E.prototype.removeAllListeners=function(t){var i;return t?(i=A?A+t:t,this._events[i]&&he(this,i)):(this._events=new G,this._eventsCount=0),this};E.prototype.off=E.prototype.removeListener;E.prototype.addListener=E.prototype.on;E.prefixed=A;E.EventEmitter=E;typeof ve!="undefined"&&(ve.exports=E)});var Qe=ze((bi,Ye)=>{"use strict";Ye.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var $=We(Je(),1);var M=[];for(pe=0;pe<256;++pe)M.push((pe+256).toString(16).slice(1));var pe;function Ke(e,t=0){return(M[e[t+0]]+M[e[t+1]]+M[e[t+2]]+M[e[t+3]]+"-"+M[e[t+4]]+M[e[t+5]]+"-"+M[e[t+6]]+M[e[t+7]]+"-"+M[e[t+8]]+M[e[t+9]]+"-"+M[e[t+10]]+M[e[t+11]]+M[e[t+12]]+M[e[t+13]]+M[e[t+14]]+M[e[t+15]]).toLowerCase()}var fe,Rt=new Uint8Array(16);function ye(){if(!fe&&(fe=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!fe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return fe(Rt)}var At=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),xe={randomUUID:At};function $t(e,t,i){if(xe.randomUUID&&!t&&!e)return xe.randomUUID();e=e||{};var n=e.random||(e.rng||ye)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){i=i||0;for(var a=0;a<16;++a)t[i+a]=n[a];return t}return Ke(n)}var X=$t;var Zt={};var It=(e=>typeof B!="undefined"?B:typeof Proxy!="undefined"?new Proxy(e,{get:(t,i)=>(typeof B!="undefined"?B:t)[i]}):e)(function(e){if(typeof B!="undefined")return B.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=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)}},ke=typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null,K=null,Z=null;async function Ut(){return ke?K||Z||(Z=(async()=>{try{try{return K=await Promise.resolve().then(()=>We(Qe(),1)),K}catch(e){if(typeof It!="undefined"){let{createRequire:t}=await import("module");return K=t(Zt.url||__filename)("ws"),K}throw e}}catch{return null}finally{Z=null}})(),Z):null}var jt=class extends $.default{constructor(e,t={}){var i,n,a;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 P((a=t.debug)!=null?a:!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(ke){let n=await Ut();if(this.logger.debug("ws module loaded:",!!n),n&&n.WebSocket)return this.logger.debug("Using ws package with Authorization header"),new Promise((a,o)=>{try{let s=new n.WebSocket(e.toString(),{headers:{Authorization:`Bearer ${t}`}});this.ws=s;let l=!1,d=f=>{if(l)return;l=!0;let v=String((f==null?void 0:f.message)||f||"").toLowerCase();if(v.includes("401")||v.includes("unauthorized")||f!=null&&f.code&&String(f.code).includes("401")){this.handleTokenExpiration();let b=new Error("Token expired or invalid. Please refresh your token and reconnect.");b.name="TokenExpiredError",this.emit("error",b),o(b);return}};typeof s.addEventListener=="function"?(s.addEventListener("error",d),s.addEventListener("open",()=>{s.removeEventListener("error",d)})):typeof s.once=="function"&&(s.once("error",d),s.once("open",()=>{})),this.setupEventHandlers(a,o)}catch(s){this.logger.error("Failed to create ws.WebSocket:",s),o(s)}});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,a)=>{try{if(!t||t.length===0){let l=new Error("Token is required for WebSocket connection");this.logger.error(l.message),a(l);return}let o=new URL(e.toString());o.searchParams.set("token",t),this.ws=new globalThis.WebSocket(o.toString()),this.logger.debug("WebSocket instance created",{readyState:this.ws.readyState,url:this.ws.url,protocol:this.ws.protocol});let s=this.ws;this.setupEventHandlers(n,a),setTimeout(()=>{(s.readyState===WebSocket.CLOSED||s.readyState===WebSocket.CLOSING)&&this.logger.warn("WebSocket closed immediately after creation",{readyState:s.readyState,url:s.url})},100)}catch(o){this.logger.error("Failed to create native WebSocket:",o),a(o)}})}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 a=n instanceof Error?n:new Error("Failed to parse message");this.logger.error("Failed to parse message:",a),this.emit("error",a)}},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"),ke&&i&&i.message){let a=String(i.message).toLowerCase();if(a.includes("401")||a.includes("unauthorized")){this.handleTokenExpiration();let o=new Error("Token expired or invalid. Please refresh your token and reconnect.");o.name="TokenExpiredError",this.emit("error",o),t(o);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 a=new Error("Token expired or invalid. Please refresh your token and reconnect.");a.name="TokenExpiredError",this.emit("error",a),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)}},Ot=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")}},Ht=new Set(["text","system","image","video","file"]);function Ge(e){return e&&Ht.has(e)?e:"text"}var ee=class{static createOptimistic(e,t,i,n="text",a,o){return{id:t,conversationId:e,content:i,messageType:n,optimistic:!0,receiptState:"sent",createdAt:new Date,metadata:a,attachments:o}}static fromServerPayload(e,t){var a,o;let i=(a=t.sender_id)!=null?a:t.senderId,n=(o=t.sender_type)!=null?o:t.senderType;return{id:t.message_id,conversationId:e,content:t.content,senderId:i,senderName:t.sender_name,senderType:n,messageType:Ge(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 a,o,s,l;let i=(a=t.sender_id)!=null?a:t.senderId,n=(o=t.sender_type)!=null?o:t.senderType;return{...e,optimistic:!1,senderId:i,senderName:t.sender_name,senderType:n,messageType:Ge(t.message_type),receiptState:(s=e.receiptState)!=null?s:"sent",createdAt:t.sent_at?new Date(t.sent_at):e.createdAt,attachments:(l=t.attachments)!=null?l:e.attachments}}static updateReceiptState(e,t){return{...e,receiptState:t}}},Lt=class extends $.default{constructor(e=!1){super(),this.receiptState=new Map,this.logger=new P(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),a=i.indexOf(t);return n===-1||a===-1?0:n-a}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")}},qt=class extends $.default{constructor(e=!1){super(),this.seenMessageIds=new Map,this.optimisticMessages=new Map,this.confirmedMessages=new Map,this.warnedMissingSenderId=new Set,this.logger=new P(e),this.receiptManager=new Lt(e),this.receiptManager.on("receipt",t=>{this.updateMessageReceiptState(t)})}createOptimisticMessage(e,t,i,n="text",a,o){let s=ee.createOptimistic(e,t,i,n,a,o);return this.trackOptimisticMessage(e,t,s),this.trackMessageId(e,t),this.emit("message",s),this.logger.debug("Created optimistic message:",t),s}handleIncomingMessage(e,t){let i=t.message_id,n=this.getOptimisticMessage(e,i);if(n){let o=this.reconcileOptimisticMessage(n,t);return o.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,o),o}if(this.hasSeenMessage(e,i))return this.logger.debug("Duplicate message ignored:",i),null;this.trackMessageId(e,i);let a=ee.fromServerPayload(e,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.trackConfirmedMessage(e,i,a),this.emit("message",a),this.logger.debug("Handled incoming message:",i),a}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=ee.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=ee.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=ee.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 a of t.keys())n.add(a);if(i)for(let a of i.keys())n.add(a);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")}},Pt=class extends $.default{constructor(e=!1){super(),this.typingTimers=new Map,this.activeTyping=new Map,this.TYPING_TIMEOUT_MS=5e3,this.logger=new P(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 a=i.has(t),o=n.get(t);o&&clearTimeout(o),i.add(t);let s=setTimeout(()=>{this.handleTypingStop(e,t)},this.TYPING_TIMEOUT_MS);n.set(t,s),a?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 a=n==null?void 0:n.get(t);a&&(clearTimeout(a),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):[]}},Dt=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Ze,Xe=typeof RTCPeerConnection!="undefined"&&typeof navigator!="undefined"&&typeof((Ze=navigator.mediaDevices)==null?void 0:Ze.getUserMedia)=="function",te=class extends $.default{constructor(e={}){var t;super(),this.peers=new Map,this.pendingIceCandidates=new Map,this.localStream=null,this.mediaOptions={},this.screenTrack=null,this.cameraTrack=null,this.options=e,this.iceServers=(t=e.iceServers)!=null?t:Dt,this.getIceServers=e.getIceServers,this.iceServersResolved=!e.getIceServers}static isAvailable(){return Xe}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 o={};t.videoDeviceId&&(o.deviceId={exact:t.videoDeviceId}),t.lowBandwidth&&(o.width={ideal:640},o.height={ideal:360},o.frameRate={ideal:15,max:20}),n=Object.keys(o).length?o:!0}let a=await navigator.mediaDevices.getUserMedia({audio:i,video:n});return t.startMuted&&a.getAudioTracks().forEach(o=>o.enabled=!1),t.startVideoOff&&a.getVideoTracks().forEach(o=>o.enabled=!1),this.localStream=a,a}async createPeerConnection(e,t){if(!Xe)return null;if(!this.iceServersResolved&&this.getIceServers)try{this.iceServers=await this.getIceServers(),this.iceServersResolved=!0}catch(a){this.options.debug&&console.warn("Failed to fetch ICE servers, using defaults:",a),this.iceServersResolved=!0}let i=new RTCPeerConnection({iceServers:this.iceServers}),n={pc:i};return this.peers.set(e,n),i.ontrack=a=>{a.streams[0]&&(n.remoteStream=a.streams[0],this.emit("remote_stream",{userId:e,stream:a.streams[0]}))},i.onicecandidate=a=>{a.candidate&&this.emit("ice_candidate",{userId:e,candidate:a.candidate.toJSON()})},i.oniceconnectionstatechange=()=>{i.iceConnectionState==="connected"||i.iceConnectionState==="completed"?(this.mediaOptions.lowBandwidth&&this.setVideoBitrate(35e4),this.emit("peer_connected",{userId:e})):i.iceConnectionState==="failed"&&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(o=>n.addTrack(o,i));let a=await n.createOffer();return await n.setLocalDescription(a),a}async handleOffer(e,t,i){let n=await this.getMedia(i),a=await this.createPeerConnection(e,i);if(!a)return null;n.getTracks().forEach(s=>a.addTrack(s,n)),await a.setRemoteDescription(new RTCSessionDescription(t)),await this.flushPendingIceCandidates(e,a);let o=await a.createAnswer();return await a.setLocalDescription(o),o}async handleAnswer(e,t){let i=this.peers.get(e);i&&(await i.pc.setRemoteDescription(new RTCSessionDescription(t)),await this.flushPendingIceCandidates(e,i.pc))}async addIceCandidate(e,t){var n;let i=this.peers.get(e);if(!i||!i.pc.remoteDescription){let a=(n=this.pendingIceCandidates.get(e))!=null?n:[];a.push(t),this.pendingIceCandidates.set(e,a);return}try{await i.pc.addIceCandidate(new RTCIceCandidate(t))}catch(a){this.options.debug&&console.warn("addIceCandidate failed:",a)}}async flushPendingIceCandidates(e,t){let i=this.pendingIceCandidates.get(e);if(i!=null&&i.length){this.pendingIceCandidates.delete(e);for(let n of i)try{await t.addIceCandidate(new RTCIceCandidate(n))}catch(a){this.options.debug&&console.warn("queued addIceCandidate failed:",a)}}}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(a=>{var o;return((o=a.track)==null?void 0:o.kind)==="video"});if(!i)continue;let n=i.getParameters();(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]);for(let a of n.encodings)e==null?delete a.maxBitrate:a.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),a=e==="video"?n.getVideoTracks()[0]:n.getAudioTracks()[0];if(!a)return;let o=e==="video"?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];o&&(a.enabled=o.enabled);for(let[,s]of this.peers){let l=s.pc.getSenders().find(d=>{var f;return((f=d.track)==null?void 0:f.kind)===e});l&&await l.replaceTrack(a)}o&&(this.localStream.removeTrack(o),o.stop()),this.localStream.addTrack(a)}isScreenSharing(){return!!this.screenTrack}async startScreenShare(){var a,o;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=(o=(a=this.localStream)==null?void 0:a.getVideoTracks()[0])!=null?o:null;let n=!1;for(let[,s]of this.peers){let l=s.pc.getSenders().find(d=>{var f;return((f=d.track)==null?void 0:f.kind)==="video"});l&&(await l.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 a;return((a=n.track)==null?void 0:a.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),this.pendingIceCandidates.delete(e)}cleanup(){for(let[e]of this.peers)this.closePeer(e);this.pendingIceCandidates.clear(),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 o,s,l,d,f,v,b,R,k,u;let a=n;if(n.type==="inbound-rtp")e.packets_lost_in=((o=e.packets_lost_in)!=null?o:0)+((s=a.packetsLost)!=null?s:0),e.packets_received=((l=e.packets_received)!=null?l:0)+((d=a.packetsReceived)!=null?d:0),e.bytes_received=((f=e.bytes_received)!=null?f:0)+((v=a.bytesReceived)!=null?v:0),typeof a.jitter=="number"&&(e.jitter_ms=a.jitter*1e3);else if(n.type==="outbound-rtp")e.packets_sent=((b=e.packets_sent)!=null?b:0)+((R=a.packetsSent)!=null?R:0),e.bytes_sent=((k=e.bytes_sent)!=null?k:0)+((u=a.bytesSent)!=null?u:0);else if(n.type==="candidate-pair"&&n.state==="succeeded"){let _=n.currentRoundTripTime;typeof _=="number"&&(e.rtt_ms=_*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)}},Ft=6e4,Vt=class extends $.default{constructor(e,t={}){var i,n;super(),this.ringTimeoutId=null,this.webRTC=null,this.webRTCOptions={},this.callRole=null,this.currentCallType="video",this.participants=new Set,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.connectedPeers=new Set,this.callConnectedEmitted=!1,this.conversationId=e,this.logger=new P((i=t.debug)!=null?i:!1),this.ringTimeoutMs=(n=t.ringTimeout)!=null?n:Ft,this.submitCallQuality=t.submitCallQuality,this.webRTCOptions={debug:t.debug,getIceServers:t.getIceServers},te.isAvailable()&&(this.webRTC=new te(this.webRTCOptions))}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}))}maybeEmitCallConnected(e){var n,a;if(!this.connectedPeers.has(e))return;let t=(n=this.webRTC)==null?void 0:n.getLocalStream(),i=(a=this.webRTC)==null?void 0:a.getRemoteStream(e);t&&i&&this.emitCallConnected(t,i,e)}setSendCallHandler(e){this.sendCallHandler=e}setCallOptions(e){var t;(t=this.webRTC)==null||t.setMediaOptions(e)}listDevices(){return te.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",t){this.clearRingTimeout(),this.callConnectedEmitted=!1,this.connectedPeers.clear(),this.callRole="caller",this.currentCallType=e;let i={type:"call_invite",conversation_id:this.conversationId,payload:{call_type:e,target_user_id:t}};this.send(i),this.logger.debug("call.invite sent",{conversation_id:this.conversationId,call_type:e,target_user_id:t}),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.connectedPeers.clear(),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{this.setupWebRTCEvents();let i=await this.webRTC.createOffer(t,this.currentCallType);i&&this.sendOffer(t,i)}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{this.setupWebRTCEvents();let i=await this.webRTC.createOffer(t,this.currentCallType);i&&this.sendOffer(t,i)}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),this.connectedPeers.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 a=await this.webRTC.handleOffer(t,i,this.currentCallType);if(a){this.sendAnswer(t,a);let o=this.webRTC.getLocalStream(),s=this.webRTC.getRemoteStream(t);o&&s&&this.maybeEmitCallConnected(t)}}catch(a){this.logger.debug("WebRTC handleOffer failed:",a),this.emit("call_error",{reason:"permission_denied",message:String(a)})}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 a=this.webRTC.getLocalStream(),o=this.webRTC.getRemoteStream(t);a&&o&&this.maybeEmitCallConnected(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:e};this.send({type:"call_offer",conversation_id:this.conversationId,payload:i})}sendAnswer(e,t){let i={sdp:t,target_user_id:e};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:e};this.send({type:"call_ice_candidate",conversation_id:this.conversationId,payload:i})}),this.webRTC.on("remote_stream",({userId:e})=>{this.maybeEmitCallConnected(e)}),this.webRTC.on("peer_connected",({userId:e})=>{this.connectedPeers.add(e),this.maybeEmitCallConnected(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 a=await i.getCallStats();Object.assign(n,a)}}catch{}if(this.submitCallQuality)try{await this.submitCallQuality(this.conversationId,n,e)}catch(a){this.logger.debug("submitCallQuality failed:",a)}i==null||i.cleanup(),this.webRTC=t?null:te.isAvailable()?new te(this.webRTCOptions):null,this.webRTCEventsSetup=!1,this.callStartedAt=null,this.callConnectedEmitted=!1,this.connectedPeers.clear()}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 Nt(e,t,i,n){return new Promise((a,o)=>{let s=new XMLHttpRequest;s.open("POST",e);for(let[l,d]of Object.entries(i))s.setRequestHeader(l,d);s.upload.onprogress=l=>{n&&l.lengthComputable&&n(Math.round(l.loaded/l.total*100))},s.onload=()=>{if(s.status>=200&&s.status<300)try{a(s.responseText?JSON.parse(s.responseText):{})}catch{a({})}else{let l=`Upload failed: HTTP ${s.status}`;try{let d=JSON.parse(s.responseText);d!=null&&d.message&&(l=d.message)}catch{}o(new Error(l))}},s.onerror=()=>o(new Error("Upload failed: network error")),s.send(t)})}function zt(e){return new Promise((t,i)=>{let n=URL.createObjectURL(e),a=new Image;a.onload=()=>{URL.revokeObjectURL(n),t({width:a.naturalWidth,height:a.naturalHeight})},a.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to load image for dimension probing"))},a.src=n})}function Wt(e){return new Promise((t,i)=>{let n=URL.createObjectURL(e),a=document.createElement("video");a.preload="metadata",a.onloadedmetadata=()=>{URL.revokeObjectURL(n),t({width:a.videoWidth,height:a.videoHeight,durationMs:Math.round(a.duration*1e3)})},a.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to load video for metadata probing"))},a.src=n})}var Bt=class extends $.default{constructor(e,t=!1){var n,a,o;super(),this._isJoined=!1;let i=typeof t=="boolean"?{debug:t}:t;this.id=e,this.messageManager=new qt((n=i.debug)!=null?n:!1),this.typingManager=new Pt((a=i.debug)!=null?a:!1),this.callManager=new Vt(e,{debug:(o=i.debug)!=null?o:!1,getIceServers:i.getIceServers}),this.callManager.on("call_invite",s=>this.emit("call_invite",s)),this.callManager.on("call_accept",s=>this.emit("call_accept",s)),this.callManager.on("call_join",s=>this.emit("call_join",s)),this.callManager.on("call_reject",s=>this.emit("call_reject",s)),this.callManager.on("call_hangup",s=>this.emit("call_hangup",s)),this.callManager.on("peer_left",s=>this.emit("peer_left",s)),this.callManager.on("peer_mute",s=>this.emit("peer_mute",s)),this.callManager.on("peer_unmute",s=>this.emit("peer_unmute",s)),this.callManager.on("peer_video_off",s=>this.emit("peer_video_off",s)),this.callManager.on("peer_video_on",s=>this.emit("peer_video_on",s)),this.callManager.on("local_mute_changed",s=>this.emit("local_mute_changed",s)),this.callManager.on("local_video_changed",s=>this.emit("local_video_changed",s)),this.callManager.on("screen_share_changed",s=>this.emit("screen_share_changed",s)),this.callManager.on("call_connected",s=>this.emit("call_connected",s)),this.callManager.on("call_error",s=>this.emit("call_error",s)),this.callManager.on("call_timeout",s=>this.emit("call_timeout",s)),this.messageManager.on("message",s=>{s.conversationId===this.id&&this.emit("message",s)}),this.messageManager.on("receipt",s=>{this.emit("receipt",s)}),this.typingManager.on("typing",s=>{s.conversationId===this.id&&this.emit("typing",{userId:s.userId,state:s.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 o=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",o),o}if(!this._isJoined){let o=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",o),o}let n=X();this.messageManager.createOptimisticMessage(this.id,n,e,t,i);let a={type:"message",conversation_id:this.id,payload:{message_id:n,content:e,message_type:t}};try{this.sendMessageHandler(a)}catch(o){let s=o instanceof Error?o:new Error("Failed to send message");throw this.emit("error",s),s}}async sendMedia(e,t){var R,k;if(!this.sendMessageHandler){let u=new Error("Conversation is not connected. Call join() first.");throw this.emit("error",u),u}if(!this._isJoined){let u=new Error("Conversation is not joined. Call join() first.");throw this.emit("error",u),u}if(!this.uploadAttachmentCallback){let u=new Error("Media upload is not configured. Set apiUrl and appId in the Vocantly config to use sendMedia().");throw this.emit("error",u),u}let i=(R=t==null?void 0:t.fileName)!=null?R:e instanceof File?e.name:"upload",n=e.type||"application/octet-stream",a,o,s;if(n.startsWith("image/")){let u=await zt(e).catch(()=>{});a=u==null?void 0:u.width,o=u==null?void 0:u.height}else if(n.startsWith("video/")){let u=await Wt(e).catch(()=>{});a=u==null?void 0:u.width,o=u==null?void 0:u.height,s=u==null?void 0:u.durationMs}let l;try{l=await this.uploadAttachmentCallback({conversationId:this.id,file:e,fileName:i,onProgress:t==null?void 0:t.onProgress})}catch(u){let _=u instanceof Error?u:new Error("Upload failed");throw this.emit("error",_),_}let d=X(),f=[{bucket:l.bucket,key:l.key,file_name:l.fileName,mime_type:l.mimeType,size_bytes:l.sizeBytes,width:a,height:o,duration_ms:s}],v=(k=t==null?void 0:t.caption)!=null?k:"";this.messageManager.createOptimisticMessage(this.id,d,v,l.category,t==null?void 0:t.metadata,f);let b={type:"message",conversation_id:this.id,payload:{message_id:d,content:v,message_type:l.category,attachments:f}};try{this.sendMessageHandler(b)}catch(u){let _=u instanceof Error?u:new Error("Failed to send media message");throw this.emit("error",_),_}}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",t){this.ensureJoinedForCall(),this.callManager.startCall(e,t)}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}}},Jt=class extends $.default{constructor(e,t=!1,i,n,a){super(),this.conversations=new Map,this.restFetcher=null,this.appId=null,this.iceServersCache=null,this.sendMessageHandler=e,this.sendTypingHandler=n,this.sendCallHandler=a,this.supportMessageHandler=i,this.debug=t,this.logger=new P(t)}setRestFetcher(e){if(this.restFetcher=e,e)for(let t of this.conversations.values())t.setSubmitCallQuality((i,n,a)=>this.submitCallQualityToApi(i,n,a))}setAppId(e){this.appId=e&&e.trim()||null,this.iceServersCache=null}getIceServersFetcher(){if(this.restFetcher)return async()=>{var s;if(this.iceServersCache)return this.iceServersCache;if(!this.appId)throw new Error("App ID is not available for ICE server fetch");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 a=await n.json();if(!a.success||!((s=a.data)!=null&&s.iceServers))throw new Error("Invalid ICE servers response");let o=a.data.iceServers;return this.iceServersCache=o,o}}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 k,u,_;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=(k=e==null?void 0:e.externalUserId)==null?void 0:k.trim(),n=Math.min(Math.max(1,(u=e==null?void 0:e.limit)!=null?u:20),100),a=new URLSearchParams({limit:String(n)});i&&a.set("external_user_id",i),e!=null&&e.cursor&&a.set("cursor",e.cursor);let o=a.toString(),s=`${t}/sdk/conversations${o?`?${o}`:""}`,l=await this.restFetcher.getHeaders(),d=await fetch(s,{method:"GET",headers:l});if(!d.ok){let D=await d.text(),S={};try{S=JSON.parse(D)}catch{S={message:D}}throw new Error(S.message||`HTTP ${d.status}: ${D}`)}let f=await d.json();if(!f.success||!f.data)throw new Error(f.message||"Invalid response");let v=f.data,b=Array.isArray(v.conversations)?v.conversations:[],R=(_=v.pagination)!=null?_:{has_next_page:!1,next_cursor:null,limit:n};return{conversations:b,pagination:R}}async getMessages(e,t,i={}){var b;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,(b=i.limit)!=null?b:20),100),a=new URLSearchParams({limit:String(n)});t!=null&&t.trim()&&a.set("external_user_id",t.trim()),i.cursor&&a.set("cursor",i.cursor);let o=this.restFetcher.apiUrl.replace(/\/$/,""),s=a.toString(),l=`${o}/sdk/conversations/${encodeURIComponent(e.trim())}/messages${s?`?${s}`:""}`,d=await this.restFetcher.getHeaders(),f=await fetch(l,{method:"GET",headers:d});if(!f.ok){let R=await f.text(),k={};try{k=JSON.parse(R)}catch{k={message:R}}throw new Error(k.message||`HTTP ${f.status}: ${R}`)}let v=await f.json();if(!v.success||!v.data)throw new Error(v.message||"Invalid response");return{messages:v.data.messages||[],pagination:v.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`,a={...await this.restFetcher.getHeaders()};delete a["Content-Type"],delete a["content-type"];let o=new FormData;o.append("conversation_id",e.conversationId),o.append("file",e.file,e.fileName);let s=await Nt(i,o,a,e.onProgress);if(!s.success||!s.data)throw new Error(s.message||"Invalid upload response");return{bucket:s.data.bucket,key:s.data.key,category:s.data.category,fileName:s.data.file_name,mimeType:s.data.mime_type,sizeBytes:s.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}),a=`${i}/apps/${encodeURIComponent(this.appId)}/uploads/url?${n.toString()}`,o=await this.restFetcher.getHeaders(),s=await fetch(a,{method:"GET",headers:o});if(!s.ok){let d=await s.text(),f={};try{f=JSON.parse(d)}catch{f={message:d}}throw new Error(f.message||`HTTP ${s.status}: ${d}`)}let l=await s.json();if(!l.success||!l.data)throw new Error(l.message||"Invalid download URL response");return{url:l.data.url,expiresInSeconds:l.data.expires_in_seconds}}async submitCallQualityToApi(e,t,i){if(!this.restFetcher)return;let a=`${this.restFetcher.apiUrl.replace(/\/$/,"")}/conversations/${encodeURIComponent(e)}/call-quality`,o=await this.restFetcher.getHeaders(),s={end_reason:i};typeof t.duration_seconds=="number"&&(s.duration_seconds=t.duration_seconds),typeof t.packets_lost_in=="number"&&(s.packets_lost_in=t.packets_lost_in),typeof t.packets_lost_out=="number"&&(s.packets_lost_out=t.packets_lost_out),typeof t.packets_received=="number"&&(s.packets_received=t.packets_received),typeof t.packets_sent=="number"&&(s.packets_sent=t.packets_sent),typeof t.bytes_received=="number"&&(s.bytes_received=t.bytes_received),typeof t.bytes_sent=="number"&&(s.bytes_sent=t.bytes_sent),typeof t.jitter_ms=="number"&&(s.jitter_ms=t.jitter_ms),typeof t.rtt_ms=="number"&&(s.rtt_ms=t.rtt_ms);let l=await fetch(a,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!l.ok){let d=await l.text();throw this.logger.debug("submitCallQuality failed:",l.status,d),new Error(`Call quality submit failed: ${l.status}`)}}get(e){if(!e||e.length===0)throw new Error("Conversation ID is required");let t=this.conversations.get(e);return t||(t=new Bt(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,a)=>this.submitCallQualityToApi(i,n,a)),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 a=e;n.handleReceipt(a.payload.message_id,a.payload.state,a.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),a="payload"in e?e.payload:void 0;n.handleIncomingCallMessage(e.type,a)}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())}getJoinedIds(){return Array.from(this.conversations.entries()).filter(([,e])=>e.isJoined).map(([e])=>e)}clear(){for(let e of this.conversations.values())e.markLeft(),e.clearMessages(),e.clearTyping();this.conversations.clear(),this.logger.debug("Cleared all conversations")}},Kt=class extends $.default{constructor(e=!1){super(),this.presenceState=new Map,this.logger=new P(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")}},Yt=class extends $.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 P(n),this.conversation.on("message",a=>this.emit("message",a)),this.conversation.on("typing",a=>this.emit("typing",a)),this.conversation.on("presence",a=>this.emit("presence",a)),this.conversation.on("joined",a=>this.emit("joined",a)),this.conversation.on("left",a=>this.emit("left",a)),this.conversation.on("error",a=>this.emit("error",a))}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(){}},Qt=class extends $.default{constructor(e,t=!1){super(),this.sessions=new Map,this.getConversationHandler=e,this.debug=t,this.logger=new P(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 Yt(e,n,t,this.debug),i.on("assigned",a=>this.emit("assigned",{conversationId:e,...a})),i.on("unassigned",a=>this.emit("unassigned",{conversationId:e,...a})),i.on("bot_takeover",()=>this.emit("bot_takeover",{conversationId:e})),i.on("bot_released",()=>this.emit("bot_released",{conversationId:e})),i.on("closed",a=>this.emit("closed",{conversationId:e,...a})),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")}};async function N(e,t){let i=await fetch(e,t),n=await i.text(),a={};try{a=n?JSON.parse(n):{}}catch{a={message:n}}if(!i.ok)throw new Error(a.message||`HTTP ${i.status}: ${n}`);return a}var Gt=class extends $.default{constructor(e=!1){super(),this.restFetcher=null,this.sendVoiceCapableHandler=null,this.voiceCapableSent=!1,this.logger=new P(e)}setRestFetcher(e){this.restFetcher=e}setSendVoiceCapableHandler(e){this.sendVoiceCapableHandler=e}sendVoiceCapable(){if(!this.voiceCapableSent){if(!this.sendVoiceCapableHandler){this.logger.warn("sendVoiceCapable called before the WebSocket send handler was wired");return}this.sendVoiceCapableHandler({type:"voice_capable"}),this.voiceCapableSent=!0}}resetVoiceCapableState(){this.voiceCapableSent=!1}handleNotification(e){let t=e.type;switch(t){case"support_call_reservation_offered":this.emit("reservation_offered",e);break;case"support_call_reservation_rescinded":this.emit("reservation_rescinded",e);break;case"support_call_reservation_won":this.emit("reservation_won",e);break;case"support_call_fallback_available":this.emit("fallback_available",e);break;case"support_call_cancelled":this.emit("cancelled",e);break;case"support_call_request_updated":this.emit("request_updated",e);break;default:this.logger.debug("Ignoring unknown notification payload type:",t)}}requireRestFetcher(){if(!this.restFetcher)throw new Error("REST not configured. Set apiUrl in Vocantly config for call-reservation methods.");return this.restFetcher}async requestCall(e,t,i){let n=this.requireRestFetcher(),a=n.apiUrl.replace(/\/$/,""),o=await n.getHeaders();return(await N(`${a}/conversations/${encodeURIComponent(e)}/calls/requests`,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({call_type:t,idempotency_key:i})})).data.request}async cancelCallRequest(e,t){let i=this.requireRestFetcher(),n=i.apiUrl.replace(/\/$/,""),a=await i.getHeaders();return(await N(`${n}/conversations/${encodeURIComponent(e)}/calls/requests/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:a})).data.request}async getCallRequest(e,t){let i=this.requireRestFetcher(),n=i.apiUrl.replace(/\/$/,""),a=await i.getHeaders();return(await N(`${n}/conversations/${encodeURIComponent(e)}/calls/requests/${encodeURIComponent(t)}`,{method:"GET",headers:a})).data.request}async listOffers(){var a;let e=this.requireRestFetcher(),t=e.apiUrl.replace(/\/$/,""),i=await e.getHeaders();return(a=(await N(`${t}/support/calls/reservations/mine`,{method:"GET",headers:i})).data.reservations)!=null?a:[]}async acceptReservation(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),n=await t.getHeaders();return(await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/accept`,{method:"POST",headers:n})).data}async declineReservation(e,t){let i=this.requireRestFetcher(),n=i.apiUrl.replace(/\/$/,""),a=await i.getHeaders();await N(`${n}/support/calls/reservations/${encodeURIComponent(e)}/decline`,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({reason:t})})}async acknowledgeOffer(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),n=await t.getHeaders();await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/ack`,{method:"POST",headers:n})}async confirmReady(e){let t=this.requireRestFetcher(),i=t.apiUrl.replace(/\/$/,""),n=await t.getHeaders();await N(`${i}/support/calls/reservations/${encodeURIComponent(e)}/ready`,{method:"POST",headers:n})}},Xt=class{constructor(e,t){this.apiUrl=e,this.publicKey=t}resolveForm(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([i,n])=>n&&t.set(i,n)),this.request(`/tickets/public/form${t.size?`?${t}`:""}`)}create(e){return this.request("/tickets/public",{method:"POST",body:JSON.stringify(e)})}getStatus(e,t){return this.request(`/tickets/public/${encodeURIComponent(e)}?token=${encodeURIComponent(t)}`,{},!1)}async reply(e,t,i,n=X()){await this.request(`/tickets/public/${encodeURIComponent(e)}/reply?token=${encodeURIComponent(t)}`,{method:"POST",body:JSON.stringify({body:i,idempotency_key:n})},!1)}async request(e,t={},i=!0){var o,s;let n=await fetch(this.apiUrl.replace(/\/$/,"")+e,{...t,headers:{"Content-Type":"application/json",...i?{"X-Api-Key":this.publicKey}:{},...(o=t.headers)!=null?o:{}}}),a=await n.json().catch(()=>({}));if(!n.ok)throw new Error(a.message||`Ticket request failed (${n.status})`);return(s=a.data)!=null?s:a}},et=class extends $.default{constructor(e){var o,s;super(),this.connectionState="disconnected",this.wsClient=null,this.config={autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,debug:!1,apiUrl:"",...e},this.tokenManager=new Ot,this.tokenManager.setToken(e.token),this.logger=new P(this.config.debug),this.wsClient=new jt(this.config.wsUrl,{autoReconnect:this.config.autoReconnect,maxReconnectAttempts:this.config.maxReconnectAttempts,reconnectDelay:this.config.reconnectDelay,debug:this.config.debug}),this.supportManager=new Qt(l=>this.conversationManager.get(l),this.config.debug),this.conversationManager=new Jt(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},this.config.debug,void 0,l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)},l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.conversationManager.setSendReadHandler(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)}),this.presenceManager=new Kt(this.config.debug),this.presenceManager.on("presence",l=>{this.emit("presence",l)}),this.reservationManager=new Gt(this.config.debug),this.reservationManager.setSendVoiceCapableHandler(l=>{if(!this.wsClient)throw new Error("WebSocket client not initialized");this.wsClient.send(l)});for(let l of["reservation_offered","reservation_rescinded","reservation_won","fallback_available","cancelled","request_updated"])this.reservationManager.on(l,d=>this.emit(l,d));let t=(o=this.config.apiUrl)==null?void 0:o.trim(),i=(s=this.config.appId)==null?void 0:s.trim(),n=this.config.apiKey&&this.config.apiSecret,a=typeof this.config.getRestHeaders=="function";if(t){let l=async()=>{if(a&&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 d=this.tokenManager.getToken();if(!d)throw new Error("Token required for list() and fetchMessages() when API keys are not set");return{Authorization:`Bearer ${d}`,"Content-Type":"application/json"}};this.conversationManager.setRestFetcher({apiUrl:t,getHeaders:l}),this.reservationManager.setRestFetcher({apiUrl:t,getHeaders:l}),i&&this.conversationManager.setAppId(i),this.config.publicKey&&(this.ticketManager=new Xt(t,this.config.publicKey))}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.rejoinActiveConversations(),this.config.declareVoiceCapable&&this.reservationManager.sendVoiceCapable()}),this.wsClient.on("disconnected",e=>{this.connectionState="disconnected",this.emit("disconnected",e),this.emit("state",this.connectionState),this.logger.debug("SDK disconnected"),this.reservationManager.resetVoiceCapableState()}),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)}if(e.type==="support"&&this.conversationManager.routeSupportMessage(e),e.type==="notification"){let t=e;t.payload&&this.reservationManager.handleNotification(t.payload)}switch(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"notification":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)}}get tickets(){if(!this.ticketManager)throw new Error("tickets requires both apiUrl and publicKey");return this.ticketManager}get reservations(){return this.reservationManager}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 rejoinActiveConversations(){let e=this.conversationManager.getJoinedIds();for(let t of e)try{await this.joinConversation(t)}catch(i){this.logger.warn("Failed to rejoin conversation after reconnect:",t,i)}}async leaveConversation(e){if(!this.isConnected())throw new Error("Must be connected before leaving a conversation");if(!e||e.length===0)throw new Error("Conversation ID is required");if(!this.wsClient)throw new Error("WebSocket client not initialized");let t={type:"leave",conversation_id:e};try{this.wsClient.send(t),this.logger.debug("Leave conversation sent:",e)}catch(i){let n=i instanceof Error?i:new Error("Failed to leave conversation");throw this.emit("error",n),n}}setAppId(e){let t=(e==null?void 0:e.trim())||null;this.config.appId=t!=null?t:void 0,this.conversationManager.setAppId(t)}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 ei={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,tickets:!0,ticketLabel:"Raise a ticket",callBundleUrl:"https://cdn.jsdelivr.net/npm/@vocantly/widget@0.1.24/dist/vocantly-widget-call.js"},U=null;function nt(e){try{return JSON.parse(atob(e.split(".")[1]))}catch{return null}}function tt(e){let t=nt(e);return(t==null?void 0:t.user_id)||(t==null?void 0:t.sub)||null}function ti(e){return typeof e!="number"?"":e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+" KB":(e/(1024*1024)).toFixed(1)+" MB"}function y(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Ce(e){return y(e).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>").replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\n/g,"<br>")}var ie=null;function ii(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;ie=ie||new e,ie.resume&&ie.resume();let t=ie,i=t.currentTime,n=t.createOscillator(),a=t.createGain();n.type="sine",n.frequency.setValueAtTime(880,i),n.frequency.exponentialRampToValueAtTime(1320,i+.08),a.gain.setValueAtTime(1e-4,i),a.gain.exponentialRampToValueAtTime(.16,i+.02),a.gain.exponentialRampToValueAtTime(1e-4,i+.34),n.connect(a).connect(t.destination),n.start(i),n.stop(i+.36)}catch{}}function it(e,t){let i=String(e).replace("#",""),n=i.length===3?i.split("").map(l=>l+l).join(""):i,a=parseInt(n.slice(0,2),16)||0,o=parseInt(n.slice(2,4),16)||0,s=parseInt(n.slice(4,6),16)||0;return`rgba(${a},${o},${s},${t})`}function ni(e,t){if(document.getElementById("caf-widget-styles"))return;let o=`
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;}
@@ -197,7 +197,7 @@ var xt=Object.create;var Ne=Object.defineProperty;var kt=Object.getOwnPropertyDe
197
197
  }
198
198
  @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}}
199
199
  @media (prefers-reduced-motion:reduce){.caf-panel,.caf-launcher,.caf-send,.caf-fbtn{transition:none!important;}.caf-media-skeleton{animation:none!important;}}
200
- `,r=document.createElement("style");r.id="caf-widget-styles",r.textContent=o,document.head.appendChild(r)}function ni(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
200
+ `,s=document.createElement("style");s.id="caf-widget-styles",s.textContent=o,document.head.appendChild(s)}function ai(e){let t=document.createElement("div");return t.className="caf-root",t.innerHTML=`
201
201
  <div class="caf-panel" id="caf-support-panel" role="dialog" aria-labelledby="caf-support-title" aria-hidden="true">
202
202
  <div class="caf-header">
203
203
  <div class="caf-headmark" aria-hidden="true">
@@ -236,17 +236,17 @@ var xt=Object.create;var Ne=Object.defineProperty;var kt=Object.getOwnPropertyDe
236
236
  <button class="caf-launcher" data-caf="launcher" aria-label="Open support chat" aria-controls="caf-support-panel" aria-expanded="false">
237
237
  <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>':y(e.launcher)}</span>
238
238
  <span class="caf-badge" data-caf="badge" style="display:none">0</span>
239
- </button>`,document.body.appendChild(t),{root:t,$:a=>t.querySelector(`[data-caf="${a}"]`)}}function Pi(e){if(I)return I.open(),I.api;let t={...ei,...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");ai(t.primaryColor,t.position);let{root:i,$:a}=ni(t),n={panel:i.querySelector(".caf-panel"),msgs:a("msgs"),input:a("input"),send:a("send"),dot:a("dot"),badge:a("badge"),launcher:a("launcher"),call:a("call"),file:a("file"),attach:a("attach"),ticket:a("ticket"),upload:a("upload"),uploadBar:a("upload-bar"),uploadLabel:a("upload-label"),pending:a("pending"),pendingThumb:a("pending-thumb"),pendingName:a("pending-name"),pendingRemove:a("pending-remove"),human:a("human"),feedback:a("feedback")},o=null;function r(s,c="error",h=5e3){n.feedback&&(o&&clearTimeout(o),n.feedback.textContent=s,n.feedback.className=`caf-feedback show${c==="success"?" success":""}`,n.feedback.setAttribute("role",c==="error"?"alert":"status"),h>0&&(o=setTimeout(()=>{n.feedback.className="caf-feedback",n.feedback.textContent=""},h)))}function l(){o&&clearTimeout(o),o=null,n.feedback.className="caf-feedback",n.feedback.textContent=""}let d=null,f=!1,v=()=>t.calls===!0||f;function b(){d&&F&&n.call&&(n.call.style.display="flex")}function R(){return new Promise((s,c)=>{if(window.VocantlyWidgetCall)return s();let h=document.createElement("script");h.src=t.callBundleUrl,h.async=!0,h.onload=()=>s(),h.onerror=()=>c(new Error("call bundle load failed")),document.head.appendChild(h)})}async function k(){if(!(d||!j))try{if(await R(),!window.VocantlyWidgetCall)return;let s=document.createElement("div");document.body.appendChild(s),d=window.VocantlyWidgetCall.mount(s,j,{logoText:"CA",sessionTitle:t.title||"Call",sessionSubtitle:t.subtitle||"Secured via Vocantly",primaryColor:t.primaryColor,self:{name:"You",role:"Visitor"},peer:{name:t.title||"Support",role:"Agent"},voiceOnly:!0,simple:!0},S.reservations),n.call&&(n.call.onclick=()=>d.startCall("voice")),b()}catch(s){r("Calling is unavailable right now. You can keep chatting with support."),t.debug&&console.error("[caf] call setup failed",s)}}let u=t.token||"",_=t.conversationId||"",P=u?tt(u):null,S=null,Se=new Set,_e=!1,ae=!1,Te=0,Me=!1,F=!t.collectContact,Ee=!1,J=s=>{n.dot.className="caf-dot"+(s?" "+s:"")},z=()=>{if(n.panel.classList.contains("caf-prechat")){n.msgs.scrollTop=0;return}n.msgs.scrollTop=n.msgs.scrollHeight},Re=s=>{Te=s,n.badge.textContent=String(s),n.badge.style.display=s>0?"flex":"none"};function ne(s,c){let h=document.createElement("div");h.className="caf-m "+s,h.innerHTML=c,n.msgs.appendChild(h),z()}let q=null,re=new Set;function nt(){q||(q=document.createElement("div"),q.className="caf-m caf-other caf-typing",q.setAttribute("role","status"),q.setAttribute("aria-live","polite"),q.setAttribute("aria-label","Support is typing"),q.innerHTML='<span class="caf-typing-dot" aria-hidden="true"></span><span class="caf-typing-dot" aria-hidden="true"></span><span class="caf-typing-dot" aria-hidden="true"></span>',n.msgs.appendChild(q),z())}function Ae(){q&&(q.remove(),q=null)}function $e(){re.clear(),Ae()}function rt(s){var g,p;let c=String((p=(g=s==null?void 0:s.userId)!=null?g:s==null?void 0:s.user_id)!=null?p:""),h=s==null?void 0:s.state;!c||c===String(P!=null?P:"")||(h==="start"?re.add(c):re.delete(c),re.size>0?nt():Ae())}function Ue(s){var C,O,T,V,H,U;if($e(),s.optimistic)return;let c=(C=s.id)!=null?C:s.message_id,h=(T=(O=s.senderId)!=null?O:s.sender_id)!=null?T:"",g=(H=(V=s.content)!=null?V:s.text)!=null?H:"",p=(U=s.messageType)!=null?U:s.message_type,w=s.attachments,x=c||`${h}:${g}`;if(Se.has(x))return;if(Se.add(x),p==="system"){ne("caf-note",Ce(g)),t.csat&&ct();return}let m=P&&h===P;(p==="image"||p==="video"||p==="file")&&w&&w.length?ot(m,g,p,w[0]):ne(m?"caf-self":"caf-other",Ce(g)),!m&&_e&&ii(),!m&&!ae&&Re(Te+1)}function st(s,c){return`<div class="caf-media-skeleton" style="${s!=="file"&&c.width&&c.height?`aspect-ratio:${c.width}/${c.height};`:"aspect-ratio:4/3;"}"></div>`}function Ie(s,c){let h=`<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>
240
- <span class="caf-file-meta"><span class="caf-file-name">${y(s.file_name)}</span><span class="caf-file-size">${y(ti(s.size_bytes))}</span></span>`;return c?`<a class="caf-file-chip" href="${c}" target="_blank" rel="noopener noreferrer" download="${y(s.file_name)}">${h}</a>`:`<div class="caf-file-chip">${h}</div>`}function ue(s,c){s&&(s.innerHTML=`<div class="caf-media-error">Couldn't load ${y(c)}</div>`)}function ot(s,c,h,g){let p=document.createElement("div");if(p.className="caf-m caf-media "+(s?"caf-self":"caf-other"),p.innerHTML=`<div class="caf-media-body" data-media>${h==="file"?Ie(g):st(h,g)}</div>`,c){let w=document.createElement("div");w.className="caf-media-caption",w.innerHTML=Ce(c),p.appendChild(w)}n.msgs.appendChild(p),z(),S&&S.conversations.getAttachmentDownloadUrl(g.bucket,g.key).then(w=>{let x=p.querySelector("[data-media]");if(x){if(h==="image"){let m=document.createElement("a");m.href=w.url,m.target="_blank",m.rel="noopener noreferrer";let C=document.createElement("img");C.alt=g.file_name,C.loading="lazy",C.onerror=()=>ue(x,g.file_name),C.src=w.url,m.appendChild(C),x.innerHTML="",x.appendChild(m)}else if(h==="video"){let m=document.createElement("video");m.controls=!0,m.preload="metadata",m.onerror=()=>ue(x,g.file_name),m.src=w.url,x.innerHTML="",x.appendChild(m)}else x.innerHTML=Ie(g,w.url);z()}}).catch(w=>{t.debug&&console.error("[caf] attachment load failed",w),ue(p.querySelector("[data-media]"),g.file_name)})}let je=!1;function ct(){if(je||!t.apiUrl||!_)return;je=!0;let s=document.createElement("div");s.className="caf-csat",s.innerHTML=`<div>${y(t.csatPrompt)}</div><div class="caf-csat-row"></div>`;let c=s.querySelector(".caf-csat-row");[["1","\u{1F61E}"],["2","\u{1F641}"],["3","\u{1F610}"],["4","\u{1F642}"],["5","\u{1F600}"]].forEach(([h,g])=>{let p=document.createElement("button");p.className="caf-csat-b",p.type="button",p.textContent=g,p.setAttribute("aria-label",h+" out of 5"),p.onclick=()=>lt(Number(h),s),c.appendChild(p)}),n.msgs.appendChild(s),z()}async function lt(s,c){c.innerHTML=`<div>${y(t.csatThanks)}</div>`,z();try{await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/conversations/"+_+"/rating",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u},body:JSON.stringify({rating:s})})}catch(h){t.debug&&console.error("[caf] csat failed",h)}}function se(s){n.input.disabled=!s,n.send.disabled=!s,n.attach.disabled=!s,n.human.disabled=!s,n.input.placeholder=s?t.placeholder:"\u2026"}function Oe(){!Me&&t.greeting&&(ne("caf-sys",y(t.greeting)),Me=!0)}function ge(s,c){return!s||typeof s!="object"?"":s[c]||s.en||Object.values(s)[0]||""}function dt(){let s=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";if(!s)return;let c=null;try{c=localStorage.getItem(s)}catch{}if(!c){c="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(s,c)}catch{}}return c}function ht(s,c){if(s.visibility==="agent_only"||s.type==="hidden")return"";let h=y(ge(s.label,c)||s.key),g=y(ge(s.placeholder,c)),p=s.required?' required aria-required="true"':"",w=(s.options||[]).filter(m=>m.is_active).map(m=>`<option value="${y(m.value)}">${y(ge(m.label,c)||m.value)}</option>`).join(""),x;if(s.type==="long_text")x=`<textarea class="caf-fi" name="${y(s.key)}" placeholder="${g}"${p}></textarea>`;else if(s.type==="select")x=`<select class="caf-fi" name="${y(s.key)}"${p}><option value="">Select\u2026</option>${w}</select>`;else{if(s.type==="checkbox"||s.type==="consent")return`<label class="caf-check-field"><input name="${y(s.key)}" type="checkbox"${p} /><span>${h}${s.required?' <span class="caf-required">*</span>':""}</span></label><span class="caf-field-error">Please confirm this field.</span>`;{let m=s.type==="email"?"email":s.type==="phone"?"tel":s.type==="number"||s.type==="currency"?"number":s.type==="date"?"date":s.type==="url"?"url":"text";x=`<input class="caf-fi" name="${y(s.key)}" type="${m}" placeholder="${g}"${p} />`}}return`<label class="caf-fl">${h}${s.required?' <span class="caf-required">*</span>':' <span class="caf-optional">Optional</span>'}${x}<span class="caf-field-error">Please complete this field.</span></label>`}function He(){return`<div class="caf-ticket-intro">
239
+ </button>`,document.body.appendChild(t),{root:t,$:n=>t.querySelector(`[data-caf="${n}"]`)}}function Di(e){if(U)return U.open(),U.api;let t={...ei,...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");ni(t.primaryColor,t.position);let{root:i,$:n}=ai(t),a={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"),ticket:n("ticket"),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"),human:n("human"),feedback:n("feedback")},o=null;function s(r,c="error",h=5e3){a.feedback&&(o&&clearTimeout(o),a.feedback.textContent=r,a.feedback.className=`caf-feedback show${c==="success"?" success":""}`,a.feedback.setAttribute("role",c==="error"?"alert":"status"),h>0&&(o=setTimeout(()=>{a.feedback.className="caf-feedback",a.feedback.textContent=""},h)))}function l(){o&&clearTimeout(o),o=null,a.feedback.className="caf-feedback",a.feedback.textContent=""}let d=null,f=!1,v=()=>t.calls===!0||f;function b(){d&&F&&a.call&&(a.call.style.display="flex")}function R(){return new Promise((r,c)=>{if(window.VocantlyWidgetCall)return r();let h=document.createElement("script");h.src=t.callBundleUrl,h.async=!0,h.onload=()=>r(),h.onerror=()=>c(new Error("call bundle load failed")),document.head.appendChild(h)})}async function k(){if(!(d||!j))try{if(await R(),!window.VocantlyWidgetCall)return;let r=document.createElement("div");document.body.appendChild(r),d=window.VocantlyWidgetCall.mount(r,j,{logoText:"CA",sessionTitle:t.title||"Call",sessionSubtitle:t.subtitle||"Secured via Vocantly",primaryColor:t.primaryColor,self:{name:"You",role:"Visitor"},peer:{name:t.title||"Support",role:"Agent"},voiceOnly:!0,simple:!0},S.reservations),a.call&&(a.call.onclick=()=>d.startCall("voice")),b()}catch(r){s("Calling is unavailable right now. You can keep chatting with support."),t.debug&&console.error("[caf] call setup failed",r)}}let u=t.token||"",_=t.conversationId||"",D=u?tt(u):null,S=null,Se=new Set,_e=!1,ne=!1,Te=0,Me=!1,F=!t.collectContact,Ee=!1,J=r=>{a.dot.className="caf-dot"+(r?" "+r:"")},z=()=>{if(a.panel.classList.contains("caf-prechat")){a.msgs.scrollTop=0;return}a.msgs.scrollTop=a.msgs.scrollHeight},Re=r=>{Te=r,a.badge.textContent=String(r),a.badge.style.display=r>0?"flex":"none"};function ae(r,c){let h=document.createElement("div");h.className="caf-m "+r,h.innerHTML=c,a.msgs.appendChild(h),z()}let q=null,se=new Set;function at(){q||(q=document.createElement("div"),q.className="caf-m caf-other caf-typing",q.setAttribute("role","status"),q.setAttribute("aria-live","polite"),q.setAttribute("aria-label","Support is typing"),q.innerHTML='<span class="caf-typing-dot" aria-hidden="true"></span><span class="caf-typing-dot" aria-hidden="true"></span><span class="caf-typing-dot" aria-hidden="true"></span>',a.msgs.appendChild(q),z())}function Ae(){q&&(q.remove(),q=null)}function $e(){se.clear(),Ae()}function st(r){var g,p;let c=String((p=(g=r==null?void 0:r.userId)!=null?g:r==null?void 0:r.user_id)!=null?p:""),h=r==null?void 0:r.state;!c||c===String(D!=null?D:"")||(h==="start"?se.add(c):se.delete(c),se.size>0?at():Ae())}function Ie(r){var C,O,T,V,H,I;if($e(),r.optimistic)return;let c=(C=r.id)!=null?C:r.message_id,h=(T=(O=r.senderId)!=null?O:r.sender_id)!=null?T:"",g=(H=(V=r.content)!=null?V:r.text)!=null?H:"",p=(I=r.messageType)!=null?I:r.message_type,w=r.attachments,x=c||`${h}:${g}`;if(Se.has(x))return;if(Se.add(x),p==="system"){ae("caf-note",Ce(g)),t.csat&&ct();return}let m=D&&h===D;(p==="image"||p==="video"||p==="file")&&w&&w.length?ot(m,g,p,w[0]):ae(m?"caf-self":"caf-other",Ce(g)),!m&&_e&&ii(),!m&&!ne&&Re(Te+1)}function rt(r,c){return`<div class="caf-media-skeleton" style="${r!=="file"&&c.width&&c.height?`aspect-ratio:${c.width}/${c.height};`:"aspect-ratio:4/3;"}"></div>`}function Ue(r,c){let h=`<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>
240
+ <span class="caf-file-meta"><span class="caf-file-name">${y(r.file_name)}</span><span class="caf-file-size">${y(ti(r.size_bytes))}</span></span>`;return c?`<a class="caf-file-chip" href="${c}" target="_blank" rel="noopener noreferrer" download="${y(r.file_name)}">${h}</a>`:`<div class="caf-file-chip">${h}</div>`}function ue(r,c){r&&(r.innerHTML=`<div class="caf-media-error">Couldn't load ${y(c)}</div>`)}function ot(r,c,h,g){let p=document.createElement("div");if(p.className="caf-m caf-media "+(r?"caf-self":"caf-other"),p.innerHTML=`<div class="caf-media-body" data-media>${h==="file"?Ue(g):rt(h,g)}</div>`,c){let w=document.createElement("div");w.className="caf-media-caption",w.innerHTML=Ce(c),p.appendChild(w)}a.msgs.appendChild(p),z(),S&&S.conversations.getAttachmentDownloadUrl(g.bucket,g.key).then(w=>{let x=p.querySelector("[data-media]");if(x){if(h==="image"){let m=document.createElement("a");m.href=w.url,m.target="_blank",m.rel="noopener noreferrer";let C=document.createElement("img");C.alt=g.file_name,C.loading="lazy",C.onerror=()=>ue(x,g.file_name),C.src=w.url,m.appendChild(C),x.innerHTML="",x.appendChild(m)}else if(h==="video"){let m=document.createElement("video");m.controls=!0,m.preload="metadata",m.onerror=()=>ue(x,g.file_name),m.src=w.url,x.innerHTML="",x.appendChild(m)}else x.innerHTML=Ue(g,w.url);z()}}).catch(w=>{t.debug&&console.error("[caf] attachment load failed",w),ue(p.querySelector("[data-media]"),g.file_name)})}let je=!1;function ct(){if(je||!t.apiUrl||!_)return;je=!0;let r=document.createElement("div");r.className="caf-csat",r.innerHTML=`<div>${y(t.csatPrompt)}</div><div class="caf-csat-row"></div>`;let c=r.querySelector(".caf-csat-row");[["1","\u{1F61E}"],["2","\u{1F641}"],["3","\u{1F610}"],["4","\u{1F642}"],["5","\u{1F600}"]].forEach(([h,g])=>{let p=document.createElement("button");p.className="caf-csat-b",p.type="button",p.textContent=g,p.setAttribute("aria-label",h+" out of 5"),p.onclick=()=>lt(Number(h),r),c.appendChild(p)}),a.msgs.appendChild(r),z()}async function lt(r,c){c.innerHTML=`<div>${y(t.csatThanks)}</div>`,z();try{await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/conversations/"+_+"/rating",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u},body:JSON.stringify({rating:r})})}catch(h){t.debug&&console.error("[caf] csat failed",h)}}function re(r){a.input.disabled=!r,a.send.disabled=!r,a.attach.disabled=!r,a.human.disabled=!r,a.input.placeholder=r?t.placeholder:"\u2026"}function Oe(){!Me&&t.greeting&&(ae("caf-sys",y(t.greeting)),Me=!0)}function ge(r,c){return!r||typeof r!="object"?"":r[c]||r.en||Object.values(r)[0]||""}function dt(){let r=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";if(!r)return;let c=null;try{c=localStorage.getItem(r)}catch{}if(!c){c="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(r,c)}catch{}}return c}function ht(r,c){if(r.visibility==="agent_only"||r.type==="hidden")return"";let h=y(ge(r.label,c)||r.key),g=y(ge(r.placeholder,c)),p=r.required?' required aria-required="true"':"",w=(r.options||[]).filter(m=>m.is_active).map(m=>`<option value="${y(m.value)}">${y(ge(m.label,c)||m.value)}</option>`).join(""),x;if(r.type==="long_text")x=`<textarea class="caf-fi" name="${y(r.key)}" placeholder="${g}"${p}></textarea>`;else if(r.type==="select")x=`<select class="caf-fi" name="${y(r.key)}"${p}><option value="">Select\u2026</option>${w}</select>`;else{if(r.type==="checkbox"||r.type==="consent")return`<label class="caf-check-field"><input name="${y(r.key)}" type="checkbox"${p} /><span>${h}${r.required?' <span class="caf-required">*</span>':""}</span></label><span class="caf-field-error">Please confirm this field.</span>`;{let m=r.type==="email"?"email":r.type==="phone"?"tel":r.type==="number"||r.type==="currency"?"number":r.type==="date"?"date":r.type==="url"?"url":"text";x=`<input class="caf-fi" name="${y(r.key)}" type="${m}" placeholder="${g}"${p} />`}}return`<label class="caf-fl">${h}${r.required?' <span class="caf-required">*</span>':' <span class="caf-optional">Optional</span>'}${x}<span class="caf-field-error">Please complete this field.</span></label>`}function He(){return`<div class="caf-ticket-intro">
241
241
  <div class="caf-form-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v3a2 2 0 0 0 0 4v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 0 0-4V5Z"/><path d="M13 5v2M13 11v2M13 17v2"/></svg></div>
242
242
  <div class="caf-ticket-intro-copy"><div class="caf-form-t">${y(t.ticketLabel)}</div><p class="caf-form-d">Tell us what happened. We\u2019ll create a reference so you can track every update.</p></div>
243
- </div>`}function pt(s){let c=null;return s.querySelectorAll("input, textarea, select").forEach(h=>{let g="";h.required&&(h.type==="checkbox"?!h.checked:!String(h.value||"").trim())?g=h.type==="checkbox"?"Please confirm this field.":"Please complete this field.":h.type==="email"&&h.value&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h.value.trim())&&(g="Enter a valid email address."),h.setAttribute("aria-invalid",g?"true":"false");let p=h.closest(".caf-fl")||h.closest(".caf-check-field"),w=(p==null?void 0:p.querySelector(".caf-field-error"))||(p==null?void 0:p.nextElementSibling);w!=null&&w.classList.contains("caf-field-error")&&(w.textContent=g,w.classList.toggle("show",!!g)),g&&!c&&(c=h)}),c?(c.focus(),c.scrollIntoView({block:"center",behavior:"smooth"}),!1):!0}async function ft(){var h;if(!t.tickets||!t.publicKey||!t.apiUrl)return;n.panel.classList.add("caf-ticketing");let s=(navigator.language||"en").split("-")[0],c=document.createElement("form");c.className="caf-form caf-ticket-form",c.noValidate=!0,c.innerHTML=`${He()}<div class="caf-ferr" role="status">Loading your ticket form\u2026</div>`,n.msgs.appendChild(c),z();try{let g=t.apiUrl.replace(/\/$/,""),p=await fetch(g+"/tickets/public/form?language="+encodeURIComponent(s),{headers:{"X-Api-Key":t.publicKey}});if(!p.ok)throw new Error("ticket form HTTP "+p.status);let w=await p.json(),x=w.data||w,m=((h=x.schema)==null?void 0:h.fields)||[],C="caf_ticket_submission_"+t.publicKey.slice(-10),O;try{O=sessionStorage.getItem(C)}catch{}if(!O){O=typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"sub_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{sessionStorage.setItem(C,O)}catch{}}c.innerHTML=`${He()}
243
+ </div>`}function pt(r){let c=null;return r.querySelectorAll("input, textarea, select").forEach(h=>{let g="";h.required&&(h.type==="checkbox"?!h.checked:!String(h.value||"").trim())?g=h.type==="checkbox"?"Please confirm this field.":"Please complete this field.":h.type==="email"&&h.value&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h.value.trim())&&(g="Enter a valid email address."),h.setAttribute("aria-invalid",g?"true":"false");let p=h.closest(".caf-fl")||h.closest(".caf-check-field"),w=(p==null?void 0:p.querySelector(".caf-field-error"))||(p==null?void 0:p.nextElementSibling);w!=null&&w.classList.contains("caf-field-error")&&(w.textContent=g,w.classList.toggle("show",!!g)),g&&!c&&(c=h)}),c?(c.focus(),c.scrollIntoView({block:"center",behavior:"smooth"}),!1):!0}async function ft(){var h;if(!t.tickets||!t.publicKey||!t.apiUrl)return;a.panel.classList.add("caf-ticketing");let r=(navigator.language||"en").split("-")[0],c=document.createElement("form");c.className="caf-form caf-ticket-form",c.noValidate=!0,c.innerHTML=`${He()}<div class="caf-ferr" role="status">Loading your ticket form\u2026</div>`,a.msgs.appendChild(c),z();try{let g=t.apiUrl.replace(/\/$/,""),p=await fetch(g+"/tickets/public/form?language="+encodeURIComponent(r),{headers:{"X-Api-Key":t.publicKey}});if(!p.ok)throw new Error("ticket form HTTP "+p.status);let w=await p.json(),x=w.data||w,m=((h=x.schema)==null?void 0:h.fields)||[],C="caf_ticket_submission_"+t.publicKey.slice(-10),O;try{O=sessionStorage.getItem(C)}catch{}if(!O){O=typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"sub_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{sessionStorage.setItem(C,O)}catch{}}c.innerHTML=`${He()}
244
244
  <label class="caf-fl">Subject <span class="caf-required">*</span><input class="caf-fi" name="subject" required placeholder="Briefly describe the issue" /><span class="caf-field-error">Please complete this field.</span></label>
245
245
  <label class="caf-fl">What happened? <span class="caf-required">*</span><textarea class="caf-fi" name="description" required placeholder="Share what happened, what you expected, and anything you\u2019ve already tried."></textarea><span class="caf-field-error">Please complete this field.</span></label>
246
246
  <label class="caf-fl">Name <span class="caf-optional">Optional</span><input class="caf-fi" name="name" autocomplete="name" placeholder="Your name" /><span class="caf-field-error"></span></label>
247
247
  <label class="caf-fl">Email <span class="caf-optional">Optional</span><input class="caf-fi" name="email" type="email" inputmode="email" autocomplete="email" autocapitalize="none" spellcheck="false" placeholder="you@company.com" /><span class="caf-field-error"></span></label>
248
- ${m.map(T=>ht(T,s)).join("")}
249
- <div class="caf-ferr" data-ticket-error role="alert" aria-live="polite"></div><div class="caf-ticket-actions"><button class="caf-ticket-cancel" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span>Back</span></button><button class="caf-fbtn" type="submit"><span>Submit ticket</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></div>`,c.querySelector(".caf-ticket-cancel").onclick=()=>{c.remove(),n.panel.classList.remove("caf-ticketing")},c.querySelectorAll("input, textarea, select").forEach(T=>{let V=()=>{if(!T.getAttribute("aria-invalid")||T.getAttribute("aria-invalid")==="false")return;T.setAttribute("aria-invalid","false");let H=T.closest(".caf-fl")||T.closest(".caf-check-field"),U=(H==null?void 0:H.querySelector(".caf-field-error"))||(H==null?void 0:H.nextElementSibling);U!=null&&U.classList.contains("caf-field-error")&&U.classList.remove("show")};T.addEventListener(T.type==="checkbox"||T.tagName==="SELECT"?"change":"input",V)}),c.onsubmit=async T=>{T.preventDefault();let V=c.querySelector(".caf-fbtn"),H=c.querySelector("[data-ticket-error]");if(!pt(c)){H.textContent="Please review the highlighted fields.";return}V.disabled=!0,H.textContent="",V.querySelector("span").textContent="Creating ticket\u2026";let U=new FormData(c),Fe={};m.forEach(L=>{L.visibility==="agent_only"||L.type==="hidden"||(Fe[L.key]=L.type==="checkbox"||L.type==="consent"?U.get(L.key)==="on":U.get(L.key))});try{let L=await fetch(g+"/tickets/public",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({subject:U.get("subject"),description:U.get("description"),name:U.get("name")||void 0,email:U.get("email")||void 0,visitor_id:dt(),external_reference:"widget:"+O,language:s,form_version_id:x.form_version_id,custom_fields:Fe})}),we=await L.json();if(!L.ok)throw new Error(we.message||"Could not create ticket");let W=we.data||we;try{localStorage.setItem("caf_ticket_"+W.reference,JSON.stringify(W))}catch{}try{sessionStorage.removeItem(C)}catch{}c.classList.add("caf-ticket-success");let Ve=W.status_url||(W.secure_token?`${location.origin}/ticket/${encodeURIComponent(W.reference)}?token=${encodeURIComponent(W.secure_token)}`:"");c.innerHTML=`<div class="caf-form-icon" style="margin-left:auto;margin-right:auto">\u2713</div><div class="caf-form-t">Ticket created</div><p class="caf-form-d">Keep this reference for future updates.</p><div class="caf-ticket-ref">${y(W.reference)}</div>${Ve?`<a class="caf-ticket-view" href="${y(Ve)}" target="_blank" rel="noopener noreferrer">View ticket status</a>`:""}<button class="caf-fbtn" type="button">Return to conversation</button>`,c.querySelector("button").onclick=()=>{c.remove(),n.panel.classList.remove("caf-ticketing")}}catch(L){H.textContent=L.message||"Could not create ticket. Please try again.",V.disabled=!1,V.querySelector("span").textContent="Submit ticket"}}}catch(g){c.querySelector(".caf-ferr").textContent="Ticket forms are unavailable right now.",t.debug&&console.error("[caf] ticket form failed",g),setTimeout(()=>{c.remove(),n.panel.classList.remove("caf-ticketing")},2500)}}async function ut(s,c){if(!t.apiUrl)return;if(await de(),!u)throw new Error("Support connection is not ready");if(!(await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/customers/me",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u},body:JSON.stringify({name:s||void 0,email:c||void 0})})).ok)throw new Error("Could not save contact details")}function gt(){Ee=!0,n.panel.classList.add("caf-prechat");let s=document.createElement("form");s.className="caf-form",s.noValidate=!0,s.innerHTML=`
248
+ ${m.map(T=>ht(T,r)).join("")}
249
+ <div class="caf-ferr" data-ticket-error role="alert" aria-live="polite"></div><div class="caf-ticket-actions"><button class="caf-ticket-cancel" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span>Back</span></button><button class="caf-fbtn" type="submit"><span>Submit ticket</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></div>`,c.querySelector(".caf-ticket-cancel").onclick=()=>{c.remove(),a.panel.classList.remove("caf-ticketing")},c.querySelectorAll("input, textarea, select").forEach(T=>{let V=()=>{if(!T.getAttribute("aria-invalid")||T.getAttribute("aria-invalid")==="false")return;T.setAttribute("aria-invalid","false");let H=T.closest(".caf-fl")||T.closest(".caf-check-field"),I=(H==null?void 0:H.querySelector(".caf-field-error"))||(H==null?void 0:H.nextElementSibling);I!=null&&I.classList.contains("caf-field-error")&&I.classList.remove("show")};T.addEventListener(T.type==="checkbox"||T.tagName==="SELECT"?"change":"input",V)}),c.onsubmit=async T=>{T.preventDefault();let V=c.querySelector(".caf-fbtn"),H=c.querySelector("[data-ticket-error]");if(!pt(c)){H.textContent="Please review the highlighted fields.";return}V.disabled=!0,H.textContent="",V.querySelector("span").textContent="Creating ticket\u2026";let I=new FormData(c),Fe={};m.forEach(L=>{L.visibility==="agent_only"||L.type==="hidden"||(Fe[L.key]=L.type==="checkbox"||L.type==="consent"?I.get(L.key)==="on":I.get(L.key))});try{let L=await fetch(g+"/tickets/public",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({subject:I.get("subject"),description:I.get("description"),name:I.get("name")||void 0,email:I.get("email")||void 0,visitor_id:dt(),external_reference:"widget:"+O,language:r,form_version_id:x.form_version_id,custom_fields:Fe})}),we=await L.json();if(!L.ok)throw new Error(we.message||"Could not create ticket");let W=we.data||we;try{localStorage.setItem("caf_ticket_"+W.reference,JSON.stringify(W))}catch{}try{sessionStorage.removeItem(C)}catch{}c.classList.add("caf-ticket-success");let Ve=W.status_url||(W.secure_token?`${location.origin}/ticket/${encodeURIComponent(W.reference)}?token=${encodeURIComponent(W.secure_token)}`:"");c.innerHTML=`<div class="caf-form-icon" style="margin-left:auto;margin-right:auto">\u2713</div><div class="caf-form-t">Ticket created</div><p class="caf-form-d">Keep this reference for future updates.</p><div class="caf-ticket-ref">${y(W.reference)}</div>${Ve?`<a class="caf-ticket-view" href="${y(Ve)}" target="_blank" rel="noopener noreferrer">View ticket status</a>`:""}<button class="caf-fbtn" type="button">Return to conversation</button>`,c.querySelector("button").onclick=()=>{c.remove(),a.panel.classList.remove("caf-ticketing")}}catch(L){H.textContent=L.message||"Could not create ticket. Please try again.",V.disabled=!1,V.querySelector("span").textContent="Submit ticket"}}}catch(g){c.querySelector(".caf-ferr").textContent="Ticket forms are unavailable right now.",t.debug&&console.error("[caf] ticket form failed",g),setTimeout(()=>{c.remove(),a.panel.classList.remove("caf-ticketing")},2500)}}async function ut(r,c){if(!t.apiUrl)return;if(await de(),!u)throw new Error("Support connection is not ready");if(!(await fetch(t.apiUrl.replace(/\/$/,"")+"/sdk/customers/me",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u},body:JSON.stringify({name:r||void 0,email:c||void 0})})).ok)throw new Error("Could not save contact details")}function gt(){Ee=!0,a.panel.classList.add("caf-prechat");let r=document.createElement("form");r.className="caf-form",r.noValidate=!0,r.innerHTML=`
250
250
  <div class="caf-form-icon" aria-hidden="true">
251
251
  <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>
252
252
  </div>
@@ -261,4 +261,4 @@ var xt=Object.create;var Ne=Object.defineProperty;var kt=Object.getOwnPropertyDe
261
261
  <div class="caf-ferr" id="caf-contact-error" data-caf="f-err" role="alert" aria-live="polite"></div>
262
262
  <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>
263
263
  ${t.requireEmail?"":'<button class="caf-fskip" data-caf="f-skip" type="button">Continue without details</button>'}
264
- <p class="caf-form-privacy">Your details are only used to support this conversation.</p>`,n.msgs.appendChild(s),n.msgs.scrollTop=0;let c=w=>s.querySelector(`[data-caf="${w}"]`),h=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,g=async w=>{let x=c("f-name").value.trim(),m=c("f-email").value.trim(),C=c("f-email");if(c("f-err").textContent="",C.setAttribute("aria-invalid","false"),w){if(t.requireEmail&&!m){c("f-err").textContent="Email is required.",C.setAttribute("aria-invalid","true"),C.focus();return}if(m&&!h.test(m)){c("f-err").textContent="Enter a valid email.",C.setAttribute("aria-invalid","true"),C.focus();return}let O=c("f-go");O.disabled=!0,O.querySelector("span").textContent="Starting\u2026";try{await ut(x,m)}catch(T){c("f-err").textContent="We couldn\u2019t start the conversation. Check your connection and try again.",O.disabled=!1,O.querySelector("span").textContent="Start conversation",t.debug&&console.error("[caf] saveContact failed",T);return}}s.remove(),n.panel.classList.remove("caf-prechat"),F=!0,b(),se(!0),Oe(),setTimeout(()=>n.input.focus(),30)};s.onsubmit=w=>{w.preventDefault(),g(!0)};let p=c("f-skip");p&&(p.onclick=()=>g(!1)),setTimeout(()=>c("f-name").focus(),40)}function oe(){if(ae=!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"),Re(0),de().catch(()=>{}),!F&&!Ee){gt();return}F&&(Oe(),setTimeout(()=>n.input.focus(),50))}function ce(){ae=!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=()=>ae?ce():oe(),a("close").onclick=ce;let j=null,le=null,Y=null;function Le(){Y&&(URL.revokeObjectURL(Y),Y=null),le=null,n.pending.classList.remove("show"),n.pendingThumb.innerHTML="",n.pendingName.textContent=""}function mt(s){le=s,n.pendingName.textContent=s.name,s.type&&s.type.startsWith("image/")?(Y=URL.createObjectURL(s),n.pendingThumb.innerHTML=`<img src="${Y}" alt="" />`):n.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>',n.pending.classList.add("show"),setTimeout(()=>n.input.focus(),30)}async function me(){if(!F)return;let s=n.input.value.trim();if(le){let c=le;Le(),n.input.value="",n.input.style.height="auto",wt(c,s);return}if(!(!s||!j))try{n.send.disabled=!0,await Promise.resolve(j.sendMessage(s)),n.input.value="",n.input.style.height="auto"}catch(c){r("Your message wasn\u2019t sent. Please try again."),t.debug&&console.error("[caf] send failed",c)}finally{n.send.disabled=!1}}function qe(s,c){n.upload.classList.add("show"),n.uploadBar.style.width=c+"%",n.uploadLabel.textContent=`Sending ${s}\u2026 ${c}%`}function bt(){n.upload.classList.remove("show")}async function wt(s,c){if(!(!F||!j)){se(!1),qe(s.name,0);try{await j.sendMedia(s,{caption:c||void 0,onProgress:h=>qe(s.name,h)})}catch(h){t.debug&&console.error("[caf] sendMedia failed",h),ne("caf-note","Couldn\u2019t send that file. Please try again.")}finally{bt(),se(F)}}}n.attach.onclick=()=>n.file.click(),!t.tickets||!t.publicKey?n.ticket.style.display="none":n.ticket.onclick=ft,n.human.onclick=async()=>{if(!(!F||!j||n.human.disabled))try{n.human.disabled=!0,await Promise.resolve(j.sendMessage("I'd like to talk to a human agent.")),n.human.disabled=!0,n.human.textContent="Human requested",r("A human support agent has been requested.","success")}catch(s){n.human.disabled=!1,r("We couldn\u2019t request a human agent. Please try again."),t.debug&&console.error("[caf] human handoff request failed",s)}},n.file.addEventListener("change",()=>{let s=n.file.files&&n.file.files[0];n.file.value="",s&&mt(s)}),n.pendingRemove.onclick=()=>Le(),n.send.onclick=me,se(F),n.input.addEventListener("input",()=>{n.input.style.height="auto",n.input.style.height=Math.min(n.input.scrollHeight,96)+"px"}),n.input.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),me())});let be=t.publicKey?"caf_session_"+t.publicKey.slice(-10):"",vt=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";function De(){if(!be)return null;try{let s=JSON.parse(localStorage.getItem(be)||"null");if(s&&s.token&&s.conversationId&&s.exp>Date.now())return s}catch{}return null}async function yt(){let s=t.apiUrl.replace(/\/$/,""),c=be,h=vt,g=De();if(g)return f=!!g.calls_enabled,{token:g.token,conversationId:g.conversationId};let p=null;try{p=localStorage.getItem(h)}catch{}if(!p){p="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(h,p)}catch{}}let w=await fetch(s+"/sdk/anonymous-session",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({visitor_id:p})});if(!w.ok)throw new Error("anonymous-session HTTP "+w.status);let x=await w.json(),m=x.data||x;f=!!m.calls_enabled;let C=Date.now()+Math.max(0,(m.expires_in||3600)*1e3-6e4);try{localStorage.setItem(c,JSON.stringify({token:m.token,conversationId:m.conversation_id,exp:C,calls_enabled:f}))}catch{}return{token:m.token,conversationId:m.conversation_id}}let Q=null;function de(){return Q||(Q=(async()=>{var s,c,h,g;try{if(J(""),t.publicKey){let p=await yt();u=p.token,_=p.conversationId,P=tt(u)}if(S=new et({wsUrl:t.wsUrl,token:u,apiUrl:t.apiUrl,appId:u?(s=at(u))==null?void 0:s.app_id:void 0,autoReconnect:!0,debug:t.debug}),S.on("connected",()=>{J("on"),l()}),S.on("disconnected",()=>{J(""),$e()}),S.on("reconnecting",()=>J("")),S.on("error",()=>{J("err"),r("Connection interrupted. We\u2019re trying to reconnect.","error",0)}),await S.connect(),await S.conversations.join(_),j=S.conversations.get(_),j.on("message",Ue),j.on("typing",rt),t.apiUrl&&typeof j.fetchMessages=="function")try{let p=await j.fetchMessages({limit:30});((g=(h=p==null?void 0:p.messages)!=null?h:(c=p==null?void 0:p.data)==null?void 0:c.messages)!=null?g:[]).forEach(Ue)}catch{}_e=!0,v()&&k()}catch(p){throw J("err"),Q=null,r("We couldn\u2019t connect to support. Please check your connection and try again.","error",0),t.debug&&console.error("[caf] connect/provision failed",p),p}})(),Q)}(!t.publicKey||De())&&de().catch(()=>{}),t.autoOpen&&oe();let Pe={open:oe,close:ce,send:async s=>{await de(),n.input.value=s,await me()},destroy:()=>{try{S==null||S.disconnect()}catch{}i.remove(),I=null}};return I={open:oe,close:ce,api:Pe},Pe}function Fi(){I==null||I.open()}function Vi(){I==null||I.close()}function Ni(){I==null||I.api.destroy()}export{Vi as close,Ni as destroy,Pi as init,Fi as open};
264
+ <p class="caf-form-privacy">Your details are only used to support this conversation.</p>`,a.msgs.appendChild(r),a.msgs.scrollTop=0;let c=w=>r.querySelector(`[data-caf="${w}"]`),h=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,g=async w=>{let x=c("f-name").value.trim(),m=c("f-email").value.trim(),C=c("f-email");if(c("f-err").textContent="",C.setAttribute("aria-invalid","false"),w){if(t.requireEmail&&!m){c("f-err").textContent="Email is required.",C.setAttribute("aria-invalid","true"),C.focus();return}if(m&&!h.test(m)){c("f-err").textContent="Enter a valid email.",C.setAttribute("aria-invalid","true"),C.focus();return}let O=c("f-go");O.disabled=!0,O.querySelector("span").textContent="Starting\u2026";try{await ut(x,m)}catch(T){c("f-err").textContent="We couldn\u2019t start the conversation. Check your connection and try again.",O.disabled=!1,O.querySelector("span").textContent="Start conversation",t.debug&&console.error("[caf] saveContact failed",T);return}}r.remove(),a.panel.classList.remove("caf-prechat"),F=!0,b(),re(!0),Oe(),setTimeout(()=>a.input.focus(),30)};r.onsubmit=w=>{w.preventDefault(),g(!0)};let p=c("f-skip");p&&(p.onclick=()=>g(!1)),setTimeout(()=>c("f-name").focus(),40)}function oe(){if(ne=!0,a.panel.classList.add("open"),a.panel.setAttribute("aria-hidden","false"),a.launcher.setAttribute("aria-expanded","true"),a.launcher.setAttribute("aria-label","Close support chat"),Re(0),de().catch(()=>{}),!F&&!Ee){gt();return}F&&(Oe(),setTimeout(()=>a.input.focus(),50))}function ce(){ne=!1,a.panel.classList.remove("open"),a.panel.setAttribute("aria-hidden","true"),a.launcher.setAttribute("aria-expanded","false"),a.launcher.setAttribute("aria-label","Open support chat"),a.launcher.focus()}a.launcher.onclick=()=>ne?ce():oe(),n("close").onclick=ce;let j=null,le=null,Y=null;function Le(){Y&&(URL.revokeObjectURL(Y),Y=null),le=null,a.pending.classList.remove("show"),a.pendingThumb.innerHTML="",a.pendingName.textContent=""}function mt(r){le=r,a.pendingName.textContent=r.name,r.type&&r.type.startsWith("image/")?(Y=URL.createObjectURL(r),a.pendingThumb.innerHTML=`<img src="${Y}" alt="" />`):a.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>',a.pending.classList.add("show"),setTimeout(()=>a.input.focus(),30)}async function me(){if(!F)return;let r=a.input.value.trim();if(le){let c=le;Le(),a.input.value="",a.input.style.height="auto",wt(c,r);return}if(!(!r||!j))try{a.send.disabled=!0,await Promise.resolve(j.sendMessage(r)),a.input.value="",a.input.style.height="auto"}catch(c){s("Your message wasn\u2019t sent. Please try again."),t.debug&&console.error("[caf] send failed",c)}finally{a.send.disabled=!1}}function qe(r,c){a.upload.classList.add("show"),a.uploadBar.style.width=c+"%",a.uploadLabel.textContent=`Sending ${r}\u2026 ${c}%`}function bt(){a.upload.classList.remove("show")}async function wt(r,c){if(!(!F||!j)){re(!1),qe(r.name,0);try{await j.sendMedia(r,{caption:c||void 0,onProgress:h=>qe(r.name,h)})}catch(h){t.debug&&console.error("[caf] sendMedia failed",h),ae("caf-note","Couldn\u2019t send that file. Please try again.")}finally{bt(),re(F)}}}a.attach.onclick=()=>a.file.click(),!t.tickets||!t.publicKey?a.ticket.style.display="none":a.ticket.onclick=ft,a.human.onclick=async()=>{if(!(!F||!j||a.human.disabled))try{a.human.disabled=!0,await Promise.resolve(j.sendMessage("I'd like to talk to a human agent.")),a.human.disabled=!0,a.human.textContent="Human requested",s("A human support agent has been requested.","success")}catch(r){a.human.disabled=!1,s("We couldn\u2019t request a human agent. Please try again."),t.debug&&console.error("[caf] human handoff request failed",r)}},a.file.addEventListener("change",()=>{let r=a.file.files&&a.file.files[0];a.file.value="",r&&mt(r)}),a.pendingRemove.onclick=()=>Le(),a.send.onclick=me,re(F),a.input.addEventListener("input",()=>{a.input.style.height="auto",a.input.style.height=Math.min(a.input.scrollHeight,96)+"px"}),a.input.addEventListener("keydown",r=>{r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),me())});let be=t.publicKey?"caf_session_"+t.publicKey.slice(-10):"",vt=t.publicKey?"caf_vid_"+t.publicKey.slice(-10):"";function Pe(){if(!be)return null;try{let r=JSON.parse(localStorage.getItem(be)||"null");if(r&&r.token&&r.conversationId&&r.exp>Date.now())return r}catch{}return null}async function yt(){let r=t.apiUrl.replace(/\/$/,""),c=be,h=vt,g=Pe();if(g)return f=!!g.calls_enabled,{token:g.token,conversationId:g.conversationId};let p=null;try{p=localStorage.getItem(h)}catch{}if(!p){p="v_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{localStorage.setItem(h,p)}catch{}}let w=await fetch(r+"/sdk/anonymous-session",{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":t.publicKey},body:JSON.stringify({visitor_id:p})});if(!w.ok)throw new Error("anonymous-session HTTP "+w.status);let x=await w.json(),m=x.data||x;f=!!m.calls_enabled;let C=Date.now()+Math.max(0,(m.expires_in||3600)*1e3-6e4);try{localStorage.setItem(c,JSON.stringify({token:m.token,conversationId:m.conversation_id,exp:C,calls_enabled:f}))}catch{}return{token:m.token,conversationId:m.conversation_id}}let Q=null;function de(){return Q||(Q=(async()=>{var r,c,h,g;try{if(J(""),t.publicKey){let p=await yt();u=p.token,_=p.conversationId,D=tt(u)}if(S=new et({wsUrl:t.wsUrl,token:u,apiUrl:t.apiUrl,appId:u?(r=nt(u))==null?void 0:r.app_id:void 0,autoReconnect:!0,debug:t.debug}),S.on("connected",()=>{J("on"),l()}),S.on("disconnected",()=>{J(""),$e()}),S.on("reconnecting",()=>J("")),S.on("error",()=>{J("err"),s("Connection interrupted. We\u2019re trying to reconnect.","error",0)}),await S.connect(),await S.conversations.join(_),j=S.conversations.get(_),j.on("message",Ie),j.on("typing",st),t.apiUrl&&typeof j.fetchMessages=="function")try{let p=await j.fetchMessages({limit:30});((g=(h=p==null?void 0:p.messages)!=null?h:(c=p==null?void 0:p.data)==null?void 0:c.messages)!=null?g:[]).forEach(Ie)}catch{}_e=!0,v()&&k()}catch(p){throw J("err"),Q=null,s("We couldn\u2019t connect to support. Please check your connection and try again.","error",0),t.debug&&console.error("[caf] connect/provision failed",p),p}})(),Q)}(!t.publicKey||Pe())&&de().catch(()=>{}),t.autoOpen&&oe();let De={open:oe,close:ce,send:async r=>{await de(),a.input.value=r,await me()},destroy:()=>{try{S==null||S.disconnect()}catch{}i.remove(),U=null}};return U={open:oe,close:ce,api:De},De}function Fi(){U==null||U.open()}function Vi(){U==null||U.close()}function Ni(){U==null||U.api.destroy()}export{Vi as close,Ni as destroy,Di as init,Fi as open};