captivate-chat-api
Version:
This is a wrapper for captivate chat api socket custom channel
1 lines • 25.3 kB
JavaScript
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this,(()=>(()=>{"use strict";var e={86:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CaptivateChatAPI=t.captivateLogger=void 0;const s=n(52);let o;if("undefined"!=typeof window&&window.WebSocket)o=window.WebSocket;else if(void 0!==n.g&&n.g.WebSocket)o=n.g.WebSocket;else try{o=n(591)}catch(e){throw new Error("WebSocket not available in this environment and ws module could not be loaded")}function r(e){return new Proxy(e,{get(e,t,n){const s=e[t];return"function"!=typeof s||["isSocketActive","connect","reconnect","getSocket","getConversationId"].includes(t)?s:function(...n){return i(this,void 0,void 0,(function*(){if("function"==typeof e.isSocketActive&&!e.isSocketActive())try{if("function"!=typeof e.reconnect)throw new Error("Reconnect method not available");yield e.reconnect()}catch(e){throw new Error(`Socket reconnection failed. Cannot execute ${String(t)}: ${e.message}`)}return s.apply(e,n)}))}}})}let a=!1;const c={log:console.log,warn:console.warn,error:console.error};t.captivateLogger={log:(...e)=>{a&&c.log("[CaptivateChatAPI]",...e)},warn:(...e)=>{c.warn("[CaptivateChatAPI]",...e)},error:(...e)=>{c.error("[CaptivateChatAPI]",...e)}};class l{static getInstanceKey(e,t){return`${e}-${t}`}static setDebugMode(e){a=e}static getDebugMode(){return a}constructor(e,n="prod"){this.socketId=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectDelay=3e3;const i=l.getInstanceKey(e,n),s=l.instances.get(i);if(s)return t.captivateLogger.log(`Reusing existing CaptivateChatAPI instance for ${i}`),s;this.apiKey=e,this.mode=n,this.url="prod"===this.mode?`wss://channel.wss.captivatechat.ai/dev?apiKey=${e}`:`wss://channel-dev.wss.captivatechat.ai/dev?apiKey=${e}`,this.socket=null,this.conversations=new Map,l.instances.set(i,this),t.captivateLogger.log(`Created new CaptivateChatAPI instance for ${i}`),t.captivateLogger.log("CaptivateChatAPI: Using HTTP for sending messages and WebSocket for receiving real-time updates.")}_send(e){return i(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("API key is required for HTTP communication");const n=("prod"===this.mode?"https://channel.prod.captivat.io":"https://channel.dev.captivat.io")+"/api/custom-channel/sockets/message",i=Object.assign(Object.assign({},e),{event:Object.assign(Object.assign({},e.event),{socket_id:this.socketId})});try{const e=yield fetch(n,{method:"POST",headers:{"x-api-key":this.apiKey,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)});if(!e.ok)throw new Error(`HTTP request failed: ${e.status} ${e.statusText}`);const s=e.headers.get("content-type");let o;if(s&&s.includes("application/json"))o=yield e.json();else{const n=yield e.text();t.captivateLogger.log("Server returned plain text:",n),o={status:"success",message:n,event:{event_payload:{conversation_id:null}}}}return t.captivateLogger.log("Message received from server via HTTP:",o),o}catch(e){throw console.error("HTTP request failed:",e),new Error(`Failed to send message via HTTP: ${e instanceof Error?e.message:"Unknown error"}`)}}))}connect(){return i(this,void 0,void 0,(function*(){return new Promise(((e,n)=>{try{this.socket=new o(this.url);const i=setTimeout((()=>{n(new Error("Connection timeout: socket_connected not received"))}),1e4);this.socket.onopen=()=>{},this.socket.onmessage=n=>{var s,o;try{const r=JSON.parse(n.data.toString());"socket_connected"===(null===(s=r.event)||void 0===s?void 0:s.event_type)&&(this.socketId=(null===(o=r.event.event_payload)||void 0===o?void 0:o.socket_id)||null,t.captivateLogger.log("Socket connected with ID:",this.socketId),clearTimeout(i),e())}catch(e){console.error("Error parsing message:",e)}},this.socket.onerror=e=>{console.error("WebSocket Error:",e.message||e),clearTimeout(i),n(new Error(e.message||"WebSocket error"))},this.socket.onclose=e=>{1e3!==e.code&&setTimeout((()=>this.connect()),3e3)}}catch(e){n(e)}}))}))}createConversation(e){return i(this,arguments,void 0,(function*(e,n={},o={},a="bot-first",c={}){return new Promise(((l,d)=>i(this,void 0,void 0,(function*(){var i;try{const h=Object.assign({},o);c&&(h.private=c);const v=e=>{var n,i,o,c;try{t.captivateLogger.log("messagereceived:",e.data.toString());const h=JSON.parse(e.data.toString());if("conversation_start_success"===(null===(n=h.event)||void 0===n?void 0:n.event_type)){const e=null===(i=h.event.event_payload)||void 0===i?void 0:i.conversation_id;if(!e)return null===(o=this.socket)||void 0===o||o.removeEventListener("message",v),void d(new Error("No conversation_id received in WebSocket response"));null===(c=this.socket)||void 0===c||c.removeEventListener("message",v);const t=r(new s.Conversation(e,this.socket,{},this.apiKey,this.mode,this.socketId));this.conversations.set(e,t),"bot-first"===a?t.sendMessage({type:"text",text:""}).then((()=>l(t))).catch(d):l(t)}}catch(e){console.error("Error processing message:",e)}};null===(i=this.socket)||void 0===i||i.addEventListener("message",v),setTimeout((()=>{var e;null===(e=this.socket)||void 0===e||e.removeEventListener("message",v),d(new Error("Timeout: No conversation_start_success received from WebSocket"))}),1e4),yield this._send({action:"sendMessage",event:{event_type:"conversation_start",event_payload:{userId:e,userBasicInfo:n,metadata:h}}})}catch(e){d(e)}}))))}))}getConversation(e){let t=this.conversations.get(e);if(!t){if(null===this.socket)throw console.error("Socket is not initialized"),new Error("WebSocket connection not established");t=r(new s.Conversation(e,this.socket,{},this.apiKey,this.mode,this.socketId)),this.conversations.set(e,t)}return null==t||t.restartListeners(),t}getUserConversations(e){return i(this,void 0,void 0,(function*(){var t;const n="string"==typeof e?{userId:e}:e,{userId:i,filter:o={},search:a={},pagination:c={},apiKeys:l}=n,d=[];let h;const v=o&&Object.keys(o).length>0||a&&Object.keys(a).length>0||c&&Object.keys(c).length>0||l&&Array.isArray(l)&&l.length>0;try{let e;if(v){const t={userId:i};o&&Object.keys(o).length>0&&(t.filter=o),a&&Object.keys(a).length>0&&(t.search=a),c&&Object.keys(c).length>0&&(t.pagination=c),l&&Array.isArray(l)&&l.length>0&&(t.apiKeys=l),e=yield this._send({action:"sendMessage",event:{event_type:"get_user_conversations_v2",event_payload:t}})}else e=yield this._send({action:"sendMessage",event:{event_type:"get_user_conversations",event_payload:{userId:i}}});const n=(null===(t=null==e?void 0:e.event)||void 0===t?void 0:t.event_payload)||e,p=(null==n?void 0:n.conversations)||[],u=null==n?void 0:n.pagination;for(const e of p){const{conversation_id:t,metadata:n,apiKey:i}=e;null!==this.socket&&d.push(r(new s.Conversation(t,this.socket,n,i||this.apiKey,this.mode,this.socketId)))}return u&&(h=u),{conversations:d,pagination:h}}catch(e){throw e}}))}deleteUserConversations(e){return i(this,arguments,void 0,(function*(e,n={}){if(!e)throw new Error("User ID must be provided.");const{softDelete:i=!0}=n,s={action:"sendMessage",event:{event_type:"delete_user_conversations",event_payload:{userId:e,softdelete:i}}},o=yield this._send(s);t.captivateLogger.log(`User conversations ${i?"soft":"hard"} delete confirmed via HTTP response:`,o)}))}getSocket(){return this.socket}getSocketId(){return this.socketId}isSocketActive(){return!!this.socket&&this.socket.readyState===o.OPEN}reconnect(){return i(this,void 0,void 0,(function*(){if(this.reconnectAttempts>=this.maxReconnectAttempts)throw new Error(`Max reconnection attempts (${this.maxReconnectAttempts}) reached`);this.reconnectAttempts++;try{yield this.connect(),this.reconnectAttempts=0}catch(e){if(console.error(`Reconnection attempt ${this.reconnectAttempts} failed:`,e),this.reconnectAttempts<this.maxReconnectAttempts)return yield new Promise((e=>setTimeout(e,this.reconnectDelay))),this.reconnect();throw e}}))}static create(e){return i(this,arguments,void 0,(function*(e,t="prod"){const n=new l(e,t);return n.isSocketActive()||(yield n.connect()),r(n)}))}static getInstance(e,t="prod"){return this.instances.get(this.getInstanceKey(e,t))}static hasInstance(e,t="prod"){return this.instances.has(this.getInstanceKey(e,t))}dispose(){const e=l.getInstanceKey(this.apiKey,this.mode);this.socket&&(this.socket.close(1e3,"Instance disposed"),this.socket=null),this.conversations.clear(),l.instances.delete(e),t.captivateLogger.log(`Disposed CaptivateChatAPI instance for ${e}`)}}t.CaptivateChatAPI=l,l.instances=new Map},67:function(e,t){var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CaptivateChatFileManager=void 0;const i=[1,7,30,90];class s{constructor(e,t,n){this.type="files",this.files=[{filename:t.metadata.originalFileName,type:n,file:e,textContent:t}]}static create(e){return n(this,void 0,void 0,(function*(){const t=e.file,n=void 0===e.storage||e.storage;if(!1===n&&!e.url)throw new Error("URL is required when storage is false for sendMessage compatibility");const i=e.fileName||(t instanceof File?t.name:`attachment_${Date.now()}`),o=e.fileType||(t instanceof File?t.type:t.type||"application/octet-stream"),r=yield s.convertFileToText(t,i,!0,n,e.apiKey,e.conversationId,e.ttlDays),a=new s(t,{type:"file_content",text:r.text,metadata:{source:"file_attachment",originalFileName:i,storageType:"direct"}},o);return n&&r.storageInfo&&(a.files[0].storage=r.storageInfo),!1===n&&e.url&&(a.files[0].url=e.url),s.createProxy(a)}))}getFirstFile(){return this.files[0]}getFilename(){var e;return null===(e=this.files[0])||void 0===e?void 0:e.filename}getTextContent(){var e,t;return(null===(t=null===(e=this.files[0])||void 0===e?void 0:e.textContent)||void 0===t?void 0:t.text)||""}getFileType(){var e;return null===(e=this.files[0])||void 0===e?void 0:e.type}toFilesArray(){return this.files}*[Symbol.iterator](){yield*this.files}get[Symbol.toStringTag](){return"Array"}get length(){return this.files.length}refreshSecureUrl(){return n(this,arguments,void 0,(function*(e=7200){var t;const n=this.files[0];if(n&&(null===(t=n.storage)||void 0===t?void 0:t.fileKey))return yield s.getSecureFileUrl(n.storage.fileKey,e)}))}static createProxy(e){return new Proxy(e,{get:(e,t)=>t===Symbol.iterator||"length"===t||"number"==typeof t?e.files[t]:e[t]})}static createFile(e){return n(this,void 0,void 0,(function*(){return(yield s.create({file:e.file,fileName:e.fileName,fileType:e.fileType,storage:e.storage,url:e.url,apiKey:e.apiKey,conversationId:e.conversationId,ttlDays:e.ttlDays})).getFirstFile()}))}static createMultiple(e){return n(this,void 0,void 0,(function*(){const t=void 0===e.storage||e.storage;if(!1===t&&(!e.urls||e.urls.length!==e.files.length))throw new Error("URLs array is required when storage is false and must match the number of files");const n=e.files,i=(yield Promise.all(n.map(((n,i)=>s.create({file:n,storage:t,url:!1===t?e.urls[i]:void 0,apiKey:e.apiKey,conversationId:e.conversationId,ttlDays:e.ttlDays}))))).flatMap((e=>e.files)),o=new s(n[0],{type:"file_content",text:"",metadata:{source:"file_attachment",originalFileName:"multiple_files",storageType:"direct"}},"application/octet-stream");return o.files=i,s.createProxy(o)}))}static getSecureFileUrl(e){return n(this,arguments,void 0,(function*(e,t=7200){const n=s.PRESIGNED_URL_API_URL;try{const i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileKey:e,expiresIn:t})});if(!i.ok){const e=yield i.json().catch((()=>({})));throw new Error(`Secure URL generation failed: ${i.status} ${i.statusText}. ${e.error||""}`)}const s=yield i.json();if(!s.success)throw new Error(`Secure URL generation failed: ${s.error||"Unknown error"}`);return s.presignedUrl||""}catch(e){if(e.message.includes("Secure URL generation failed"))throw e;throw new Error(`Failed to generate secure URL: ${e.message}`)}}))}static convertFileToText(e,t,o,r,a,c,l){return n(this,void 0,void 0,(function*(){const n=s.FILE_TO_TEXT_API_URL,d=new FormData;if(d.append("file",e,t),d.append("includeMetadata",o.toString()),d.append("storage",r.toString()),a&&c){const e=`${a}/${c}`;d.append("path",e)}void 0!==l&&i.includes(l)&&d.append("ttlDays",String(l));try{const e=yield fetch(n,{method:"POST",body:d});if(!e.ok){const t=yield e.json().catch((()=>({})));throw new Error(`File conversion failed: ${e.status} ${e.statusText}. ${t.error||""}`)}const t=yield e.json();if(!t.success)throw new Error(`File conversion failed: ${t.error||"Unknown error"}`);return{text:t.text||"",storageInfo:r?{fileKey:t.fileKey,presignedUrl:t.presignedUrl,expiresIn:t.expiresIn,fileSize:t.fileSize,processingTime:t.processingTime}:void 0}}catch(e){if(e.message.includes("File conversion failed"))throw e;throw new Error(`Failed to convert file to text: ${e.message}`)}}))}}t.CaptivateChatFileManager=s,s.FILE_TO_TEXT_API_URL="https://file-to-text.prod.captivat.io/api/file-to-text",s.PRESIGNED_URL_API_URL="https://file-to-text.prod.captivat.io/api/presigned-url"},629:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))},s=this&&this.__rest||function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n};Object.defineProperty(t,"__esModule",{value:!0}),t.CaptivateChatManager=void 0;const o=n(86),r=n(52);class a{constructor(e,t="prod"){this.apiInstances={};const n=[...new Set(e)];for(const e of n)this.apiInstances[e]=new o.CaptivateChatAPI(e,t)}static create(e){return i(this,arguments,void 0,(function*(e,t="prod"){const n=[...new Set(e)],i=Object.create(a.prototype);i.apiInstances={};for(const e of n)i.apiInstances[e]=yield o.CaptivateChatAPI.create(e,t);return i}))}connectAll(){return i(this,void 0,void 0,(function*(){yield Promise.all(Object.values(this.apiInstances).map((e=>e.connect())))}))}getUserConversations(e){return i(this,void 0,void 0,(function*(){const t=e.apiKeys||Object.keys(this.apiInstances),n=this.apiInstances[t[0]],{apiKeys:i}=e,o=s(e,["apiKeys"]),a=yield n.getUserConversations(Object.assign(Object.assign({},o),{apiKeys:t}));return{conversations:a.conversations.map((e=>{const t=e.apiKey,n=this.apiInstances[t];if(!n)throw new Error(`No CaptivateChatAPI instance for apiKey: ${t}`);if(!n.getSocket())throw new Error(`WebSocket not initialized for apiKey: ${t}`);return new r.Conversation(e.conversationId,n.getSocket(),e.metadata,t)})),pagination:a.pagination}}))}getApiInstance(e){return this.apiInstances[e]}dispose(e){const t=this.apiInstances[e];t&&(t.dispose(),delete this.apiInstances[e])}disposeAll(){for(const e of Object.values(this.apiInstances))e.dispose();this.apiInstances={}}}t.CaptivateChatManager=a},52:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Conversation=void 0;const s=n(67),o=n(86),r=[1,7,30,90];t.Conversation=class{constructor(e,t,n,o,r,a){this.socketId=null,this.apiKey=o||"",this.conversationId=e,this.socket=t,this.metadata=n||{},this.listeners=new Map,this.mode=r||"prod",this.socketId=a||null,this.defaultTtlDays=void 0,this.socket&&(this.socket.onmessage=this.handleMessage.bind(this)),this.apiKey||console.warn("API key is required for HTTP communication. Some features may not work properly."),this.fileManager={create:e=>i(this,void 0,void 0,(function*(){return s.CaptivateChatFileManager.create({file:e.file,fileName:e.fileName,fileType:e.fileType,storage:e.storage,url:e.url,apiKey:this.apiKey,conversationId:this.conversationId,ttlDays:this.defaultTtlDays})})),createFile:e=>i(this,void 0,void 0,(function*(){return s.CaptivateChatFileManager.createFile({file:e.file,fileName:e.fileName,fileType:e.fileType,storage:e.storage,url:e.url,apiKey:this.apiKey,conversationId:this.conversationId,ttlDays:this.defaultTtlDays})})),createMultiple:e=>i(this,void 0,void 0,(function*(){return s.CaptivateChatFileManager.createMultiple({files:e.files,storage:e.storage,urls:e.urls,apiKey:this.apiKey,conversationId:this.conversationId,ttlDays:this.defaultTtlDays})}))}}setTimeToLive(e){return i(this,void 0,void 0,(function*(){const t=e;r.includes(t)&&(this.defaultTtlDays=t,yield this.setMetadata({timeToLive:e}))}))}handleMessage(e){var t,n;const i=JSON.parse(e.data),s=null===(t=i.event)||void 0===t?void 0:t.event_type;if(s&&this.listeners.has(s)){const e=i.event.event_payload;null===(n=this.listeners.get(s))||void 0===n||n.forEach((t=>t(e)))}}restartListeners(){this.socket.onmessage=this.handleMessage.bind(this)}addListener(e,t){var n;this.restartListeners(),this.listeners.has(e)||this.listeners.set(e,[]),null===(n=this.listeners.get(e))||void 0===n||n.push(t)}onMessage(e){this.addListener("bot_message",(t=>e(t.content,"ai_agent"))),this.addListener("livechat_message",(t=>e(t.content,"human_agent"))),this.addListener("general_error",(t=>i(this,void 0,void 0,(function*(){if(413===t.error_code&&t.message_link)try{const n=yield fetch(t.message_link,{method:"GET",headers:{"x-api-key":this.apiKey,Accept:"application/json"}});if(!n.ok)throw new Error(`Failed to fetch large message: ${n.status} ${n.statusText}`);const i=yield n.json();e(i.botMessage.content,"ai_agent")}catch(t){console.error("Error fetching large message:",t),e(`[Error fetching large message: ${t.message}]`,"error")}else e(`[Error: ${t.error_desc||"Unknown error"}]`,"error")}))))}onActionReceived(e){this.addListener("action",(t=>e(t.actions)))}onConversationUpdate(e){this.addListener("conversation_update",(t=>{e({type:t.type,conversationId:t.conversation_id,data:t.data})}))}onError(e){this.addListener("general_error",(t=>{e({conversationId:t.conversation_id,errorCode:t.error_code,errorDesc:t.error_desc})}))}sendMessage(e){return i(this,void 0,void 0,(function*(){return"string"==typeof e&&(e={type:"text",text:e}),this.sendPayload("user_message",{type:"message_create",client_msg_id:`unique-message-id-${Date.now()}`,conversation_id:this.conversationId,content:e})}))}setMetadata(e){return i(this,void 0,void 0,(function*(){if("object"!=typeof e||null===e)throw new Error("Metadata must be a non-null object.");const t={action:"sendMessage",event:{event_type:"metadata",event_payload:{metadata:e,client_msg_id:`metadata-${Date.now()}`,conversation_id:this.conversationId}}},n=yield this.sendPayloadViaHttp(t);o.captivateLogger.log("Metadata update confirmed via HTTP response:",n)}))}setPrivateMetadata(e){return i(this,void 0,void 0,(function*(){if("object"!=typeof e||null===e)throw new Error("Private metadata must be a non-null object.");return this.setMetadata({private:e})}))}sendAction(e){return i(this,arguments,void 0,(function*(e,t={}){const n=yield this.sendPayload("action",{type:"normal",id:e,data:t,conversation_id:this.conversationId});o.captivateLogger.log("Action sent confirmed via HTTP response:",n)}))}getTranscript(){return i(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("API key is required to fetch transcript via REST.");const e=`${this.getBaseUrl()}/api/transcript?conversation_id=${encodeURIComponent(this.conversationId)}`,t=yield fetch(e,{method:"GET",headers:{"x-api-key":this.apiKey,Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch transcript: ${t.status} ${t.statusText}`);const n=yield t.json();return yield this.refreshExpiredFileUrls(n.transcript)}))}refreshExpiredFileUrls(e){return i(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3);return yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){if(!e.files||0===e.files.length)return e;const n=yield Promise.all(e.files.map((e=>i(this,void 0,void 0,(function*(){if(!e.storage||!e.storage.fileKey)return e;try{if(e.storage.expiresIn-t<300){const n=yield s.CaptivateChatFileManager.getSecureFileUrl(e.storage.fileKey,7200);return Object.assign(Object.assign({},e),{storage:Object.assign(Object.assign({},e.storage),{presignedUrl:n,expiresIn:t+7200})})}return e}catch(t){return console.error(`Failed to refresh file ${e.filename}:`,t),e}})))));if(n.some(((t,n)=>t!==e.files[n])))try{const t=e.message_id||e.id;if(t){const i=e.content?Object.assign(Object.assign({},e.content),{files:n}):{text:e.text||"",files:n};yield this.editMessage(String(t),i)}}catch(e){console.error("Failed to push refreshed URLs via editMessage:",e)}return Object.assign(Object.assign({},e),{files:n})})))))}))}getMetadata(){return i(this,void 0,void 0,(function*(){const e={action:"sendMessage",event:{event_type:"metadata_request",event_payload:{conversation_id:this.conversationId}}},t=yield this.sendPayloadViaHttp(e);return o.captivateLogger.log("Metadata retrieved via HTTP response:",t),t.metadata||t}))}delete(){return i(this,arguments,void 0,(function*(e={}){const{softDelete:t=!0}=e,n={action:"sendMessage",event:{event_type:"delete_conversation",event_payload:{conversation_id:this.conversationId,softdelete:t}}},i=yield this.sendPayloadViaHttp(n);o.captivateLogger.log(`Conversation ${t?"soft":"hard"} delete confirmed via HTTP response:`,i)}))}editMessage(e,t){return i(this,void 0,void 0,(function*(){"string"==typeof t&&(t={type:"text",text:t});const n={action:"sendMessage",event:{event_type:"edit_message",event_payload:{type:"message_create",client_msg_id:`edit-message-id-${Date.now()}`,conversation_id:this.conversationId,message_id:e,content:t}}},i=yield this.sendPayloadViaHttp(n);o.captivateLogger.log("Message edit confirmed via HTTP response:",i)}))}sendPayload(e,t){return i(this,void 0,void 0,(function*(){const n={action:"sendMessage",event:{event_type:e,event_payload:t}};return this.sendPayloadViaHttp(n)}))}sendPayloadViaHttp(e){return i(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("API key is required for HTTP communication");const t=`${this.getBaseUrl()}/api/custom-channel/sockets/message`,n=Object.assign(Object.assign({},e),{event:Object.assign(Object.assign({},e.event),{socket_id:this.socketId})});try{const e=yield fetch(t,{method:"POST",headers:{"x-api-key":this.apiKey,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!e.ok)throw new Error(`HTTP request failed: ${e.status} ${e.statusText}`);const i=e.headers.get("content-type");let s;if(i&&i.includes("application/json"))s=yield e.json();else{const t=yield e.text();o.captivateLogger.log("Server returned plain text:",t),s={status:"success",message:t}}return o.captivateLogger.log("Payload received from server via HTTP:",s),s}catch(e){throw console.error("HTTP request failed:",e),new Error(`Failed to send payload via HTTP: ${e instanceof Error?e.message:"Unknown error"}`)}}))}removeListener(e,t){const n=this.listeners.get(e);n&&this.listeners.set(e,n.filter((e=>e!==t)))}getBaseUrl(){return"prod"===this.mode?"https://channel.prod.captivat.io":"https://channel.dev.captivat.io"}getConversationId(){return this.conversationId}}},591:e=>{e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var i={};return(()=>{var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.CaptivateChatFileManager=e.CaptivateChatManager=e.CaptivateChatAPI=void 0;const t=n(86);Object.defineProperty(e,"CaptivateChatAPI",{enumerable:!0,get:function(){return t.CaptivateChatAPI}});const s=n(629);Object.defineProperty(e,"CaptivateChatManager",{enumerable:!0,get:function(){return s.CaptivateChatManager}});const o=n(67);Object.defineProperty(e,"CaptivateChatFileManager",{enumerable:!0,get:function(){return o.CaptivateChatFileManager}}),"undefined"!=typeof window&&(window.CaptivateChatAPI=t.CaptivateChatAPI,window.CaptivateChatManager=s.CaptivateChatManager,window.CaptivateChatFileManager=o.CaptivateChatFileManager)})(),i})()));