cevro-messenger-sdk 0.1.0

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/README.md ADDED
@@ -0,0 +1 @@
1
+ # messanger-sdk
@@ -0,0 +1,3 @@
1
+ !function(){"use strict";try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode('#cevro-messenger-container,.cevro-launcher,.cevro-chat-window{--cevro-primary: #8B5CF6;--cevro-primary-hover: #7C3AED;--cevro-primary-light: #A78BFA;--cevro-bg: #ffffff;--cevro-bg-secondary: #f9fafb;--cevro-text: #111827;--cevro-text-secondary: #6b7280;--cevro-border: #e5e7eb;--cevro-shadow: 0 10px 40px rgba(0, 0, 0, .15);--cevro-shadow-sm: 0 2px 8px rgba(0, 0, 0, .08);--cevro-radius: 16px;--cevro-radius-sm: 12px;--cevro-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;--cevro-transition: .2s ease}.cevro-chat-window--dark{--cevro-bg: #1f2937;--cevro-bg-secondary: #374151;--cevro-text: #f9fafb;--cevro-text-secondary: #9ca3af;--cevro-border: #4b5563}.cevro-launcher{position:fixed;bottom:20px;right:20px;z-index:2147483647;font-family:var(--cevro-font)}.cevro-launcher__button{width:56px;height:56px;border-radius:50%;border:none;background-color:var(--cevro-primary);color:#fff;cursor:pointer;box-shadow:var(--cevro-shadow);display:flex;align-items:center;justify-content:center;transition:transform var(--cevro-transition),box-shadow var(--cevro-transition);position:relative}.cevro-launcher__button:hover{transform:scale(1.05);box-shadow:0 12px 48px #8b5cf666}.cevro-launcher__button:active{transform:scale(.95)}.cevro-launcher__icon{width:24px;height:24px;transition:opacity var(--cevro-transition),transform var(--cevro-transition)}.cevro-launcher__icon--chat{opacity:1;transform:scale(1)}.cevro-launcher__icon--close{position:absolute;opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--chat{opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--close{opacity:1;transform:scale(1)}.cevro-launcher__badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;background-color:#ef4444;color:#fff;font-size:12px;font-weight:600;border-radius:10px;display:flex;align-items:center;justify-content:center;border:2px solid white}.cevro-chat-window{position:fixed;bottom:96px;right:20px;width:380px;height:600px;max-height:calc(100vh - 140px);background-color:var(--cevro-bg);border-radius:var(--cevro-radius);box-shadow:var(--cevro-shadow);display:flex;flex-direction:column;overflow:hidden;font-family:var(--cevro-font);z-index:2147483646;opacity:0;visibility:hidden;transform:translateY(20px) scale(.95);transition:opacity .25s ease,transform .25s ease,visibility .25s ease}.cevro-chat-window--visible{opacity:1;visibility:visible;transform:translateY(0) scale(1)}@media (max-width: 480px){.cevro-chat-window{width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0}}.cevro-chat-window__header{background:linear-gradient(135deg,var(--cevro-primary) 0%,var(--cevro-primary-hover) 100%);color:#fff;padding:16px 20px;display:flex;align-items:center;gap:12px;flex-shrink:0}.cevro-chat-window__agent-avatar{width:40px;height:40px;border-radius:50%;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:#fff3}.cevro-chat-window__agent-avatar svg{width:100%;height:100%}.cevro-chat-window__agent-avatar-img{width:100%;height:100%;object-fit:cover}.cevro-chat-window__title-section{flex:1;min-width:0}.cevro-chat-window__title{margin:0;font-size:16px;font-weight:600}.cevro-chat-window__subtitle{margin:2px 0 0;font-size:12px;opacity:.9}.cevro-chat-window__close{background:none;border:none;color:#fff;cursor:pointer;padding:4px;margin:-4px;opacity:.8;transition:opacity var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-chat-window__close:hover{opacity:1}.cevro-messages{flex:1;overflow:hidden;display:flex;flex-direction:column;background-color:var(--cevro-bg)}.cevro-messages__container{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:8px}.cevro-message{display:flex;max-width:80%;animation:none}.cevro-message--animate{animation:cevro-message-in .3s ease}@keyframes cevro-message-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.cevro-message--inbound{align-self:flex-start}.cevro-message--outbound{align-self:flex-end}.cevro-message__avatar{display:none}.cevro-message__content-wrapper{display:flex;flex-direction:column;gap:4px}.cevro-message--outbound .cevro-message__content-wrapper{align-items:flex-end}.cevro-message__bubble{padding:10px 14px;border-radius:var(--cevro-radius-sm);word-wrap:break-word;overflow-wrap:break-word}.cevro-message--inbound .cevro-message__bubble{background-color:var(--cevro-primary);color:#fff;border-bottom-left-radius:4px}.cevro-message--outbound .cevro-message__bubble{background-color:var(--cevro-bg);color:var(--cevro-text);border:1px solid var(--cevro-border);box-shadow:var(--cevro-shadow-sm);border-bottom-right-radius:4px}.cevro-message__text{font-size:14px;line-height:1.5}.cevro-message__text a{color:inherit;text-decoration:underline}.cevro-message--inbound .cevro-message__text code{background-color:#fff3;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message--outbound .cevro-message__text code{background-color:#0000000d;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message__image-container{position:relative;display:inline-block;max-width:100%}.cevro-message__image{max-width:100%;max-height:300px;border-radius:var(--cevro-radius-sm);display:block}.cevro-file-progress-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#00000080;border-radius:var(--cevro-radius-sm);display:flex;align-items:center;justify-content:center}.cevro-file-progress-overlay .cevro-file-progress{width:80%;text-align:center}.cevro-file-progress-overlay .cevro-file-progress__bar{background:#ffffff4d}.cevro-file-progress-overlay .cevro-file-progress__fill{background:#fff}.cevro-file-progress-overlay .cevro-file-progress__text{color:#fff;font-size:12px;margin-top:4px;display:block}.cevro-file-card{display:flex;align-items:center;gap:12px;padding:12px;background:#ffffff1a;border-radius:var(--cevro-radius-sm);min-width:200px;max-width:280px;transition:background var(--cevro-transition)}.cevro-message--outbound .cevro-file-card{background:#0000000d}.cevro-file-card:hover{background:#fff3}.cevro-message--outbound .cevro-file-card:hover{background:#00000014}.cevro-file-card__icon{flex-shrink:0;width:40px;height:40px;display:flex;align-items:center;justify-content:center}.cevro-file-card__icon svg{width:36px;height:36px}.cevro-file-card__info{flex:1;min-width:0;overflow:hidden}.cevro-file-card__name{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:inherit}.cevro-file-card__details{font-size:11px;opacity:.7;margin-top:2px}.cevro-file-card__progress{flex-shrink:0;width:60px}.cevro-file-progress{width:100%}.cevro-file-progress__bar{height:4px;background:#0000001a;border-radius:2px;overflow:hidden}.cevro-message--outbound .cevro-file-progress__bar{background:#0000001a}.cevro-message--inbound .cevro-file-progress__bar{background:#fff3}.cevro-file-progress__fill{height:100%;background:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-message--inbound .cevro-file-progress__fill{background:#fff}.cevro-file-progress__text{font-size:10px;opacity:.7;margin-top:2px;display:block;text-align:right}.cevro-message__attachment{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none;padding:8px 12px;background-color:#ffffff26;border-radius:var(--cevro-radius-sm);font-size:13px}.cevro-message--outbound .cevro-message__attachment{background-color:#0000000d}.cevro-message__attachment:hover{background-color:#ffffff40}.cevro-message--outbound .cevro-message__attachment:hover{background-color:#00000014}.cevro-message__meta{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--cevro-text-secondary);padding:0 4px}.cevro-message__status{display:flex;align-items:center}.cevro-message__quick-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}.cevro-message__quick-action{padding:8px 16px;background-color:var(--cevro-bg);border:1px solid var(--cevro-border);color:var(--cevro-text);border-radius:20px;font-size:13px;cursor:pointer;transition:all var(--cevro-transition)}.cevro-message__quick-action:hover{background-color:var(--cevro-primary);border-color:var(--cevro-primary);color:#fff}.cevro-typing-indicator{display:flex;gap:8px;align-items:center;padding:8px 0}.cevro-typing-indicator__avatar{display:none}.cevro-typing-indicator__dots{display:flex;gap:4px;padding:12px 16px;background-color:var(--cevro-primary);border-radius:var(--cevro-radius-sm);border-bottom-left-radius:4px}.cevro-typing-indicator__dots span{width:6px;height:6px;background-color:#ffffffb3;border-radius:50%;animation:cevro-typing-bounce 1.4s ease-in-out infinite}.cevro-typing-indicator__dots span:nth-child(1){animation-delay:0s}.cevro-typing-indicator__dots span:nth-child(2){animation-delay:.2s}.cevro-typing-indicator__dots span:nth-child(3){animation-delay:.4s}@keyframes cevro-typing-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cevro-chat-window__input-wrapper{border-top:1px solid var(--cevro-border);background-color:var(--cevro-bg)}.cevro-chat-window__input-area{display:flex;align-items:center;gap:8px;padding:12px 16px}.cevro-chat-window__file-button{width:36px;height:36px;border:1px solid var(--cevro-border);background-color:var(--cevro-bg);color:var(--cevro-text-secondary);cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__file-button:hover{background-color:var(--cevro-bg-secondary);border-color:var(--cevro-primary);color:var(--cevro-primary)}.cevro-chat-window__file-button svg{display:block;width:20px;height:20px;color:var(--cevro-text-secondary)}.cevro-chat-window__file-button:hover svg{color:var(--cevro-primary)}.cevro-chat-window__file-input{display:none}.cevro-chat-window__input{flex:1;border:1px solid var(--cevro-border);border-radius:20px;padding:8px 16px;font-size:14px;font-family:var(--cevro-font);resize:none;outline:none;background-color:var(--cevro-bg);color:var(--cevro-text);max-height:100px;line-height:1.4;transition:border-color var(--cevro-transition)}.cevro-chat-window__input::placeholder{color:var(--cevro-text-secondary)}.cevro-chat-window__input:focus{border-color:var(--cevro-primary)}.cevro-chat-window__send-button{width:36px;height:36px;border:none;background-color:var(--cevro-primary);color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__send-button:hover:not(:disabled){background-color:var(--cevro-primary-hover);transform:scale(1.05)}.cevro-chat-window__send-button:disabled{opacity:.5;cursor:not-allowed}.cevro-chat-window__send-button svg{display:block;width:18px;height:18px;flex-shrink:0}.cevro-chat-window__upload-progress{display:flex;align-items:center;gap:12px;padding:8px 16px;background-color:var(--cevro-bg-secondary);border-bottom:1px solid var(--cevro-border)}.cevro-chat-window__upload-progress-bar{flex:1;height:4px;background-color:var(--cevro-border);border-radius:2px;overflow:hidden}.cevro-chat-window__upload-progress-fill{height:100%;background-color:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-chat-window__upload-progress-text{font-size:12px;color:var(--cevro-text-secondary);white-space:nowrap}.cevro-chat-window__file-button:disabled{opacity:.5;cursor:not-allowed}.cevro-chat-window__footer{padding:8px 16px;text-align:center;font-size:11px;color:var(--cevro-text-secondary);background-color:var(--cevro-bg)}.cevro-chat-window__footer a{color:var(--cevro-primary);text-decoration:none}.cevro-chat-window__footer a:hover{text-decoration:underline}.cevro-messages__container::-webkit-scrollbar{width:6px}.cevro-messages__container::-webkit-scrollbar-track{background:transparent}.cevro-messages__container::-webkit-scrollbar-thumb{background-color:var(--cevro-border);border-radius:3px}.cevro-messages__container::-webkit-scrollbar-thumb:hover{background-color:var(--cevro-text-secondary)}.cevro-messages__closed-notice{flex:1;display:flex;flex-direction:column;justify-content:flex-end;padding:16px;text-align:center}.cevro-messages__closed-text{font-size:14px;color:var(--cevro-text-secondary);margin:0;line-height:1.5}.cevro-chat-window__closed-footer{padding:16px;background-color:var(--cevro-bg);border-top:1px solid var(--cevro-border);display:flex;flex-direction:column;gap:12px}.cevro-chat-window__new-chat-button{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition);font-family:var(--cevro-font)}.cevro-chat-window__new-chat-button:hover{background:var(--cevro-primary-hover)}.cevro-chat-window__new-chat-button:active{transform:scale(.98)}.cevro-chat-window__powered-by{text-align:center;font-size:11px;color:var(--cevro-text-secondary)}@keyframes cevro-fade-in{0%{opacity:0}to{opacity:1}}')),document.head.appendChild(e)}}catch(r){console.error("vite-plugin-css-injected-by-js",r)}}();
2
+ "use strict";var e=Object.defineProperty,t=(t,s,i)=>((t,s,i)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i)(t,"symbol"!=typeof s?s+"":s,i);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});let s=class{constructor(){t(this,"listeners",new Map),t(this,"onceHandlers",new Map)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const s=i=>{this.onceHandlers.delete(s),this.off(e,s),t(i)};return this.onceHandlers.set(s,t),this.on(e,s)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),this.onceHandlers.delete(t))}emit(e,t){const s=this.listeners.get(e);s&&s.forEach(s=>{try{s(t)}catch(i){console.error(`[CevroMessenger] Error in event handler for "${e}":`,i)}})}removeAllListeners(e){if(e){const t=this.listeners.get(e);t&&t.forEach(e=>{this.onceHandlers.delete(e)}),this.listeners.delete(e)}else this.listeners.clear(),this.onceHandlers.clear()}listenerCount(e){var t;return(null==(t=this.listeners.get(e))?void 0:t.size)||0}};function i(){try{return localStorage.getItem("cevro_visitor_token")}catch{return null}}function n(e){try{localStorage.setItem("cevro_visitor_token",e)}catch{}}function o(){return function(){const e=i();return e?function(e){if(!e)return null;const t=e.lastIndexOf(".");return t<=0?null:e.substring(0,t)}(e):null}()}const r=new Set(["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","text/plain","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","audio/mpeg","audio/wav","audio/ogg","video/mp4","video/webm","application/zip","application/x-rar-compressed"]),a=new Set([".exe",".dll",".bat",".cmd",".sh",".bash",".ps1",".psm1",".psd1",".vbs",".vbe",".js",".jse",".ws",".wsf",".wsc",".wsh",".msi",".msp",".mst",".scr",".pif",".com",".hta",".cpl",".msc",".jar",".class",".php",".php3",".php4",".php5",".phtml",".asp",".aspx",".ashx",".asmx",".jsp",".jspx",".py",".pyc",".pyw",".rb",".rbw",".pl",".pm",".cgi",".htaccess",".htpasswd"]),c={maxSizeBytes:26214400,minSizeBytes:1,maxFilenameLength:255};function l(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?"":e.substring(t).toLowerCase()}function h(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}class d{constructor(e=5,s=6e4){t(this,"uploadTimestamps",[]),t(this,"maxUploads"),t(this,"windowMs"),this.maxUploads=e,this.windowMs=s}canUpload(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),this.uploadTimestamps.length<this.maxUploads}recordUpload(){this.uploadTimestamps.push(Date.now())}getRemainingUploads(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),Math.max(0,this.maxUploads-this.uploadTimestamps.length)}getTimeUntilNextUpload(){if(this.canUpload())return 0;const e=Math.min(...this.uploadTimestamps);return Math.max(0,this.windowMs-(Date.now()-e))}reset(){this.uploadTimestamps=[]}}class u{constructor(e){var s;t(this,"config"),t(this,"accessToken",null),t(this,"contactId",null),t(this,"currentTicketId",null),t(this,"visitorToken",null),t(this,"currentAgent",null),t(this,"uploadRateLimiter"),this.config=e;const i=(null==(s=e.fileUpload)?void 0:s.maxUploadsPerMinute)??5;this.uploadRateLimiter=new d(i,6e4)}setVisitorToken(e){this.visitorToken=e}getVisitorToken(){return this.visitorToken}setAccessToken(e){this.accessToken=e}getContactId(){return this.contactId}getCurrentTicketId(){return this.currentTicketId}setCurrentTicketId(e){this.currentTicketId=e}getCurrentAgent(){return this.currentAgent}async request(e,t={}){const s=`${this.config.apiBase}${e}`,i={"Content-Type":"application/json",...t.headers||{}};this.config.workspaceId&&(i["X-Workspace-Id"]=this.config.workspaceId),this.config.brandId&&(i["X-Brand-Id"]=this.config.brandId),this.visitorToken&&(i["X-Visitor-Token"]=this.visitorToken),this.accessToken&&(i.Authorization=`Bearer ${this.accessToken}`);const n=await fetch(s,{...t,headers:i});if(!n.ok){const e=await n.json().catch(()=>({message:n.statusText}));throw new Error(e.message||`Request failed: ${n.status}`)}return n.json()}async initSession(e,t){var s,i,n,o;const r={visitorId:e,session:function(){const e={};if("undefined"==typeof window||"undefined"==typeof navigator)return e;try{e.userAgent=navigator.userAgent,e.language=navigator.language,e.platform=navigator.platform,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.currentPage=window.location.href,e.pageTitle=document.title,e.referrer=document.referrer,e.screenWidth=window.screen.width,e.screenHeight=window.screen.height,e.viewportWidth=window.innerWidth,e.viewportHeight=window.innerHeight,e.devicePixelRatio=window.devicePixelRatio;const t=new URLSearchParams(window.location.search);e.utmSource=t.get("utm_source")||void 0,e.utmMedium=t.get("utm_medium")||void 0,e.utmCampaign=t.get("utm_campaign")||void 0,e.utmContent=t.get("utm_content")||void 0,e.utmTerm=t.get("utm_term")||void 0,e.cookiesEnabled=navigator.cookieEnabled,e.touchSupport="ontouchstart"in window||navigator.maxTouchPoints>0,e.online=navigator.onLine;const s=navigator.connection;s&&(e.connectionType=s.effectiveType)}catch(t){}return e}(),brandId:this.config.brandId,firstName:null==(s=this.config.player)?void 0:s.firstName,email:null==(i=this.config.player)?void 0:i.email,locale:this.config.locale,forceNewTicket:null==t?void 0:t.forceNewTicket};(null==(n=this.config.player)?void 0:n.playerId)&&(r.playerId=this.config.player.playerId,r.playerHash=this.config.player.playerHash);const a=await this.request("/api/v1/sdk/session",{method:"POST",body:JSON.stringify(r),headers:e?{"X-Visitor-Id":e}:void 0});return this.contactId=a.contactId,this.currentTicketId=a.ticketId,a.agent&&(this.currentAgent=a.agent),{sessionId:a.sessionId,contactId:a.contactId,ticketId:a.ticketId,visitorId:a.visitorId,isNewSession:a.isNewSession,isNewTicket:a.isNewTicket,ticketClosed:a.ticketClosed,ticketClosedReason:a.ticketClosedReason,agent:a.agent,typingConfig:a.typingConfig,messages:null==(o=a.messages)?void 0:o.map(e=>this.normalizeMessage(e))}}async sendMessage(e,t){if(!this.contactId||!this.currentTicketId)throw new Error("No active session. Call initSession first.");const s={contactId:this.contactId,ticketId:this.currentTicketId,message:e,assetId:t},i=await this.request("/api/v1/sdk/send",{method:"POST",body:JSON.stringify(s)});return this.normalizeMessage(i.message||i)}async getMessages(e){const t=e||this.currentTicketId;if(!t)throw new Error("No ticket ID available");const s=await this.request(`/api/v1/messages/my-tickets?supportTicketId=${t}`);return(s.results||s.messages||s||[]).map(e=>this.normalizeMessage(e))}async getMyTickets(){const e=await this.request("/api/v1/messages/my-tickets");return(e.results||e.tickets||e||[]).map(e=>this.normalizeConversation(e))}async uploadFile(e,t){var s,i,n;if(!this.uploadRateLimiter.canUpload()){const e=Math.ceil(this.uploadRateLimiter.getTimeUntilNextUpload()/1e3);throw new Error(`Too many uploads. Please wait ${e} seconds before uploading again.`)}const o=function(e,t={}){const{maxSizeBytes:s=c.maxSizeBytes,minSizeBytes:i=c.minSizeBytes,allowedMimeTypes:n=r,blockedExtensions:o=a,maxFilenameLength:d=c.maxFilenameLength}=t;if(0===e.size)return{valid:!1,error:"File is empty",errorCode:"EMPTY_FILE"};if(e.size<i)return{valid:!1,error:`File is too small. Minimum size is ${h(i)}`,errorCode:"FILE_TOO_SMALL"};if(e.size>s)return{valid:!1,error:`File is too large. Maximum size is ${h(s)}`,errorCode:"FILE_TOO_LARGE"};if(e.name.length>d)return{valid:!1,error:`Filename is too long. Maximum length is ${d} characters`,errorCode:"FILENAME_TOO_LONG"};const u=l(e.name);if(u&&o.has(u))return{valid:!1,error:`File type "${u}" is not allowed for security reasons`,errorCode:"BLOCKED_EXTENSION"};const p=e.type||"application/octet-stream";return n.has(p)||"application/octet-stream"===p&&u&&!o.has(u)?{valid:!0}:{valid:!1,error:`File type "${p}" is not allowed. Allowed types: images, documents, audio, video`,errorCode:"INVALID_TYPE"}}(e,{maxSizeBytes:(null==(s=this.config.fileUpload)?void 0:s.maxSizeBytes)??c.maxSizeBytes,allowedMimeTypes:(null==(i=this.config.fileUpload)?void 0:i.allowedMimeTypes)?new Set(this.config.fileUpload.allowedMimeTypes):r,blockedExtensions:(null==(n=this.config.fileUpload)?void 0:n.additionalBlockedExtensions)?new Set([...a,...this.config.fileUpload.additionalBlockedExtensions]):a});if(!o.valid)throw new Error(o.error||"File validation failed");const d=function(e){let t=e.replace(/^.*[\\/]/,"");if(t=t.replace(/[\x00-\x1f\x7f]/g,""),t=t.replace(/[<>:"/\\|?*]/g,"_"),t=t.replace(/^[\s.]+|[\s.]+$/g,""),t||(t="unnamed_file"),t.length>c.maxFilenameLength){const e=l(t),s=t.slice(0,-e.length||void 0),i=c.maxFilenameLength-e.length;t=s.slice(0,i)+e}return t}(e.name);this.uploadRateLimiter.recordUpload();const{uploadUrl:u,assetId:p}=await this.request("/api/v1/sdk/upload-url",{method:"POST",body:JSON.stringify({filename:d,contentType:e.type||"application/octet-stream",size:e.size})});return await this.uploadToS3(u,e,t),p}async uploadToS3(e,t,s){return new Promise((i,n)=>{const o=new XMLHttpRequest;o.upload.addEventListener("progress",e=>{if(e.lengthComputable&&s){const t=Math.round(e.loaded/e.total*100);s(t)}}),o.addEventListener("load",()=>{o.status>=200&&o.status<300?i():n(new Error(`Upload failed with status ${o.status}`))}),o.addEventListener("error",()=>{n(new Error("Upload failed"))}),o.open("PUT",e),o.setRequestHeader("Content-Type",t.type||"application/octet-stream"),o.send(t)})}normalizeMessage(e){return{id:e.objectId||e.id,body:e.body||"",inbound:e.inbound||!1,outbound:e.outbound||!e.inbound,createdAt:e.createdAt||(new Date).toISOString(),type:e.type||"text",mediaUrl:e.mediaUrl,mediaType:e.mediaType,status:e.status||"sent",richContent:e.richContent}}normalizeConversation(e){return{id:e.objectId||e.id,conversationId:e.conversationId||e.objectId||e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.resolved?"resolved":e.escalated?"escalated":"open",unreadCount:e.unreadCount||0,lastMessage:e.latestMessage?this.normalizeMessage(e.latestMessage):void 0}}async getConnectionToken(e){var t;const s={workspaceId:this.config.workspaceId,brandId:this.config.brandId};e&&(s.visitorToken=e),(null==(t=this.config.player)?void 0:t.playerId)&&(s.playerId=this.config.player.playerId,s.playerHash=this.config.player.playerHash,s.email=this.config.player.email,s.firstName=this.config.player.firstName);return await this.request("/api/v1/sdk/token",{method:"POST",body:JSON.stringify(s)})}async refreshConnectionToken(e){return this.getConnectionToken(e)}clear(){this.accessToken=null,this.contactId=null,this.currentTicketId=null}}function p(e,t,s,i){return new(s||(s=Promise))(function(t,n){function o(e){try{a(i.next(e))}catch(t){n(t)}}function r(e){try{a(i.throw(e))}catch(t){n(t)}}function a(e){var i;e.done?t(e.value):(i=e.value,i instanceof s?i:new s(function(e){e(i)})).then(o,r)}a((i=i.apply(e,[])).next())})}function g(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var m,_={exports:{}},f="object"==typeof Reflect?Reflect:null,b=f&&"function"==typeof f.apply?f.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};m=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var v=Number.isNaN||function(e){return e!=e};function w(){w.init.call(this)}_.exports=w,_.exports.once=function(e,t){return new Promise(function(s,i){function n(s){e.removeListener(t,o),i(s)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",n),s([].slice.call(arguments))}L(e,t,o,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&L(e,"error",t,s)}(e,n,{once:!0})})},w.EventEmitter=w,w.prototype._events=void 0,w.prototype._eventsCount=0,w.prototype._maxListeners=void 0;var y=10;function C(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function T(e){return void 0===e._maxListeners?w.defaultMaxListeners:e._maxListeners}function k(e,t,s,i){var n,o,r,a;if(C(s),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),o=e._events),r=o[t]),void 0===r)r=o[t]=s,++e._eventsCount;else if("function"==typeof r?r=o[t]=i?[s,r]:[r,s]:i?r.unshift(s):r.push(s),(n=T(e))>0&&r.length>n&&!r.warned){r.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=r.length,a=c,console&&console.warn&&console.warn(a)}return e}function S(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function E(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},n=S.bind(i);return n.listener=s,i.wrapFn=n,n}function x(e,t,s){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?s?[n.listener||n]:[n]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(n):M(n,n.length)}function I(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function M(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function L(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function n(o){i.once&&e.removeEventListener(t,n),s(o)})}}Object.defineProperty(w,"defaultMaxListeners",{enumerable:!0,get:function(){return y},set:function(e){if("number"!=typeof e||e<0||v(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");y=e}}),w.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},w.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||v(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},w.prototype.getMaxListeners=function(){return T(this)},w.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var r=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw r.context=o,r}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)b(a,this,t);else{var c=a.length,l=M(a,c);for(s=0;s<c;++s)b(l[s],this,t)}return!0},w.prototype.addListener=function(e,t){return k(this,e,t,!1)},w.prototype.on=w.prototype.addListener,w.prototype.prependListener=function(e,t){return k(this,e,t,!0)},w.prototype.once=function(e,t){return C(t),this.on(e,E(this,e,t)),this},w.prototype.prependOnceListener=function(e,t){return C(t),this.prependListener(e,E(this,e,t)),this},w.prototype.removeListener=function(e,t){var s,i,n,o,r;if(C(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(n=-1,o=s.length-1;o>=0;o--)if(s[o]===t||s[o].listener===t){r=s[o].listener,n=o;break}if(n<0)return this;0===n?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,n),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,r||t)}return this},w.prototype.off=w.prototype.removeListener,w.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var n,o=Object.keys(s);for(i=0;i<o.length;++i)"removeListener"!==(n=o[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},w.prototype.listeners=function(e){return x(this,e,!0)},w.prototype.rawListeners=function(e){return x(this,e,!1)},w.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):I.call(e,t)},w.prototype.listenerCount=I,w.prototype.eventNames=function(){return this._eventsCount>0?m(this._events):[]};var P,R,O,z,N,A,H,U,V,B,D,j,W,F,$,Z,q=g(_.exports);function J(e){return null!=e&&"function"==typeof e}function Q(e,t,s){e>31&&(e=31);const i=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)}(0,Math.min(s,t*Math.pow(2,e)));return Math.min(s,t+i)}function G(e){return Math.min(1e3*e,2147483647)}(R=P||(P={}))[R.timeout=1]="timeout",R[R.transportClosed=2]="transportClosed",R[R.clientDisconnected=3]="clientDisconnected",R[R.clientClosed=4]="clientClosed",R[R.clientConnectToken=5]="clientConnectToken",R[R.clientRefreshToken=6]="clientRefreshToken",R[R.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",R[R.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",R[R.subscriptionRefreshToken=9]="subscriptionRefreshToken",R[R.transportWriteError=10]="transportWriteError",R[R.connectionClosed=11]="connectionClosed",R[R.badConfiguration=12]="badConfiguration",(z=O||(O={}))[z.connectCalled=0]="connectCalled",z[z.transportClosed=1]="transportClosed",z[z.noPing=2]="noPing",z[z.subscribeTimeout=3]="subscribeTimeout",z[z.unsubscribeError=4]="unsubscribeError",(A=N||(N={}))[A.disconnectCalled=0]="disconnectCalled",A[A.unauthorized=1]="unauthorized",A[A.badProtocol=2]="badProtocol",A[A.messageSizeLimit=3]="messageSizeLimit",(U=H||(H={}))[U.subscribeCalled=0]="subscribeCalled",U[U.transportClosed=1]="transportClosed",(B=V||(V={}))[B.unsubscribeCalled=0]="unsubscribeCalled",B[B.unauthorized=1]="unauthorized",B[B.clientClosed=2]="clientClosed",(j=D||(D={}))[j.channelCompaction=1]="channelCompaction",(F=W||(W={})).Disconnected="disconnected",F.Connecting="connecting",F.Connected="connected",(Z=$||($={})).Unsubscribed="unsubscribed",Z.Subscribing="subscribing",Z.Subscribed="subscribed";class K extends q{constructor(e,t,s){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=$.Unsubscribed,this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValue=null,this._unsubPromise=Promise.resolve(),this._setOptions(s),this._centrifuge._debugEnabled?(this.on("state",e=>{this._debug("subscription state",t,e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("subscription error",t,e)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state===$.Unsubscribed?Promise.reject({code:P.subscriptionUnsubscribed,message:this.state}):this.state===$.Subscribed?Promise.resolve():new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(function(){s({code:P.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(H.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(V.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return p(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return p(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return p(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return p(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e}setData(e){this._data=e}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:P.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const s=this._centrifuge._config.timeout,i=setTimeout(()=>{t({code:P.timeout,message:"timeout"})},s);this._promises[this._nextPromiseId()]={timeout:i,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===$.Unsubscribed}_isSubscribing(){return this.state===$.Subscribing}_isSubscribed(){return this.state===$.Subscribed}_setState(e){if(this.state!==e){const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(!this._isSubscribing())return;this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,this._setState($.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const s=e.publications;if(s&&s.length>0)for(const i in s)s.hasOwnProperty(i)&&this._handlePublication(s[i]);!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),G(e.ttl)))}_setSubscribing(e,t){return p(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState($.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(e=>this._handleTokenResponse(e)).catch(e=>this._handleTokenError(e)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_getDataAndSubscribe(e){this._getData?this._getData({channel:this.channel}).then(t=>{this._isSubscribing()?(this._data=t,this._sendSubscribe(e)):this._inflight=!1}).catch(e=>this._handleGetDataError(e)):this._inflight=!1}_handleGetDataError(e){if(this._isSubscribing()){if(e instanceof le)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:P.badConfiguration,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(e){if(this._isSubscribing()){if(!e)return this._inflight=!1,void this._failUnauthorized();this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}else this._inflight=!1}_handleTokenError(e){if(this._isSubscribing()){if(e instanceof le)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:P.subscriptionSubscribeToken,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(e=>{this._inflight=!1;const t=e.reply.subscribe;this._handleSubscribeResponse(t),e.next&&e.next()},e=>{this._inflight=!1,this._handleSubscribeError(e.error),e.next&&e.next()}),t}_buildSubscribeCommand(e){const t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=D.channelCompaction,this._needRecover()){t.recover=!0;const e=this._getOffset();e&&(t.offset=e);const s=this._getEpoch();s&&(t.epoch=s)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==P.timeout?this._subscribeError(e):this._centrifuge._disconnect(O.subscribeTimeout,"subscribe timeout",!0))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,s){if(this._isUnsubscribed())return Promise.resolve();let i=Promise.resolve();return this._isSubscribed()?(s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._setState($.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:P.subscriptionUnsubscribed,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){const{newData:t,newPrevValue:s}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValue);e.data=t,this._prevValue=s}const t=this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),e.offset&&(this._offset=e.offset)}_handleJoin(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||109===e.code||!0===e.temporary){109===e.code&&(this._token="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===W.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=Q(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=e.since.offset||0,this._epoch=e.since.epoch||"",this._recover=!0),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),!0===e.positioned&&(this._positioned=!0),!0===e.recoverable&&(this._recoverable=!0),!0===e.joinLeave&&(this._joinLeave=!0),e.delta){if("fossil"!==e.delta)throw new Error("unsupported delta format");this._delta=e.delta}if(e.tagsFilter&&(this._tagsFilter=e.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together")}}_getOffset(){const e=this._offset;return null!==e?e:0}_getEpoch(){const e=this._epoch;return null!==e?e:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const e={channel:this.channel},t=this._getToken;return null===t?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:P.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new le(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t)return void e._failUnauthorized();e._token=t;const s={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(s).then(t=>{const s=t.reply.sub_refresh;e._refreshResponse(s),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){t instanceof le?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:P.subscriptionRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay()))})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),G(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return Q(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(V.unauthorized,"unauthorized",!0)}}class X{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class Y{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(e,t){let s="";"protobuf"===e&&(s="centrifuge-protobuf"),this._transport=""!==s?new this.options.websocket(this.endpoint,s):new this.options.websocket(this.endpoint),"protobuf"===e&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class ee{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,s){const i=new EventTarget;return(0,e.options.fetch)(t,s).then(e._handleErrors).then(t=>{i.dispatchEvent(new Event("open"));let s="",n=0,o=new Uint8Array;const r=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return r.read().then(({done:r,value:c})=>{if(r)return i.dispatchEvent(new Event("close")),void t.close();try{if("json"===e._protocol)for(s+=e._utf8decoder.decode(c);n<s.length;)if("\n"===s[n]){const e=s.substring(0,n);i.dispatchEvent(new MessageEvent("message",{data:e})),s=s.substring(n+1),n=0}else++n;else{const t=new Uint8Array(o.length+c.length);for(t.set(o),t.set(c,o.length),o=t;;){const t=e.options.decoder.decodeReply(o);if(t.ok){const e=o.slice(0,t.pos);i.dispatchEvent(new MessageEvent("message",{data:e})),o=o.slice(t.pos);continue}break}}}catch(l){return i.dispatchEvent(new Event("error",{detail:l})),i.dispatchEvent(new Event("close")),void t.close()}a()}).catch(function(e){i.dispatchEvent(new Event("error",{detail:e})),i.dispatchEvent(new Event("close")),t.close()})}()})}).catch(e=>{i.dispatchEvent(new Event("error",{detail:e})),i.dispatchEvent(new Event("close"))}),i}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!=typeof TextDecoder&&"undefined"!=typeof AbortController&&"undefined"!=typeof EventTarget&&"undefined"!=typeof Event&&"undefined"!=typeof MessageEvent&&"undefined"!=typeof Error}initialize(e,t,s){let i,n;this._protocol=e,this._abortController=new AbortController,"json"===e?(i={Accept:"application/json","Content-Type":"application/json"},n=s):(i={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=s);const o={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},r=this._fetchEventTarget(this,this.endpoint,o);r.addEventListener("open",()=>{t.onOpen()}),r.addEventListener("error",e=>{this._abortController.abort(),t.onError(e)}),r.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),r.addEventListener("message",e=>{t.onMessage(e.data)})}close(){this._abortController.abort()}send(e,t,s){let i,n;const o={session:t,node:s,data:e};"json"===this._protocol?(i={"Content-Type":"application/json"},n=JSON.stringify(o)):(i={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(o));const r={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,r)}}class te{constructor(e,t){this.endpoint=e,this.options=t,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,s){let i;i=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),i.searchParams.append("cf_connect",s);const n=new this.options.eventsource(i.toString(),{});this._transport=n;n.onopen=function(){t.onOpen()},n.onerror=function(e){n.close(),t.onError(e),t.onClose({code:4,reason:"connection closed"})},n.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,s){const i={session:t,node:s,data:e},n={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,n)}}class se{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(e,t){return p(this,0,void 0,function*(){let s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===e&&s.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const i=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(o){return void this.close()}let n;try{n=yield this._transport.createBidirectionalStream()}catch(r){return void this.close()}this._stream=n,this._writer=this._stream.writable.getWriter(),i.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),i.addEventListener("message",e=>{t.onMessage(e.data)}),this._startReading(i),t.onOpen()})}_startReading(e){return p(this,0,void 0,function*(){const t=this._stream.readable.getReader();let s="",i=0,n=new Uint8Array;try{for(;;){const{done:o,value:r}=yield t.read();if(r.length>0)if("json"===this._protocol)for(s+=this._utf8decoder.decode(r);i<s.length;)if("\n"===s[i]){const t=s.substring(0,i);e.dispatchEvent(new MessageEvent("message",{data:t})),s=s.substring(i+1),i=0}else++i;else{const t=new Uint8Array(n.length+r.length);for(t.set(n),t.set(r,n.length),n=t;;){const t=this.options.decoder.decodeReply(n);if(t.ok){const s=n.slice(0,t.pos);e.dispatchEvent(new MessageEvent("message",{data:s})),n=n.slice(t.pos);continue}break}}if(o)break}}catch(o){e.dispatchEvent(new Event("close"))}})}close(){return p(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return p(this,0,void 0,function*(){let t;t="json"===this._protocol?(new TextEncoder).encode(e+"\n"):e;try{yield this._writer.write(t)}catch(s){this.close()}})}}const ie=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class ne{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e,t=0;for(;this.haveBytes()&&(e=ie[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class oe{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,s){for(let i=t;i<s;i++)this.a.push(e[i])}}function re(e){let t=0,s=0,i=0,n=0,o=0,r=e.length;for(;r>=16;)t=t+e[o+0]|0,s=s+e[o+1]|0,i=i+e[o+2]|0,n=n+e[o+3]|0,t=t+e[o+4]|0,s=s+e[o+5]|0,i=i+e[o+6]|0,n=n+e[o+7]|0,t=t+e[o+8]|0,s=s+e[o+9]|0,i=i+e[o+10]|0,n=n+e[o+11]|0,t=t+e[o+12]|0,s=s+e[o+13]|0,i=i+e[o+14]|0,n=n+e[o+15]|0,o+=16,r-=16;for(;r>=4;)t=t+e[o+0]|0,s=s+e[o+1]|0,i=i+e[o+2]|0,n=n+e[o+3]|0,o+=4,r-=4;switch(n=((n+(i<<8)|0)+(s<<16)|0)+(t<<24)|0,r){case 3:n=n+(e[o+2]<<8)|0;case 2:n=n+(e[o+1]<<16)|0;case 1:n=n+(e[o+0]<<24)|0}return n>>>0}class ae{name(){return"json"}encodeCommands(e){return e.map(e=>JSON.stringify(e)).join("\n")}decodeReplies(e){return e.trim().split("\n").map(e=>JSON.parse(e))}applyDeltaIfNeeded(e,t){let s,i;if(e.delta){const n=function(e,t){let s=0;const i=new ne(t),n=e.length,o=t.length,r=i.getInt();if("\n"!==i.getChar())throw new Error("size integer not terminated by '\\n'");const a=new oe;for(;i.haveBytes();){const t=i.getInt();let c;switch(i.getChar()){case"@":if(c=i.getInt(),i.haveBytes()&&","!==i.getChar())throw new Error("copy command not terminated by ','");if(s+=t,s>r)throw new Error("copy exceeds output file size");if(c+t>n)throw new Error("copy extends past end of input");a.putArray(e,c,c+t);break;case":":if(s+=t,s>r)throw new Error("insert command gives an output larger than predicted");if(t>o)throw new Error("insert count exceeds size of delta");a.putArray(i.a,i.pos,i.pos+t),i.pos+=t;break;case";":{const i=a.toByteArray(e);if(t!==re(i))throw new Error("bad checksum");if(s!==r)throw new Error("generated size does not match predicted size");return i}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(t,(new TextEncoder).encode(e.data));s=JSON.parse((new TextDecoder).decode(n)),i=n}else s=JSON.parse(e.data),i=(new TextEncoder).encode(e.data);return{newData:s,newPrevValue:i}}}const ce={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class le extends Error{constructor(e){super(e),this.name=this.constructor.name}}class he extends q{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=W.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new ae,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},ce),t),this._configure(),this._debugEnabled?(this.on("state",e=>{this._debug("client state",e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("client error",e)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new K(this,e,t);return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==$.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return p(this,0,void 0,function*(){switch(this.state){case W.Disconnected:throw{code:P.clientDisconnected,message:"client disconnected"};case W.Connected:return;default:return new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(()=>{s({code:P.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(N.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return p(this,0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(P.transportWriteError,"transport write error")})}rpc(e,t){return p(this,0,void 0,function*(){const s={rpc:{method:e,data:t}};yield this._methodCall();return{data:(yield this._callPromise(s,e=>e.rpc)).data}})}publish(e,t){return p(this,0,void 0,function*(){const s={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}history(e,t){return p(this,0,void 0,function*(){const s={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(s,e=>e.history),n=[];if(i.publications)for(let t=0;t<i.publications.length;t++)n.push(this._getPublicationContext(e,i.publications[t]));return{publications:n,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return p(this,0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(t,e=>e.presence)).presence;for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){const t=s[e],i=t.conn_info,n=t.chan_info;i&&(t.connInfo=i),n&&(t.chanInfo=n)}return{clients:s}})}presenceStats(e){return p(this,0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const s=yield this._callPromise(t,e=>e.presence_stats);return{numUsers:s.num_users,numClients:s.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&function(e,t){if(globalThis.console){const s=globalThis.console[e];J(s)&&s.apply(globalThis.console,t)}}("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new ae,this._formatOverride(),(!0===this._config.debug||"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"==typeof this._endpoint);else{if(!Array.isArray(this._endpoint))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const s=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(s)<0)throw new Error("unsupported transport name: "+s)}}}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===W.Disconnected}_isConnecting(){return this.state===W.Connecting}_isConnected(){return this.state===W.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==W.Connected&&this.state!==W.Connecting||(this._disconnect(O.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===W.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=Q(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const s=t.errback;if(!s)continue;s({error:this._createErrorObject(P.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===$.Subscribed&&t._setSubscribing(H.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const e=t.id;if(!(e in this._callbacks))continue;const s=this._callbacks[e];clearTimeout(this._callbacks[e].timeout),delete this._callbacks[e];(0,s.errback)({error:this._createErrorObject(P.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;null!==this._config.websocket?e=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(e=globalThis.WebSocket);let t=null;null!==this._config.sockjs?t=this._config.sockjs:void 0!==globalThis.SockJS&&(t=globalThis.SockJS);let s=null;null!==this._config.eventsource?s=this._config.eventsource:void 0!==globalThis.EventSource&&(s=globalThis.EventSource);let i=null;null!==this._config.fetch?i=this._config.fetch:void 0!==globalThis.fetch&&(i=globalThis.fetch);let n=null;if(null!==this._config.readableStream?n=this._config.readableStream:void 0!==globalThis.ReadableStream&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let o=0;for(;;){if(o>=this._transports.length)throw new Error("no supported transport found");const r=this._transports[this._currentTransportIndex],a=r.transport,c=r.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new Y(c,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,o++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new se(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,o++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new ee(c,{fetch:i,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,o++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new te(c,{eventsource:s,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,o++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new X(c,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,o++;continue}}break}}else{if(o=this._endpoint,r="http",0===o.lastIndexOf(r,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new Y(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var o,r;const a=this,c=this._transport,l=this._nextTransportId();a._debug("id of transport",l);let h=!1;const d=[];if(this._transport.emulation()){const e=a._sendConnect(!0);d.push(e)}this._setNetworkEvents();const u=this._codec.encodeCommands(d);let p;this._transportClosed=!1,p=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return a._debug("open callback from non-actual transport"),void c.close();h=!0,a._debug(c.subName(),"transport open"),c.emulation()||(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(e){a._transportId==l?a._debug("transport level error",e):a._debug("error callback from non-actual transport")},onClose:function(e){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return void a._debug("close callback from non-actual transport");a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let t="connection closed",s=!0,i=0;if(e&&"code"in e&&e.code&&(i=e.code),e&&e.reason)try{const i=JSON.parse(e.reason);t=i.reason,s=i.reconnect}catch(n){t=e.reason,(i>=3500&&i<4e3||i>=4500&&i<5e3)&&(s=!1)}i<3e3?(1009===i?(i=N.messageSizeLimit,t="message size limit exceeded",s=!1):(i=O.transportClosed,t="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!h&&a.emit("error",{type:"transport",error:{code:P.transportClosed,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(i,t,s)},onMessage:function(e){a._dataReceived(e)}},u),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),s=this;return this._call(t,e).then(e=>{const t=e.reply.connect;s._connectResponse(t),e.next&&e.next()},e=>{s._connectError(e.error),e.next&&e.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const e=""===this._token;if(!(this._refreshRequired||e&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(e=>{this._isConnecting()&&(this._data=e,this._initializeTransport())}).catch(e=>this._handleGetDataError(e)):this._initializeTransport());const t=this;this._getToken().then(function(e){t._isConnecting()&&(null!=e&&null!=e?(t._token=e,t._debug("connection token refreshed"),t._config.getData?t._config.getData().then(function(e){t._isConnecting()&&(t._data=e,t._initializeTransport())}).catch(e=>t._handleGetDataError(e)):t._initializeTransport()):t._failUnauthorized())}).catch(function(e){if(!t._isConnecting())return;if(e instanceof le)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:P.clientConnectToken,message:void 0!==e?e.toString():""}});const s=t._getReconnectDelay();t._debug("error on getting connection token, reconnect after "+s+" milliseconds",e),t._reconnecting=!1,t._reconnectTimeout=setTimeout(()=>{t._startReconnecting()},s)})}_handleGetDataError(e){if(e instanceof le)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:P.badConfiguration,message:(null==e?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===W.Connecting&&(109===e.code&&(this._refreshRequired=!0),e.code<100||!0===e.temporary||109===e.code?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let s=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;const e={recover:!0};this._serverSubs[i].offset&&(e.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(e.epoch=this._serverSubs[i].epoch),t[i]=e}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const s={channel:e};return void 0!==t&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),void 0!==t.limit&&(s.limit=t.limit),!0===t.reverse&&(s.reverse=!0)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const s=setTimeout(function(){t({code:P.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((s,i)=>{this._call(e,!1).then(e=>{var i;const n=t(e.reply);s(n),null===(i=e.next)||void 0===i||i.call(e)},e=>{var t;i(e.error),null===(t=e.next)||void 0===t||t.call(e)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let e;this._dispatchPromise=new Promise(t=>{e=t}),this._dispatchSynchronized(t,e)})}_dispatchSynchronized(e,t){let s=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(s=s.then(()=>this._dispatchReply(e[i])));s=s.then(()=>{t()})}_dispatchReply(e){let t;const s=new Promise(e=>{t=e});if(null==e)return this._debug("dispatch: got undefined or null reply"),t(),s;const i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise((s,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(W.Connecting)&&this.emit("connecting",{code:O.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const n={code:e,reason:t};let o=!1;if(s?o=this._setState(W.Connecting):(o=this._setState(W.Disconnected),this._rejectPromises({code:P.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===W.Connecting&&this._clearReconnectTimeout(),i===W.Connected&&this._clearConnectedState(),o&&(this._isConnecting()?this.emit("connecting",n):this.emit("disconnected",n)),this._transport){this._debug("closing existing transport");const e=this._transport;this._transport=null,e.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(N.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:P.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new le("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(s){if(e!==t._client)return;if(!s)return void t._failUnauthorized();if(t._token=s,t._debug("connection token refreshed"),!t._isConnected())return;const i={refresh:{token:t._token}};t._call(i,!1).then(e=>{const s=e.reply.refresh;t._refreshResponse(s),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){t._isConnected()&&(e instanceof le?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:P.clientRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())))})}_refreshError(e){e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return Q(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),G(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const t={unsubscribe:{channel:e.channel}},s=this;return new Promise((e,i)=>{this._call(t,!1).then(t=>{e(),t.next&&t.next()},t=>{e(),t.next&&t.next(),s._disconnect(O.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const e in this._subs)if(this._subs.hasOwnProperty(e)){const s=this._subs[e];if(s._id===t)return s}return null}const s=this._subs[e];return s||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const s=this._subs[t];if(!0!==s._inflight&&s.state===$.Subscribing){const t=s._subscribe();t&&e.push(t)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(W.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),G(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=!0===e.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||!1};const i=this._getSubscribeContext(t,s);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];if(s.recovered){const e=s.publications;if(e&&e.length>0)for(const s in e)e.hasOwnProperty(s)&&this._handlePublication(t,e[s])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(O.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const s={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(s.recovered=!0),t.positioned&&(s.positioned=!0),t.recoverable&&(s.recoverable=!0),t.was_recovering&&(s.wasRecovering=!0);let i="";"epoch"in t&&(i=t.epoch);let n=0;return"offset"in t&&(n=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:n,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(s.hasRecoveredPublications=!0),t.data&&(s.data=t.data),s}_handleReply(e,t){const s=e.id;if(!(s in this._callbacks))return void t();const i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],"error"in(n=e)&&null!==n.error){const s=i.errback;if(!s)return void t();s({error:{code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1},next:t})}else{const s=i.callback;if(!s)return;s({reply:e,next:t})}var n}_handleJoin(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handleJoin(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",s)}}_handleLeave(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handleLeave(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",s)}}_handleUnsubscribe(e,t){const s=this._getSub(e,0);s||!e?t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):s._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){const s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);const i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handlePublication(t);else if(this._isServerSub(e)){const s=this._getPublicationContext(e,t);this.emit("publication",s),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const e={};this._transportSendCommands([e])}e()}_handlePush(e,t){const s=e.channel,i=e.id;e.pub?this._handlePublication(s,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join,i):e.leave?this._handleLeave(s,e.leave,i):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){const i={code:e,message:t};return s&&(i.temporary=!0),i}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],J(s)&&s({error:this._createErrorObject(P.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}he.SubscriptionState=$,he.State=W,he.UnauthorizedError=le;class de{constructor(e,s){t(this,"config"),t(this,"events"),t(this,"client",null),t(this,"personalSub",null),t(this,"userId",null),t(this,"getTokenCallback",null),this.config=e,this.events=s}setTokenRefreshCallback(e){this.getTokenCallback=e}connect(e,t){var s;if("connected"===(null==(s=this.client)?void 0:s.state))return void this.log("Already connected");this.userId=e;const i=this.getWebSocketUrl(),n={token:t,debug:this.config.debug};this.getTokenCallback&&(n.getToken=async()=>{this.log("Token refresh requested by Centrifugo");try{const e=await this.getTokenCallback();return this.log("Token refreshed successfully"),e}catch(e){throw this.log("Token refresh failed:",e),e}}),this.client=new he(i,n),this.setupClientEventListeners(),this.client.connect()}getWebSocketUrl(){if(this.config.centrifugoUrl)return this.config.centrifugoUrl;const e=new URL(this.config.apiBase);return`${"https:"===e.protocol?"wss:":"ws:"}//${e.host}/connection/websocket`}setupClientEventListeners(){this.client&&(this.client.on("connected",e=>{this.log("Connected to Centrifugo:",e),this.events.emit("connection:open",{clientId:e.client}),this.subscribeToPersonalChannel()}),this.client.on("disconnected",e=>{this.log("Disconnected from Centrifugo:",e),this.events.emit("connection:close",{reason:e.reason,code:e.code})}),this.client.on("error",e=>{var t;this.log("Connection error:",e),this.events.emit("connection:error",{error:(null==(t=e.error)?void 0:t.message)||"Unknown error"})}),this.client.on("connecting",e=>{this.log("Connecting...",e)}))}subscribeToPersonalChannel(){if(!this.client||!this.userId)return;const e=`visitor:${this.userId}`;this.log("Subscribing to channel:",e),this.personalSub=this.client.newSubscription(e),this.personalSub.on("publication",e=>{this.handleMessage(e.data)}),this.personalSub.on("subscribed",t=>{this.log("Subscribed to channel:",e,t)}),this.personalSub.on("error",e=>{var t;this.log("Subscription error:",e),this.events.emit("error",{type:"subscription",error:null==(t=e.error)?void 0:t.message})}),this.personalSub.subscribe()}handleMessage(e){this.log("Received message:",e);const t=e.data||e;switch(e.type){case"new_message":const s={id:t.id,body:t.body,inbound:t.inbound||!1,outbound:t.outbound||!1,createdAt:t.createdAt,type:t.type||"text",mediaUrl:t.mediaUrl};this.events.emit("message:received",{ticketId:t.ticketId,message:s});break;case"typing":t.isTyping?this.events.emit("typing:start",{ticketId:t.ticketId,actor:t.senderType||"agent"}):this.events.emit("typing:stop",{ticketId:t.ticketId,actor:t.senderType||"agent"});break;case"ticket_created":this.events.emit("conversation:started",{ticketId:t.ticketId,contactId:t.contactId,createdAt:t.createdAt});break;case"ticket_status":this.events.emit("conversation:updated",{ticketId:t.ticketId,status:t.status,chatOpen:t.chatOpen});break;default:this.log("Unknown message type:",e.type)}}updateToken(e){this.client&&this.client.setToken(e)}disconnect(){this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client&&(this.client.disconnect(),this.client=null),this.userId=null}isConnected(){var e;return"connected"===(null==(e=this.client)?void 0:e.state)}getUserId(){return this.userId}log(...e){this.config.debug&&console.log("[CevroMessenger WS]",...e)}}function ue(e,t,s){const i=document.createElement(e);return t&&Object.entries(t).forEach(([e,t])=>{"className"===e?i.className=t:e.startsWith("data-")||e.startsWith("aria-")?i.setAttribute(e,t):i[e]=t}),s&&s.forEach(e=>{"string"==typeof e?i.appendChild(document.createTextNode(e)):i.appendChild(e)}),i}function pe(e){if(!e||"string"!=typeof e)return!1;try{const t=new URL(e,window.location.origin);return["http:","https:","blob:"].includes(t.protocol)}catch{return!1}}function ge(e){return function(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>").replace(/\[(.+?)\]\((.+?)\)/g,(e,t,s)=>{const i=function(e){return pe(e)?e:""}(s);return i?`<a href="${i}" target="_blank" rel="noopener">${t}</a>`:t}).replace(/\n/g,"<br>")}function me(e,t=!0){e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"})}function _e(){return"cevro_"+Math.random().toString(36).substring(2,9)}class fe{constructor(e,s){t(this,"config"),t(this,"element",null),t(this,"unreadBadge",null),t(this,"onClick"),this.config=e,this.onClick=s}render(){if(this.element)return this.element;this.element=ue("div",{className:"cevro-launcher",id:_e()}),this.applyPositioning();const e=ue("button",{className:"cevro-launcher__button","aria-label":"Open chat","data-testid":"launcher-button"}),t=this.createChatIcon();t.classList.add("cevro-launcher__icon","cevro-launcher__icon--chat"),e.appendChild(t);const s=this.createCloseIcon();return s.classList.add("cevro-launcher__icon","cevro-launcher__icon--close"),e.appendChild(s),this.unreadBadge=ue("span",{className:"cevro-launcher__badge","data-testid":"unread-badge"}),this.unreadBadge.style.display="none",e.appendChild(this.unreadBadge),e.addEventListener("click",()=>{this.onClick()}),this.element.appendChild(e),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,s=this.config.horizontalPadding??20;this.element.style.bottom=`${t}px`,"left"===e?(this.element.style.left=`${s}px`,this.element.style.right="auto"):(this.element.style.right=`${s}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex))}createChatIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","24"),e.setAttribute("height","24"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"),e.appendChild(t),e}createCloseIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","24"),e.setAttribute("height","24"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","polyline");return t.setAttribute("points","6 9 12 15 18 9"),e.appendChild(t),e}setOpen(e){this.element&&this.element.classList.toggle("cevro-launcher--open",e)}setUnreadCount(e){this.unreadBadge&&(e>0?(this.unreadBadge.textContent=e>99?"99+":String(e),this.unreadBadge.style.display="flex"):this.unreadBadge.style.display="none")}show(){this.element&&(this.element.style.display="block")}hide(){this.element&&(this.element.style.display="none")}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.unreadBadge=null}}class be{constructor(){t(this,"element",null),t(this,"messagesContainer",null),t(this,"messages",new Map),t(this,"onQuickAction",null),t(this,"autoScroll",!0),t(this,"closedMessageElement",null)}setQuickActionHandler(e){this.onQuickAction=e}render(){return this.element||(this.element=ue("div",{className:"cevro-messages",id:_e()}),this.messagesContainer=ue("div",{className:"cevro-messages__container","data-testid":"messages-container"}),this.messagesContainer.addEventListener("scroll",()=>{this.autoScroll=function(e,t=50){return e.scrollHeight-e.scrollTop-e.clientHeight<t}(this.messagesContainer)}),this.element.appendChild(this.messagesContainer)),this.element}addMessage(e,t=!0){if(!this.messagesContainer)return;if(this.messages.has(e.id))return void this.updateMessage(e);const s=this.createMessageElement(e);t&&s.classList.add("cevro-message--animate"),this.messagesContainer.appendChild(s),this.messages.set(e.id,s),this.autoScroll&&me(this.messagesContainer)}updateMessage(e,t){const s=t||e.id,i=this.messages.get(s);if(!i||!this.messagesContainer)return;const n=this.createMessageElement(e);this.messagesContainer.replaceChild(n,i),t&&t!==e.id&&this.messages.delete(t),this.messages.set(e.id,n)}updateMessageProgress(e,t){const s=this.messages.get(e);if(!s)return;const i=s.querySelector(".cevro-file-progress__fill"),n=s.querySelector(".cevro-file-progress__text");i&&(i.style.width=`${t}%`),n&&(n.textContent=`${t}%`)}removeMessage(e){const t=this.messages.get(e);t&&(t.remove(),this.messages.delete(e))}createMessageElement(e){var t,s,i,n;const o=!0===e.inbound,r=ue("div",{className:"cevro-message "+(o?"cevro-message--outbound":"cevro-message--inbound"),"data-message-id":e.id,"data-testid":`message-${e.id}`});if(!o){const e=ue("div",{className:"cevro-message__avatar"});e.innerHTML=this.createBotAvatarSvg(),r.appendChild(e)}const a=ue("div",{className:"cevro-message__content-wrapper"}),c=ue("div",{className:"cevro-message__bubble"}),l="image"===e.type||"image"===(null==(t=e.attachment)?void 0:t.category);if(l&&e.mediaUrl&&pe(e.mediaUrl)){const t=ue("div",{className:"cevro-message__image-container"}),i=ue("img",{className:"cevro-message__image"});if(i.src=e.mediaUrl,i.alt=(null==(s=e.attachment)?void 0:s.filename)||"Image",i.loading="lazy",t.appendChild(i),"sending"===e.status){const e=this.createProgressOverlay();t.appendChild(e)}c.appendChild(t)}else if("file"===e.type||e.attachment&&!l){const t=this.createFileCard(e);c.appendChild(t)}else if("media"===e.type&&e.mediaUrl&&pe(e.mediaUrl)){const t=ue("a",{className:"cevro-message__attachment"});t.href=e.mediaUrl,t.target="_blank",t.rel="noopener",t.innerHTML=`\n ${this.getFileIcon("file")}\n <span>Attachment</span>\n `,c.appendChild(t)}if(e.body){const t=ue("div",{className:"cevro-message__text"});t.innerHTML=ge(e.body),c.appendChild(t)}if(a.appendChild(c),null==(n=null==(i=e.richContent)?void 0:i.quickActions)?void 0:n.length){const t=ue("div",{className:"cevro-message__quick-actions"});e.richContent.quickActions.forEach(e=>{const s=ue("button",{className:"cevro-message__quick-action"});s.textContent=e.label,s.addEventListener("click",()=>{this.onQuickAction&&this.onQuickAction(e)}),t.appendChild(s)}),a.appendChild(t)}const h=ue("div",{className:"cevro-message__meta"});var d;if(h.textContent=("string"==typeof(d=e.createdAt)?new Date(d):d).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o&&e.status){const t=ue("span",{className:`cevro-message__status cevro-message__status--${e.status}`});t.innerHTML=this.getStatusIcon(e.status),h.appendChild(t)}return a.appendChild(h),r.appendChild(a),r}createProgressOverlay(){const e=ue("div",{className:"cevro-file-progress-overlay"});return e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',e}createFileCard(e){const t=e.attachment,s=(null==t?void 0:t.category)||"file",i=(null==t?void 0:t.filename)||"File",n=(null==t?void 0:t.size)||0,o="sending"===e.status,r=ue("div",{className:`cevro-file-card cevro-file-card--${s}`}),a=ue("div",{className:"cevro-file-card__icon"});a.innerHTML=this.getFileIcon(s),r.appendChild(a);const c=ue("div",{className:"cevro-file-card__info"}),l=ue("div",{className:"cevro-file-card__name"});l.textContent=this.truncateFilename(i,25),l.title=i,c.appendChild(l);const h=ue("div",{className:"cevro-file-card__details"});if(h.textContent=this.formatFileSize(n),c.appendChild(h),r.appendChild(c),o){const e=ue("div",{className:"cevro-file-card__progress"});e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',r.appendChild(e)}else e.mediaUrl&&pe(e.mediaUrl)&&(r.style.cursor="pointer",r.addEventListener("click",()=>{window.open(e.mediaUrl,"_blank")}));return r}getFileIcon(e){const t={pdf:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#E53935"/>\n <path d="M14 2V8H20" fill="#FFCDD2"/>\n <path d="M9 13H10.5V14.5H9V16H7.5V11H10.5V12.5H9V13Z" fill="white"/>\n <path d="M11.5 11H13.5C14.05 11 14.5 11.45 14.5 12V14C14.5 14.55 14.05 15 13.5 15H12.5V16H11.5V11ZM13 14V12H12.5V14H13Z" fill="white"/>\n <path d="M15.5 11H17V12H16V13H17V14H16V16H15.5V11Z" fill="white"/>\n </svg>',document:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#1976D2"/>\n <path d="M14 2V8H20" fill="#BBDEFB"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15Z" fill="white"/>\n </svg>',spreadsheet:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#388E3C"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <path d="M8 12H10V14H8V12ZM11 12H13V14H11V12ZM14 12H16V14H14V12ZM8 15H10V17H8V15ZM11 15H13V17H11V15Z" fill="white"/>\n </svg>',presentation:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#F57C00"/>\n <path d="M14 2V8H20" fill="#FFE0B2"/>\n <rect x="8" y="12" width="8" height="5" rx="1" fill="white"/>\n </svg>',video:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#7B1FA2"/>\n <path d="M14 2V8H20" fill="#E1BEE7"/>\n <path d="M10 11V17L15 14L10 11Z" fill="white"/>\n </svg>',audio:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#00897B"/>\n <path d="M14 2V8H20" fill="#B2DFDB"/>\n <path d="M12 11C10.9 11 10 11.9 10 13V15C10 16.1 10.9 17 12 17C13.1 17 14 16.1 14 15V13C14 11.9 13.1 11 12 11Z" fill="white"/>\n <path d="M15 14V15C15 16.66 13.66 18 12 18C10.34 18 9 16.66 9 15V14H8V15C8 17.03 9.53 18.71 11.5 18.96V20H10V21H14V20H12.5V18.96C14.47 18.71 16 17.03 16 15V14H15Z" fill="white"/>\n </svg>',archive:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#795548"/>\n <path d="M14 2V8H20" fill="#D7CCC8"/>\n <rect x="10" y="11" width="4" height="2" fill="white"/>\n <rect x="10" y="14" width="4" height="2" fill="white"/>\n <rect x="10" y="17" width="4" height="2" fill="white"/>\n </svg>',text:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#607D8B"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15ZM8 18H16V19H8V18Z" fill="white"/>\n </svg>',image:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#43A047"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <circle cx="10" cy="13" r="2" fill="white"/>\n <path d="M8 18L10 15L12 17L15 13L17 18H8Z" fill="white"/>\n </svg>',file:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#90A4AE"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n </svg>'};return t[e]||t.file}formatFileSize(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}truncateFilename(e,t){if(e.length<=t)return e;const s=e.split(".").pop()||"";return e.slice(0,e.length-s.length-1).slice(0,t-s.length-4)+"..."+"."+s}createBotAvatarSvg(){return'\n <svg width="32" height="32" viewBox="0 0 32 32" fill="none">\n <circle cx="16" cy="16" r="16" fill="currentColor"/>\n <path d="M16 8C11.582 8 8 11.582 8 16s3.582 8 8 8 8-3.582 8-8-3.582-8-8-8zm0 14.5c-3.59 0-6.5-2.91-6.5-6.5s2.91-6.5 6.5-6.5 6.5 2.91 6.5 6.5-2.91 6.5-6.5 6.5z" fill="white"/>\n <circle cx="13" cy="14" r="1.5" fill="white"/>\n <circle cx="19" cy="14" r="1.5" fill="white"/>\n <path d="M16 19c1.657 0 3-1.343 3-3h-6c0 1.657 1.343 3 3 3z" fill="white"/>\n </svg>\n '}getStatusIcon(e){switch(e){case"sending":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';case"sent":case"delivered":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"read":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="#8B5CF6" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"failed":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>';default:return""}}showTypingIndicator(){if(!this.messagesContainer)return;this.hideTypingIndicator();const e=ue("div",{className:"cevro-typing-indicator",id:"cevro-typing-indicator","data-testid":"typing-indicator"});e.innerHTML=`\n <div class="cevro-typing-indicator__avatar">\n ${this.createBotAvatarSvg()}\n </div>\n <div class="cevro-typing-indicator__dots">\n <span></span>\n <span></span>\n <span></span>\n </div>\n `,this.messagesContainer.appendChild(e),this.autoScroll&&me(this.messagesContainer)}hideTypingIndicator(){const e=document.getElementById("cevro-typing-indicator");e&&e.remove()}clear(){this.messagesContainer&&(this.messagesContainer.innerHTML=""),this.messages.clear(),this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}showClosedMessage(){this.messagesContainer&&(this.hideClosedMessage(),this.closedMessageElement=ue("div",{className:"cevro-messages__closed-notice","data-testid":"closed-chat-message"}),this.closedMessageElement.innerHTML='\n <p class="cevro-messages__closed-text">\n The agent closed the chat. If you need assistance please start a new chat.\n </p>\n ',this.messagesContainer.appendChild(this.closedMessageElement),this.autoScroll&&me(this.messagesContainer))}hideClosedMessage(){this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}scrollToBottom(){this.messagesContainer&&me(this.messagesContainer,!1)}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.messagesContainer=null,this.messages.clear()}}class ve{constructor(e,s){t(this,"config"),t(this,"callbacks"),t(this,"element",null),t(this,"messageList"),t(this,"inputElement",null),t(this,"sendButton",null),t(this,"fileInput",null),t(this,"fileButton",null),t(this,"isVisible",!1),t(this,"agentAvatarElement",null),t(this,"agentNameElement",null),t(this,"inputWrapper",null),t(this,"closedFooter",null),t(this,"themeMediaQuery",null),t(this,"themeChangeHandler",null),this.config=e,this.callbacks=s,this.messageList=new be,this.messageList.setQuickActionHandler(e=>{this.callbacks.onQuickAction(e)})}render(){if(this.element)return this.element;this.element=ue("div",{className:"cevro-chat-window",id:_e()}),this.applyPositioning();const e=this.createHeader();this.element.appendChild(e);const t=this.messageList.render();return this.element.appendChild(t),this.inputWrapper=this.createInputArea(),this.element.appendChild(this.inputWrapper),this.applyTheme(),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,s=this.config.horizontalPadding??20;this.element.style.bottom=`${t+70}px`,"left"===e?(this.element.style.left=`${s}px`,this.element.style.right="auto"):(this.element.style.right=`${s}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex-1))}createHeader(){const e=ue("div",{className:"cevro-chat-window__header"});this.agentAvatarElement=ue("div",{className:"cevro-chat-window__agent-avatar","data-testid":"agent-avatar"}),this.agentAvatarElement.innerHTML=this.createDefaultAvatarSvg(),e.appendChild(this.agentAvatarElement);const t=ue("div",{className:"cevro-chat-window__title-section"});this.agentNameElement=ue("h2",{className:"cevro-chat-window__title","data-testid":"agent-name"},["Support"]);const s=ue("p",{className:"cevro-chat-window__subtitle"},["We typically reply within a few minutes"]);t.appendChild(this.agentNameElement),t.appendChild(s),e.appendChild(t);const i=ue("button",{className:"cevro-chat-window__close","aria-label":"Close chat","data-testid":"close-button"});return i.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"/>\n <line x1="6" y1="6" x2="18" y2="18"/>\n </svg>\n ',i.addEventListener("click",()=>{this.callbacks.onClose()}),e.appendChild(i),e}createDefaultAvatarSvg(){return'\n <svg width="40" height="40" viewBox="0 0 40 40" fill="none">\n <circle cx="20" cy="20" r="20" fill="rgba(255,255,255,0.2)"/>\n <path d="M20 10C14.477 10 10 14.477 10 20s4.477 10 10 10 10-4.477 10-10-4.477-10-10-10zm0 18c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8z" fill="white"/>\n <circle cx="16" cy="17" r="2" fill="white"/>\n <circle cx="24" cy="17" r="2" fill="white"/>\n <path d="M20 24c2.071 0 3.75-1.679 3.75-3.75h-7.5c0 2.071 1.679 3.75 3.75 3.75z" fill="white"/>\n </svg>\n '}setAgent(e){if(this.agentNameElement&&e.name&&(this.agentNameElement.textContent=e.name),this.agentAvatarElement&&e.avatarUrl&&pe(e.avatarUrl)){this.agentAvatarElement.innerHTML="";const t=ue("img",{className:"cevro-chat-window__agent-avatar-img"});t.src=e.avatarUrl,t.alt=e.name||"Agent",this.agentAvatarElement.appendChild(t)}}createInputArea(){var e;const t=ue("div",{className:"cevro-chat-window__input-wrapper"}),s=ue("div",{className:"cevro-chat-window__input-area"});this.fileButton=ue("button",{className:"cevro-chat-window__file-button","aria-label":"Attach file","data-testid":"file-button"}),this.fileButton.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M16.5 6V17.5C16.5 19.71 14.71 21.5 12.5 21.5C10.29 21.5 8.5 19.71 8.5 17.5V5C8.5 3.62 9.62 2.5 11 2.5C12.38 2.5 13.5 3.62 13.5 5V16.5C13.5 17.05 13.05 17.5 12.5 17.5C11.95 17.5 11.5 17.05 11.5 16.5V6H10V16.5C10 17.88 11.12 19 12.5 19C13.88 19 15 17.88 15 16.5V5C15 2.79 13.21 1 11 1C8.79 1 7 2.79 7 5V17.5C7 20.54 9.46 23 12.5 23C15.54 23 18 20.54 18 17.5V6H16.5Z" fill="currentColor"/>\n </svg>\n ',this.fileInput=ue("input",{className:"cevro-chat-window__file-input"}),this.fileInput.type="file",this.fileInput.accept=(null==(e=this.config.fileUpload)?void 0:e.allowedMimeTypes)?this.config.fileUpload.allowedMimeTypes.join(","):function(e=r){const t=[];return e.forEach(e=>{t.push(e)}),t.join(",")}(),this.fileInput.addEventListener("change",()=>{var e,t;(null==(t=null==(e=this.fileInput)?void 0:e.files)?void 0:t.length)&&this.callbacks.onFileUpload&&(this.callbacks.onFileUpload(this.fileInput.files[0]),this.fileInput.value="")}),this.fileButton.addEventListener("click",()=>{var e;null==(e=this.fileInput)||e.click()}),s.appendChild(this.fileButton),s.appendChild(this.fileInput),this.inputElement=ue("textarea",{className:"cevro-chat-window__input","data-testid":"chat-input"}),this.inputElement.placeholder="How can we help",this.inputElement.rows=1,this.inputElement.addEventListener("input",()=>{this.inputElement&&(this.inputElement.style.height="auto",this.inputElement.style.height=Math.min(this.inputElement.scrollHeight,100)+"px",this.updateSendButtonState())}),this.inputElement.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSend())}),s.appendChild(this.inputElement),this.sendButton=ue("button",{className:"cevro-chat-window__send-button","aria-label":"Send message","data-testid":"send-button"}),this.sendButton.disabled=!0,this.sendButton.innerHTML='\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 19V5M5 12L12 5L19 12" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.sendButton.addEventListener("click",()=>{this.handleSend()}),s.appendChild(this.sendButton),t.appendChild(s);const i=ue("div",{className:"cevro-chat-window__footer"});return i.innerHTML='Powered by <a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>',t.appendChild(i),t}handleSend(){if(!this.inputElement)return;const e=this.inputElement.value.trim();e&&(this.callbacks.onSendMessage(e),this.inputElement.value="",this.inputElement.style.height="auto",this.updateSendButtonState(),this.inputElement.focus())}updateSendButtonState(){this.sendButton&&this.inputElement&&(this.sendButton.disabled=!this.inputElement.value.trim())}applyTheme(){if(!this.element)return;const e=this.config.theme||"light";if(this.cleanupThemeListener(),"system"===e){this.themeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");const e=this.themeMediaQuery.matches;this.element.classList.toggle("cevro-chat-window--dark",e),this.themeChangeHandler=e=>{var t;null==(t=this.element)||t.classList.toggle("cevro-chat-window--dark",e.matches)},this.themeMediaQuery.addEventListener("change",this.themeChangeHandler)}else this.element.classList.toggle("cevro-chat-window--dark","dark"===e)}cleanupThemeListener(){this.themeMediaQuery&&this.themeChangeHandler&&(this.themeMediaQuery.removeEventListener("change",this.themeChangeHandler),this.themeMediaQuery=null,this.themeChangeHandler=null)}addMessage(e,t=!0){this.messageList.addMessage(e,t)}updateMessage(e,t){this.messageList.updateMessage(e,t)}updateMessageProgress(e,t){this.messageList.updateMessageProgress(e,t)}removeMessage(e){this.messageList.removeMessage(e)}showTypingIndicator(){this.messageList.showTypingIndicator()}hideTypingIndicator(){this.messageList.hideTypingIndicator()}clearMessages(){this.messageList.clear()}show(){var e;this.element&&(this.element.classList.add("cevro-chat-window--visible"),this.isVisible=!0,null==(e=this.inputElement)||e.focus(),this.messageList.scrollToBottom())}hide(){this.element&&(this.element.classList.remove("cevro-chat-window--visible"),this.isVisible=!1)}isWindowVisible(){return this.isVisible}focusInput(){var e;null==(e=this.inputElement)||e.focus()}setTicketClosed(e,t,s){const i=(null==s?void 0:s.showHistory)??!1;if(e){if(i||this.messageList.clear(),this.inputWrapper&&(this.inputWrapper.style.display="none"),this.messageList.showClosedMessage(),!this.closedFooter&&this.element){this.closedFooter=ue("div",{className:"cevro-chat-window__closed-footer"});const e=ue("button",{className:"cevro-chat-window__new-chat-button"},["New Conversation"]);e.addEventListener("click",()=>{t&&t()});const s=ue("div",{className:"cevro-chat-window__powered-by"},["Powered by Cevro AI"]);this.closedFooter.appendChild(e),this.closedFooter.appendChild(s),this.element.appendChild(this.closedFooter)}}else this.inputWrapper&&(this.inputWrapper.style.display=""),this.messageList.hideClosedMessage(),this.closedFooter&&this.closedFooter.parentNode&&(this.closedFooter.parentNode.removeChild(this.closedFooter),this.closedFooter=null)}destroy(){this.cleanupThemeListener(),this.messageList.destroy(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.inputElement=null,this.sendButton=null,this.fileInput=null,this.fileButton=null,this.closedFooter=null}}const we=class e{constructor(i){t(this,"config"),t(this,"events"),t(this,"api"),t(this,"ws"),t(this,"launcher",null),t(this,"chatWindow",null),t(this,"container",null),t(this,"isBooted",!1),t(this,"isVisible",!1),t(this,"unreadCount",0),t(this,"visitorId"),t(this,"isSessionInitialized",!1),t(this,"isInitializingSession",null),t(this,"connectingPromise",null),t(this,"typingCycleTimeout",null),t(this,"isTypingVisible",!1),t(this,"typingConfig",{onDurationMs:7e3,offDurationMs:4e3}),this.config=this.normalizeConfig(i),this.events=new s,this.api=new u(this.config),this.ws=new de(this.config,this.events),this.visitorId=o(),this.ws.setTokenRefreshCallback(async()=>this.refreshConnectionToken()),this.setupEventHandlers(),e.instance=this,this.log("Initialized with config:",this.config)}static getInstance(){return e.instance}normalizeConfig(e){return{...e,apiBase:e.apiBase.replace(/\/$/,""),alignment:e.alignment||"right",verticalPadding:e.verticalPadding??20,horizontalPadding:e.horizontalPadding??20,theme:e.theme||"light",zIndex:e.zIndex??2147483647,debug:e.debug??!1}}setupEventHandlers(){this.events.on("message:received",e=>{this.log("Received message:",e),this.stopTypingCycle(),this.chatWindow&&this.chatWindow.addMessage(e.message),this.isVisible||this.setUnreadCount(this.unreadCount+1)}),this.events.on("typing:start",e=>{this.log("Typing started:",e),e.ticketId===this.api.getCurrentTicketId()&&this.startTypingCycle()}),this.events.on("typing:stop",e=>{this.log("Typing stopped:",e),this.stopTypingCycle()}),this.events.on("conversation:started",e=>{this.log("Conversation started:",e)}),this.events.on("conversation:updated",e=>{this.log("Conversation updated:",e)}),this.events.on("connection:open",()=>{this.log("WebSocket connected")}),this.events.on("connection:close",()=>{this.log("WebSocket disconnected")}),this.events.on("connection:error",e=>{this.log("WebSocket error:",e.error)})}boot(){if(this.isBooted)return void this.log("Already booted");if(this.log("Booting..."),this.container=document.createElement("div"),this.container.id="cevro-messenger-container",document.body.appendChild(this.container),this.config.hideDefaultLauncher||(this.launcher=new fe(this.config,()=>this.toggle()),this.container.appendChild(this.launcher.render())),this.config.customLauncherSelector){const e=document.querySelector(this.config.customLauncherSelector);e&&e.addEventListener("click",()=>this.toggle())}this.chatWindow=new ve(this.config,{onClose:()=>this.hide(),onSendMessage:e=>this.sendMessage(e),onQuickAction:e=>this.handleQuickAction(e),onFileUpload:e=>this.handleFileUpload(e)}),this.container.appendChild(this.chatWindow.render());const e=function(){try{const e=localStorage.getItem("cevro_session");return e?JSON.parse(e):null}catch{return null}}();(null==e?void 0:e.ticketId)&&this.api.setCurrentTicketId(e.ticketId),this.isBooted=!0,this.events.emit("boot"),this.log("Booted successfully")}async connectWebSocket(){return this.connectingPromise?(this.log("Already connecting to WebSocket, waiting..."),this.connectingPromise):(this.connectingPromise=this.doConnectWebSocket(),this.connectingPromise)}async doConnectWebSocket(){try{this.log("Fetching Centrifugo connection token...");const e=i(),t=await this.api.getConnectionToken(e);this.visitorId=t.visitorId,this.log("Visitor:",t.visitorId),t.visitorToken&&(n(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),this.log("Got connection token, connecting to Centrifugo..."),this.ws.connect(t.visitorId,t.token),this.events.emit("ready")}catch(e){this.log("Failed to connect to WebSocket:",e),this.events.emit("ready"),this.events.emit("error",{type:"websocket_connect",error:e})}finally{this.connectingPromise=null}}async refreshConnectionToken(){this.log("Refreshing Centrifugo connection token...");const e=i(),t=await this.api.getConnectionToken(e);return t.visitorToken&&(n(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),this.log("Token refreshed for visitor:",t.visitorId),t.token}shutdown(e){var t,s;this.isBooted&&(this.log("Shutting down..."),this.stopTypingCycle(),this.ws.disconnect(),null==(t=this.launcher)||t.destroy(),null==(s=this.chatWindow)||s.destroy(),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),function(){try{localStorage.removeItem("cevro_session")}catch{}}(),(null==e?void 0:e.clearVisitorData)&&(!function(){try{localStorage.removeItem("cevro_visitor_token")}catch{}}(),this.visitorId=null),this.api.clear(),this.launcher=null,this.chatWindow=null,this.container=null,this.isBooted=!1,this.isVisible=!1,this.unreadCount=0,this.isSessionInitialized=!1,this.isInitializingSession=null,this.connectingPromise=null,this.events.emit("shutdown"),this.log("Shutdown complete"))}async update(e){var t;const s=!!(null==(t=this.config.player)?void 0:t.playerId);this.config.player={...this.config.player,...e},this.log("Player data updated:",this.config.player),!s&&e.playerId&&this.isSessionInitialized&&(this.log("Player ID added, re-initializing session for merge..."),this.isSessionInitialized=!1,await this.initializeSession())}async show(){var e;this.isBooted||this.boot(),this.chatWindow&&(this.chatWindow.show(),this.isVisible=!0,null==(e=this.launcher)||e.setOpen(!0),this.setUnreadCount(0),this.events.emit("show"),await this.connectWebSocket(),await this.initializeSession())}async initializeSession(e=!1){if(e&&(this.isSessionInitialized=!1,this.isInitializingSession=null),this.isSessionInitialized)return;if(this.isInitializingSession)return this.isInitializingSession;const t=this.doInitializeSession().finally(()=>{this.isInitializingSession===t&&(this.isInitializingSession=null)});return this.isInitializingSession=t,t}async doInitializeSession(e){var t,s,i;this.log("Initializing session...",e);try{const n=await this.api.initSession(this.visitorId,e);if(this.log("Session initialized:",n),function(e,t,s){try{localStorage.setItem("cevro_session",JSON.stringify({sessionId:e,contactId:t,ticketId:s}))}catch{}}(n.sessionId,n.contactId,n.ticketId),this.isSessionInitialized=!0,n.agent&&this.chatWindow&&this.chatWindow.setAgent(n.agent),n.typingConfig&&(this.typingConfig=n.typingConfig,this.log("Typing config:",this.typingConfig)),n.messages&&n.messages.length>0){this.log(`Loading ${n.messages.length} existing messages`);for(const e of n.messages)null==(t=this.chatWindow)||t.addMessage(e)}n.ticketClosed&&(this.log("Ticket is closed:",n.ticketClosedReason),null==(s=this.chatWindow)||s.setTicketClosed(!0,()=>this.startNewChat())),this.events.emit("session:initialized",{sessionId:n.sessionId,contactId:n.contactId,ticketId:n.ticketId,isNewSession:n.isNewSession,isNewTicket:n.isNewTicket,ticketClosed:n.ticketClosed,messageCount:(null==(i=n.messages)?void 0:i.length)||0})}catch(n){throw this.log("Failed to initialize session:",n),this.events.emit("error",{type:"session_init",error:n}),n}}async startNewChat(){var e,t;this.log("Starting new chat..."),null==(e=this.chatWindow)||e.clearMessages(),null==(t=this.chatWindow)||t.setTicketClosed(!1),this.isSessionInitialized=!1,await this.doInitializeSession({forceNewTicket:!0}),this.events.emit("chat:new_started")}hide(){var e;this.chatWindow&&(this.chatWindow.hide(),this.isVisible=!1,null==(e=this.launcher)||e.setOpen(!1),this.events.emit("hide"))}toggle(){this.isVisible?this.hide():this.show()}async sendMessage(e){var t,s,i,n,o,r,a,c,l,h,d;if(!e.trim())return;this.log("Sending message:",e);const u={id:"temp_"+Date.now(),body:e,inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:"text",status:"sending"};null==(t=this.chatWindow)||t.addMessage(u);try{this.isSessionInitialized||await this.initializeSession();const t=u.id,i=await this.api.sendMessage(e);u.id=i.id,u.status="sent",null==(s=this.chatWindow)||s.updateMessage(u,t),this.events.emit("message:sent",{message:i})}catch(p){this.log("Error sending message:",p);if((null==(i=null==p?void 0:p.message)?void 0:i.includes("closed"))||(null==(n=null==p?void 0:p.message)?void 0:n.includes("resolved"))||(null==(o=null==p?void 0:p.message)?void 0:o.includes("escalated"))||(null==(c=null==(a=null==(r=null==p?void 0:p.response)?void 0:r.data)?void 0:a.message)?void 0:c.includes("closed")))return this.log("Conversation is closed, showing closed UI"),null==(l=this.chatWindow)||l.removeMessage(u.id),void(null==(h=this.chatWindow)||h.setTicketClosed(!0,()=>this.startNewChat()));u.status="failed",null==(d=this.chatWindow)||d.updateMessage(u),this.events.emit("error",{error:p,type:"send_message"})}}showNewMessage(e){this.show(),e&&this.chatWindow&&this.log("Pre-filling message:",e)}async handleQuickAction(e){this.log("Quick action clicked:",e),"link"===e.type&&e.url?pe(e.url)?window.open(e.url,"_blank"):this.log("Invalid URL blocked:",e.url):await this.sendMessage(e.value||e.label)}async handleFileUpload(e){var t,s,i;let n,o;this.log("File upload:",e.name,e.type,e.size);try{this.isSessionInitialized||await this.initializeSession();const i=e.type.startsWith("image/"),r=this.getFileCategory(e.type);n=i?URL.createObjectURL(e):void 0,o="temp_"+Date.now();const a={id:o,body:"",inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:i?"image":"file",mediaUrl:n,mediaType:e.type,status:"sending",attachment:{filename:e.name,contentType:e.type||"application/octet-stream",size:e.size,category:r}};null==(t=this.chatWindow)||t.addMessage(a);const c=await this.api.uploadFile(e,e=>{var t;null==(t=this.chatWindow)||t.updateMessageProgress(o,e)}),l=await this.api.sendMessage("",c),h=l.mediaUrl&&pe(l.mediaUrl),d={...l,status:"sent",type:i?"image":"file",mediaUrl:h?l.mediaUrl:n,attachment:a.attachment};null==(s=this.chatWindow)||s.updateMessage(d,o),n&&h&&URL.revokeObjectURL(n),this.events.emit("message:sent",{type:r,fileName:e.name})}catch(r){this.log("Error uploading file:",r),n&&URL.revokeObjectURL(n),o&&(null==(i=this.chatWindow)||i.removeMessage(o));const t=(null==r?void 0:r.message)||"File upload failed",s=t.includes("too large")||t.includes("too small")||t.includes("not allowed")||t.includes("Too many uploads");this.events.emit("error",{error:r,type:s?"file_validation":"file_upload",message:t,fileName:e.name})}}getFileCategory(e){return e.startsWith("image/")?"image":"application/pdf"===e?"pdf":e.includes("word")||e.includes("document")?"document":e.includes("sheet")||e.includes("excel")?"spreadsheet":e.includes("presentation")||e.includes("powerpoint")?"presentation":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":e.includes("zip")||e.includes("archive")||e.includes("compressed")?"archive":e.startsWith("text/")?"text":"file"}setUnreadCount(e){var t;this.unreadCount=e,null==(t=this.launcher)||t.setUnreadCount(e),this.events.emit("unread_count_change",{count:e})}getUnreadCount(){return this.unreadCount}getVisitorId(){return this.visitorId}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}trackEvent(e,t){this.log("Track event:",e,t)}startTypingCycle(){var e;this.stopTypingCycle();const{onDurationMs:t,offDurationMs:s}=this.typingConfig,i=()=>{var e,n;this.isTypingVisible?(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1,this.log("Typing cycle: hidden"),this.typingCycleTimeout=setTimeout(i,s)):(null==(n=this.chatWindow)||n.showTypingIndicator(),this.isTypingVisible=!0,this.log("Typing cycle: visible"),this.typingCycleTimeout=setTimeout(i,t))};null==(e=this.chatWindow)||e.showTypingIndicator(),this.isTypingVisible=!0,this.log("Typing cycle: started"),this.typingCycleTimeout=setTimeout(i,t)}stopTypingCycle(){var e;this.typingCycleTimeout&&(clearTimeout(this.typingCycleTimeout),this.typingCycleTimeout=null),this.isTypingVisible&&(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1),this.log("Typing cycle: stopped")}log(...e){this.config.debug&&console.log("[CevroMessenger]",...e)}};t(we,"instance",null);let ye=we;"undefined"!=typeof window&&(window.CevroMessenger=ye),exports.CevroMessenger=ye,exports.default=ye;
3
+ //# sourceMappingURL=index.js.map