1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4098],{14098:(e,n,t)=>{t.d(n,{v:()=>l});var i=t(91183),s=t.n(i),a=t(44155);class r{setOnMembersChange(e){this.onMembersChange=e}memberAdded(e){let n=this.pendingRemovals.get(e.id);n&&(clearTimeout(n.timeout),this.pendingRemovals.delete(e.id)),this.members.set(e.id,e),this.notifyChange()}memberRemoved(e){let n=this.members.get(e);if(!n||this.pendingRemovals.has(e))return;let t=setTimeout(()=>{this.members.delete(e),this.pendingRemovals.delete(e),this.notifyChange()},this.debounceMs);this.pendingRemovals.set(e,{member:n,timeout:t,timestamp:Date.now()})}setInitialMembers(e){this.pendingRemovals.forEach(e=>clearTimeout(e.timeout)),this.pendingRemovals.clear(),this.members.clear(),e.forEach(e=>this.members.set(e.id,e)),this.notifyChange()}getMembers(){return Array.from(this.members.values())}getMemberCount(){return this.members.size}isMemberOnline(e){return this.members.has(e)}clear(){this.pendingRemovals.forEach(e=>clearTimeout(e.timeout)),this.pendingRemovals.clear(),this.members.clear(),this.notifyChange()}forceRemove(e){let n=this.pendingRemovals.get(e);n&&(clearTimeout(n.timeout),this.pendingRemovals.delete(e)),this.members.delete(e),this.notifyChange()}notifyChange(){var e;null==(e=this.onMembersChange)||e.call(this,this.getMembers())}constructor(e=5e3,n){this.members=new Map,this.pendingRemovals=new Map,this.debounceMs=e,this.onMembersChange=n}}class o{initialize(e){if(this.pusher){let n=this.pusher.connection.state,t=!!this.config&&this.config.key===e.key&&this.config.cluster===e.cluster&&(this.config.authEndpoint||"/api/pusher/auth")===(e.authEndpoint||"/api/pusher/auth")&&(this.config.userAuthEndpoint||"/api/pusher/user-auth")===(e.userAuthEndpoint||"/api/pusher/user-auth");if(t&&("connected"===n||"connecting"===n||"initialized"===n)){a.G.debug("[PusherClient] Reusing existing instance. State:",n),this.initialized=!0;return}a.G.debug("[PusherClient] Reinitializing Pusher. Previous state:","".concat(n,", Same config: ").concat(t)),this.disconnect()}this.config=e,this.initialized=!0,this.pusher=new(s())(e.key,{cluster:e.cluster,forceTLS:!0,authEndpoint:e.authEndpoint||"/api/pusher/auth",userAuthentication:{endpoint:e.userAuthEndpoint||"/api/pusher/user-auth",transport:"ajax"},authorizer:e=>({authorize:(n,t)=>{this.authorizeChannel(e.name,n,t)}}),activityTimeout:3e4,pongTimeout:1e4,disableStats:!0,enabledTransports:["ws","wss"]}),this.setupConnectionEvents(),this.setupTokenRefreshListener(),this.setupVisibilityChangeHandler(),this.setupOnlineHandler(),this.startHealthCheck()}setupTokenRefreshListener(){this.tokenRefreshHandler&&window.removeEventListener("wizebot:auth:token-refreshed",this.tokenRefreshHandler),this.tokenRefreshHandler=e=>{var n;let t=null==(n=e.detail)?void 0:n.accessToken;t&&(a.G.debug("[PusherClient] Token refreshed externally, updating..."),this.verifyTokenIdentity(t).then(e=>{e&&(this.authToken=t,this.lastTokenHash=this.getTokenHash(t),this.authCache.clear())}))},window.addEventListener("wizebot:auth:token-refreshed",this.tokenRefreshHandler)}setupVisibilityChangeHandler(){if("undefined"==typeof document)return;this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.focusHandler&&window.removeEventListener("focus",this.focusHandler);let e=null;this.visibilityChangeHandler=()=>{if("visible"===document.visibilityState){var n;let t=null==(n=this.pusher)?void 0:n.connection.state,i=e?Date.now()-e:0;a.G.debug("[PusherClient] Page became visible, connection state:","".concat(t,", background for ").concat(i,"ms")),"disconnected"===t||"unavailable"===t||"failed"===t?(a.G.debug("[PusherClient] Connection in terminal state, calling connect()..."),this.triggerReconnect(e)):"connected"===t&&i>6e4&&!this.hasRecentServerActivity()?(a.G.debug("[PusherClient] Long background detected without recent server activity, forcing fresh reconnect"),this.forceReconnect(e)):"connected"===t&&a.G.debug("[PusherClient] Connection appears healthy after visibility change"),e=null,this.startHealthCheck()}else e=Date.now(),a.G.debug("[PusherClient] Page hidden, maintaining connection")},this.focusHandler=()=>{var e;let n=null==(e=this.pusher)?void 0:e.connection.state;("disconnected"===n||"unavailable"===n||"failed"===n)&&(a.G.debug("[PusherClient] Window focused, connection in terminal state, reconnecting..."),this.triggerReconnect(null))},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("focus",this.focusHandler)}setupOnlineHandler(){this.onlineHandler&&window.removeEventListener("online",this.onlineHandler),this.onlineHandler=()=>{var e;
1a.G.debug("[PusherClient] Network came back online, checking connection...");let n=null==(e=this.pusher)?void 0:e.connection.state;"connected"!==n&&"connecting"!==n&&setTimeout(()=>this.forceReconnect(null),1e3)},window.addEventListener("online",this.onlineHandler)}startHealthCheck(){this.stopHealthCheck(),this.lastHealthCheckTime=Date.now(),this.healthCheckInterval=setInterval(()=>{var e,n;let t=Date.now(),i=t-this.lastHealthCheckTime;if(this.lastHealthCheckTime=t,i>this.SLEEP_DETECTION_THRESHOLD)return void((null==(n=this.pusher)?void 0:n.connection.state)==="connected"&&this.hasRecentServerActivity()?a.G.debug("[PusherClient] Timer gap (".concat(i,"ms) com atividade recente do servidor â throttle de background, mantendo conex\xe3o")):(a.G.debug("[PusherClient] Possible wake from sleep detected (".concat(i,"ms gap)")),this.forceReconnect(null)));let s=null==(e=this.pusher)?void 0:e.connection.state;("disconnected"===s||"unavailable"===s||"failed"===s)&&(a.G.debug("[PusherClient] Health check: connection in ".concat(s," state, triggering reconnect")),this.triggerReconnect(null))},this.HEALTH_CHECK_INTERVAL)}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}hasRecentServerActivity(){return this.lastServerActivityAt>0&&Date.now()-this.lastServerActivityAt<this.SERVER_ACTIVITY_WINDOW}triggerReconnect(e){this.pusher&&!this.reconnecting&&(this.disconnectedAt||(this.disconnectedAt=e||Date.now()),this.authCache.clear(),this.reconnecting=!0,a.G.debug("[PusherClient] Calling connect()..."),this.safeConnect(),setTimeout(()=>{this.reconnecting=!1},2e3))}safeConnect(){if(!this.pusher)return;let e=this.pusher.connection.state;if("connected"===e||"connecting"===e)return void a.G.debug("[PusherClient] safeConnect ignorado, estado:",e);try{this.pusher.connect()}catch(n){a.G.warn("[PusherClient] connect() lan\xe7ou exce\xe7\xe3o (estado inv\xe1lido? state=".concat(e,")"),n)}}forceReconnect(e){this.pusher&&!this.reconnecting&&(this.disconnectedAt||(this.disconnectedAt=e||Date.now()),this.authCache.clear(),this.reconnecting=!0,a.G.debug("[PusherClient] Force reconnecting (disconnect + connect)..."),this.pusher.disconnect(),setTimeout(()=>{this.safeConnect(),setTimeout(()=>{this.reconnecting=!1},2e3)},300))}setupConnectionEvents(){this.pusher&&(this.pusher.connection.bind("message",()=>{this.lastServerActivityAt=Date.now()}),this.pusher.connection.bind("connected",()=>{if(a.G.debug("Pusher connected"),this.lastConnectedAt=Date.now(),this.lastServerActivityAt=Date.now(),this.disconnectedAt){let e=Date.now()-this.disconnectedAt;a.G.debug("[PusherClient] Reconnected after ".concat(e,"ms offline")),this.authCache.clear(),this.reconnectCallbacks.forEach(n=>{try{n(e)}catch(e){a.G.error("[PusherClient] Reconnect callback error",e)}}),this.disconnectedAt=null}}),this.pusher.connection.bind("disconnected",()=>{a.G.debug("Pusher disconnected"),this.authCache.clear(),this.disconnectedAt||(this.disconnectedAt=Date.now())}),this.pusher.connection.bind("error",e=>{var n,t,i;let s=(null==e||null==(t=e.error)||null==(n=t.data)?void 0:n.code)||(null==e||null==(i=e.data)?void 0:i.code);s?1006===s?a.G.debug("[PusherClient] WebSocket closed abnormally (code 1006), will auto-reconnect"):s>=4e3&&s<4100?a.G.error("[PusherClient] Fatal connection error (code ".concat(s,"), will NOT reconnect"),e):s>=4100&&s<4200?a.G.warn("[PusherClient] Temporary error (code ".concat(s,"), Pusher will reconnect with backoff")):s>=4200&&s<4300?a.G.warn("[PusherClient] Connection error (code ".concat(s,"), Pusher will reconnect immediately")):s>=1e3&&s<2e3?a.G.debug("[PusherClient] WebSocket closed (code ".concat(s,")")):a.G.error("[PusherClient] Connection error (code ".concat(s,")"),e):a.G.warn("[PusherClient] Connection error (no code)",e)}),this.pusher.connection.bind("unavailable",()=>{a.G.warn("[PusherClient] Connection unavailable (Pusher gave up auto-reconnect)"),this.disconnectedAt||(this.disconnectedAt=Date.now()),setTimeout(()=>{var e;let n=null==(e=this.pusher)?void 0:e.connection.state;("unavailable"===n||"disconnected"===n)&&(a.G.debug("[PusherClient] Attempting reconnect from unavailable state..."),this.triggerReconnect(this.disconnectedAt))},3e3)}),this.pusher.connection.bind("state_change",e=>{try{a.G.debug("[PusherClient] State change:","".concat(null==e?void 0:e.previous," -> ").concat(null==e?void 0:e.current))}catch(e){}}))}onReconnect(e){return this.reconnectCallbacks.add(e),()=>{this.reconnectCallbacks.delete(e)}}getLastConnectedAt(){return this.lastConnectedAt}getTokenHash(e){return e?e.slice(-16):""}async ensureValidToken(){let e=await this.resolveValidToken();if(e&&!await this.verifyTokenIdentity(e))throw Error("Token identity changed; session resync in progress");return e}async verifyTokenIdentity(e){if(!e||this.resyncingIdentity)return!0;let{decodeJwtPayload:n}=await Promise.resolve().then(t.bind(t,92343)),i=n(e);if(!i)return!0;let s="string"==typeof i.sub?i.sub:null,r="string"==typeof i.tenantId?i.tenantId:null,o=!!(this.tokenSub&&s&&s!==this.tokenSub),l=!!(this.tenantId&&r&&r!==this.tenantId);return o||l?(a.G.warn("[PusherClient] Identidade do token divergiu da sess\xe3o em mem\xf3ria (sub mudou: ".concat(o,", tenant mudou: ").concat(l,"), re-sincronizando")),this.resyncFromToken(e),!1):(s&&(this.tokenSub=s),!0)}async resyncFromToken(e){if(!this.resyncingIdentity){this.resyncingIdentity=!0;try{let{decodeJwtPayload:n}=await Promise.resolve().then(t.bind(t,92343)),i=n(e),s="string"==typeof(null==i?void 0:i.tenantId)?i.tenantId:null;this.disconnect(),this.authCache.clear(),this.pendingAuth.clear(),this.tenantId=null,this.hashedTenantId=null,this.hashTenantPromise=null,this.authToken=e,this.lastTokenHash=this.getTokenHash(e),this.tokenSub="string"==typeof(null==i?void 0:i.sub)?i.sub:null,s&&this.setTenantId(s),window.dispatchEvent(new CustomEvent("wizebot:auth:identity-changed",{detail:{tenantId:s}}))}finally{this.resyncingIdentity=!1}}}async resolveValidToken(){let{getAccessToken:e,isTokenExpired:n,refreshTokens:i}=await Promise.resolve().then(t.bind(t,92343));if(!n()){let n=await e()||this.authToken||"";if(n)return this.authToken=n,this.lastTokenHash=this.getTokenHash(n),n}if(this.refreshPromise){a.G.debug("[PusherClient] Waiting for existing refresh..."),await this.refreshPromise;let n=await e()||"";return this.authToken=n,this.lastTokenHash=this.getTokenHash(n),n}return a.G.debug("[PusherClient] Starting token refresh..."),this.refreshPromise=(async()=>{try{await i();let n=await e()||"";if(n){let e=this.getTokenHash(n);e!==this.lastTokenHash&&(a.G.debug("[PusherClient] Token changed, clearing auth cache"),this.authCache.clear()),this.authToken=n,this.lastTokenHash=e,a.G.debug("[PusherClient] Token refreshed successfully")}}finally{this.refreshPromise=null}})(),await this.refreshPromise,await e()||""}async authorizeChannel(e,n,t){let i="".concat(e,":").concat(n);try{let s=await this.ensureValidToken();if(!s)throw Error("No auth token available after refresh attempt");let r=this.getTokenHash(s),o=this.authCache.get(i);if(o&&Date.now()-o.timestamp<this.AUTH_CACHE_TTL&&o.tokenHash===r){a.G.debug("[PusherClient] Using cached auth for:",e),t(null,JSON.parse(o.auth));return}let l=this.pendingAuth.get(i);if(l){a.G.debug("[PusherClient] Waiting for pending auth:",e);try{let e=await l;t(null,e)}catch(e){t(e instanceof Error?e:Error(String(e)),null)}return}a.G.debug("[PusherClient] Making auth request for:",e);let h=this.makeAuthRequest(e,n,s);this.pendingAuth.set(i,h);let c=await h;this.authCache.set(i,{auth:JSON.stringify(c),timestamp:Date.now(),tokenHash:r}),this.pendingAuth.delete(i),t(null,c)}catch(e){this.pendingAuth.delete(i),a.G.error("[PusherClient] Channel authorization error",e),t(e instanceof Error?e:Error(String(e)),null)}}calculateBackoffDelay(e){return Math.min(3e4,1e3*Math.pow(2,e))+1e3*Math.random()}async makeAuthRequest(e,n,t){var i;let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=(null==(i=this.config)?void 0:i.authEndpoint)||"/api/pusher/auth";try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(t)},body:JSON.stringify({socket_id:n,channel_name:e})});if(!i.ok){if(401===i.status&&s<3){a.G.debug("[PusherClient] Got 401, refreshing token and retrying..."),this.authCache.clear(),this.refreshPromise=null;let i=await this.ensureValidToken();if(i&&i!==t){let t=this.calculateBackoffDelay(s);return a.G.debug("[PusherClient] Waiting ".concat(t,"ms before retry ").concat(s+1)),await new Promise(e=>setTimeout(e,t)),this.makeAuthRequest(e,n,i,s+1)}}if(i.status>=500&&s<3){let r=this.calculateBackoffDelay(s);return a.G.debug("[PusherClient] Server error ".concat(i.status,", waiting ").concat(r,"ms before retry ").concat(s+1)),await new Promise(e=>setTimeout(e,r)),this.makeAuthRequest(e,n,t,s+1)}throw a.G.error("[PusherClient] Auth failed",{status:i.status,channelName:e,retryCount:s}),Error("Authorization failed: ".concat(i.status))}return await i.json()}catch(i){if(s<3&&!(i instanceof Error&&(i.message.includes("Authorization failed")||i.message.includes("Token identity changed")))){let i=this.calculateBackoffDelay(s);return a.G.debug("[PusherClient] Network error, waiting ".concat(i,"ms before retry ").concat(s+1)),await new Promise(e=>
1setTimeout(e,i)),this.makeAuthRequest(e,n,t,s+1)}throw i}}setAuthToken(e){this.authToken=e,this.initialized&&a.G.debug("[PusherClient] Auth token set")}setTenantId(e){(this.tenantId!==e||!this.hashedTenantId)&&(this.tenantId=e,this.hashedTenantId=null,this.hashTenantPromise=this.fetchTenantHash(e),this.hashTenantPromise.then(e=>{e&&(this.hashedTenantId=e,a.G.debug("[PusherClient] Tenant hash resolved:",null==e?void 0:e.slice(0,12)))}),this.initialized&&a.G.debug("[PusherClient] Tenant set:",null==e?void 0:e.slice(0,8)))}async fetchTenantHash(e){try{var n;let e=await this.ensureValidToken();if(!e)return a.G.error("[PusherClient] No auth token available for tenant hash request"),null;let t=((null==(n=this.config)?void 0:n.authEndpoint)||"").replace(/\/auth$/,""),i=await fetch("".concat(t,"/tenant-hash"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!i.ok)return a.G.error("[PusherClient] Failed to fetch tenant hash:",i.status),null;return(await i.json()).hash||null}catch(e){return a.G.error("[PusherClient] Error fetching tenant hash",e),null}}async ensureTenantHash(){return this.hashedTenantId?this.hashedTenantId:this.hashTenantPromise?await this.hashTenantPromise:null}generateChannelName(e){let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1],t=n?"private-":"",i=this.hashedTenantId;if(!i)return a.G.warn("[PusherClient] Tenant hash not yet resolved, cannot generate channel name"),null;switch(e.channelType){case"chat":return"".concat(t).concat(i,".chat.").concat(e.identifier);case"user":return"".concat(t).concat(i,".user.").concat(e.identifier);case"phone":return"".concat(t).concat(i,".phone.").concat(e.identifier);case"events":return"".concat(t).concat(i,".events");case"crm":return"".concat(t).concat(i,".crm");case"agents":return"presence-".concat(i,".agents");case"tenant":return"".concat(t).concat(i,".tenant.").concat(e.identifier);default:throw Error("Unsupported channel type: ".concat(e.channelType))}}subscribeToUnreadCount(e){if(!this.pusher)return a.G.warn("[PusherClient] Not initialized for unread-count subscription"),()=>{};let n=this.generateChannelName({tenantId:this.tenantId,channelType:"events",identifier:""});if(!n)return()=>{};let t=this.channels.get(n);return t||(t=this.pusher.subscribe(n),this.channels.set(n,t)),t.bind("unread-count-changed",e),()=>{try{null==t||t.unbind("unread-count-changed",e)}catch(e){}}}subscribeToWaflowStatus(e){if(!this.pusher)return a.G.warn("[PusherClient] Not initialized for waflow-status subscription"),()=>{};let n=this.generateChannelName({tenantId:this.tenantId,channelType:"events",identifier:""});if(!n)return()=>{};let t=this.channels.get(n);return t||(t=this.pusher.subscribe(n),this.channels.set(n,t)),t.bind("waflow:status-changed",e),()=>{try{null==t||t.unbind("waflow:status-changed",e)}catch(e){}}}subscribeToPlatformNotifications(e){if(!this.pusher)return a.G.warn("[PusherClient] Not initialized for platform-notification subscription"),()=>{};let n=this.generateChannelName({tenantId:this.tenantId,channelType:"events",identifier:""});if(!n)return()=>{};let t=this.channels.get(n);return t||(t=this.pusher.subscribe(n),this.channels.set(n,t)),t.bind("platform-notification",e),()=>{try{null==t||t.unbind("platform-notification",e)}catch(e){}}}subscribeToChatChannel(e,n){if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set",{pusherInitialized:!!this.pusher,hasTenantId:!!this.tenantId,hasAuthToken:!!this.authToken}),null;let t=this.generateChannelName({tenantId:this.tenantId,channelType:"chat",identifier:e});if(!t)return null;if(a.G.debug("[PusherClient] Subscribing to channel:","".concat(t," for chatId: ").concat(e)),this.channels.has(t)){a.G.debug("[PusherClient] Channel already exists, rebinding callbacks:",t);let i=this.channels.get(t);return this.bindChatChannelCallbacks(i,e,t,n),i}let i=this.pusher.subscribe(t);return i.bind("pusher:subscription_succeeded",()=>{a.G.debug("[PusherClient] Successfully subscribed to:",t)}),i.bind("pusher:subscription_error",e=>{a.G.error("[PusherClient] Subscription error",{channelName:t,error:e})}),this.bindChatChannelCallbacks(i,e,t,n),this.channels.set(t,i),i}bindChatChannelCallbacks(e,n,t,i){e.unbind("new-message"),e.unbind("message-status"),e.unbind("typing"),e.unbind("audio-conversion-complete"),e.unbind("message-media-updated"),e.unbind("message-reaction"),e.unbind("history-cleared"),e.unbind("messages-read"),e.unbind("conversation-updated"),e.unbind("automation-paused"),e.unbind("automation-resumed"),e.unbind("note-created"),e.unbind("note-updated"),i.onMessage&&e.bind("new-message",e=>{a.G.debug("[PusherClient] New message event received");try{var n;let t=this.convertMessageDTOToInternal(e);null==(n=i.onMessage)||n.call(i,t)}catch(e){a.G.error("[PusherClient] Erro ao converter MessageDTO",e)}}),i.onMessageStatus&&e.bind("message-status",i.onMessageStatus),i.onTyping&&e.bind("typing",e=>{var t;null==(t=i.onTyping)||t.call(i,{...e,conversationId:(null==e?void 0:e.conversationId)||n})}),i.onAudioConversionComplete&&e.bind("audio-conversion-complete",e=>{var n;a.G.debug("[PusherClient] Audio conversion complete event received:",e),null==(n=i.onAudioConversionComplete)||n.call(i,e)}),i.onMessageMediaUpdated&&e.bind("message-media-updated",e=>{var n;a.G.debug("[PusherClient] message-media-updated received:",e),null==(n=i.onMessageMediaUpdated)||n.call(i,e)}),i.onReaction&&e.bind("message-reaction",e=>{var n;null==(n=i.onReaction)||n.call(i,e)}),i.onHistoryCleared&&e.bind("history-cleared",e=>{var n;null==(n=i.onHistoryCleared)||n.call(i,e)}),i.onMessagesRead&&e.bind("messages-read",e=>{var n;null==(n=i.onMessagesRead)||n.call(i,e)}),i.onConversationUpdated&&e.bind("conversation-updated",e=>{var n;null==(n=i.onConversationUpdated)||n.call(i,e)}),i.onAutomationPaused&&e.bind("automation-paused",e=>{var n;null==(n=i.onAutomationPaused)||n.call(i,e)}),i.onAutomationResumed&&e.bind("automation-resumed",e=>{var n;null==(n=i.onAutomationResumed)||n.call(i,e)}),i.onNoteCreated&&e.bind("note-created",e=>{var n;null==(n=i.onNoteCreated)||n.call(i,e)}),i.onNoteUpdated&&e.bind("note-updated",e=>{var n;null==(n=i.onNoteUpdated)||n.call(i,e)})}subscribeToUserChannel(e,n){if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set for user channel"),null;let t=this.generateChannelName({tenantId:this.tenantId,channelType:"user",identifier:e});if(!t)return null;if(this.channels.has(t))return this.channels.get(t);let i=this.pusher.subscribe(t);return n.onNotification&&i.bind("notification",n.onNotification),n.onUserUpdate&&i.bind("user-update",n.onUserUpdate),this.channels.set(t,i),i}subscribeToTenantChannel(e){if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set for tenant channel"),null;let n=this.generateChannelName({tenantId:this.tenantId,channelType:"tenant",identifier:"messages"});if(!n)return null;if(a.G.debug("[PusherClient] Subscribing to tenant-wide channel:",n),this.channels.has(n)){a.G.debug("[PusherClient] Tenant channel already exists, rebinding callbacks:",n);let t=this.channels.get(n);return this.bindTenantChannelCallbacks(t,e),t}let t=this.pusher.subscribe(n);return t.bind("pusher:subscription_succeeded",()=>{a.G.debug("[PusherClient] Successfully subscribed to tenant channel:",n)}),t.bind("pusher:subscription_error",e=>{a.G.error("[PusherClient] Tenant channel subscription error",{channelName:n,error:e})}),this.bindTenantChannelCallbacks(t,e),this.channels.set(n,t),t}bindTenantChannelCallbacks(e,n){e.unbind("new-message"),e.unbind("message-status"),e.unbind("message-media-updated"),e.unbind("messages-read"),e.unbind("history-cleared"),e.unbind("agent-assigned"),e.unbind("agent-unassigned"),e.unbind("conversation-updated"),e.unbind("automation-paused"),e.unbind("automation-resumed"),e.unbind("contact:tags-updated"),e.unbind("conversation-status-changed"),e.unbind("new-conversation-queued"),e.unbind("contact:updated"),e.unbind("conversations-bulk-updated"),n.onMessage&&e.bind("new-message",e=>{try{let t=this.convertMessageDTOToInternal(e);n.onMessage(t)}
1catch(e){a.G.error("[PusherClient] Error converting tenant message",e)}}),n.onMessageStatus&&e.bind("message-status",n.onMessageStatus),n.onMessageMediaUpdated&&e.bind("message-media-updated",e=>{var t;null==(t=n.onMessageMediaUpdated)||t.call(n,e)}),n.onMessagesRead&&e.bind("messages-read",e=>{var t;null==(t=n.onMessagesRead)||t.call(n,e)}),n.onHistoryCleared&&e.bind("history-cleared",e=>{var t;null==(t=n.onHistoryCleared)||t.call(n,e)}),n.onAgentAssigned&&e.bind("agent-assigned",e=>{var t;null==(t=n.onAgentAssigned)||t.call(n,e)}),n.onAgentUnassigned&&e.bind("agent-unassigned",e=>{var t;null==(t=n.onAgentUnassigned)||t.call(n,e)}),n.onConversationUpdated&&e.bind("conversation-updated",e=>{var t;null==(t=n.onConversationUpdated)||t.call(n,e)}),n.onAutomationPaused&&e.bind("automation-paused",e=>{var t;null==(t=n.onAutomationPaused)||t.call(n,e)}),n.onAutomationResumed&&e.bind("automation-resumed",e=>{var t;null==(t=n.onAutomationResumed)||t.call(n,e)}),n.onContactTagsUpdated&&e.bind("contact:tags-updated",e=>{var t;null==(t=n.onContactTagsUpdated)||t.call(n,e)}),n.onConversationStatusChanged&&e.bind("conversation-status-changed",e=>{var t;null==(t=n.onConversationStatusChanged)||t.call(n,e)}),n.onNewConversationQueued&&e.bind("new-conversation-queued",e=>{var t;null==(t=n.onNewConversationQueued)||t.call(n,e)}),n.onContactUpdated&&e.bind("contact:updated",e=>{var t;null==(t=n.onContactUpdated)||t.call(n,e)}),n.onConversationsBulkUpdated&&e.bind("conversations-bulk-updated",e=>{var t;null==(t=n.onConversationsBulkUpdated)||t.call(n,e)})}subscribeToAgentsChannel(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set for agents channel"),null;let t=this.generateChannelName({tenantId:this.tenantId,channelType:"agents",identifier:""});if(!t)return null;if(this.channels.has(t))return this.channels.get(t);this.presenceDebouncer=new r(n,n=>{var t;null==(t=e.onPresenceUpdate)||t.call(e,n)});let i=this.pusher.subscribe(t);return e.onAgentStatusChange&&i.bind("agent-status",e.onAgentStatusChange),i.bind("pusher:subscription_succeeded",e=>{var n;let t=[];e.each(e=>{var n,i,s,a;t.push({id:e.id,name:(null==(n=e.info)?void 0:n.name)||e.id,avatar:null==(i=e.info)?void 0:i.avatar,status:(null==(s=e.info)?void 0:s.status)||"online",role:null==(a=e.info)?void 0:a.role})}),null==(n=this.presenceDebouncer)||n.setInitialMembers(t),a.G.debug("[PusherClient] Presence channel subscribed, members:",t.length)}),i.bind("pusher:member_added",e=>{var n,t,i,s,r;let o={id:e.id,name:(null==(n=e.info)?void 0:n.name)||e.id,avatar:null==(t=e.info)?void 0:t.avatar,status:(null==(i=e.info)?void 0:i.status)||"online",role:null==(s=e.info)?void 0:s.role};null==(r=this.presenceDebouncer)||r.memberAdded(o),a.G.debug("[PusherClient] Member added:",o.name)}),i.bind("pusher:member_removed",e=>{var n;null==(n=this.presenceDebouncer)||n.memberRemoved(e.id),a.G.debug("[PusherClient] Member removal scheduled (debounced):",e.id)}),this.channels.set(t,i),i}subscribeToEventsChannel(e){if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set for events channel"),null;let n=this.generateChannelName({tenantId:this.tenantId,channelType:"events",identifier:""});if(!n)return null;if(this.channels.has(n)){let t=this.channels.get(n);return e.onBulkProgress&&t.bind("bulk-progress",e.onBulkProgress),e.onCampaignProgress&&t.bind("campaign:progress",e.onCampaignProgress),e.onCampaignCompleted&&t.bind("campaign:completed",e.onCampaignCompleted),t}let t=this.pusher.subscribe(n);return t.bind("pusher:subscription_succeeded",()=>{a.G.debug("[PusherClient] Successfully subscribed to events channel:",n)}),t.bind("pusher:subscription_error",e=>{a.G.error("[PusherClient] Events channel subscription error",{channelName:n,error:e})}),e.onBulkProgress&&t.bind("bulk-progress",e.onBulkProgress),e.onCampaignProgress&&t.bind("campaign:progress",e.onCampaignProgress),e.onCampaignCompleted&&t.bind("campaign:completed",e.onCampaignCompleted),this.channels.set(n,t),t}async subscribeToCrmChannel(e){if(!this.pusher||!this.tenantId)return a.G.error("[PusherClient] Not initialized or tenant ID not set for CRM channel"),null;if(await this.ensureTenantHash(),!this.hashedTenantId)return a.G.error("[PusherClient] Tenant hash not available for CRM channel"),null;let n=this.generateChannelName({tenantId:this.tenantId,channelType:"crm",identifier:""});if(!n)return null;if(this.channels.has(n))return this.channels.get(n);let t=this.pusher.subscribe(n);return t.bind("pusher:subscription_succeeded",()=>{a.G.debug("[PusherClient] Successfully subscribed to CRM channel:",n)}),t.bind("pusher:subscription_error",e=>{a.G.error("[PusherClient] CRM channel subscription error",{channelName:n,error:e})}),e.onDealCreated&&t.bind("crm:deal.created",e.onDealCreated),e.onDealUpdated&&t.bind("crm:deal.updated",e.onDealUpdated),e.onDealMoved&&t.bind("crm:deal.moved",e.onDealMoved),e.onDealDeleted&&t.bind("crm:deal.deleted",e.onDealDeleted),e.onDealWon&&t.bind("crm:deal.won",e.onDealWon),e.onDealLost&&t.bind("crm:deal.lost",e.onDealLost),e.onStageCreated&&t.bind("crm:stage.created",e.onStageCreated),e.onStageUpdated&&t.bind("crm:stage.updated",e.onStageUpdated),e.onStageDeleted&&t.bind("crm:stage.deleted",e.onStageDeleted),e.onStageReordered&&t.bind("crm:stages.reordered",e.onStageReordered),e.onTaskCreated&&t.bind("crm:task.created",e.onTaskCreated),e.onTaskUpdated&&t.bind("crm:task.updated",e.onTaskUpdated),this.channels.set(n,t),t}unsubscribeFromCrmChannel(){if(!this.tenantId)return;let e=this.generateChannelName({tenantId:this.tenantId,channelType:"crm",identifier:""});e&&this.unsubscribeFromChannel(e)}unsubscribeFromChannel(e){if(this.channels.has(e)&&(this.channels.get(e),this.pusher&&this.pusher.unsubscribe(e),this.channels.delete(e),e.includes(".agents"))){var n;null==(n=this.presenceDebouncer)||n.clear(),this.presenceDebouncer=null}}unsubscribeFromChatChannel(e){if(!this.tenantId)return;let n=this.generateChannelName({tenantId:this.tenantId,channelType:"chat",identifier:e});n&&this.unsubscribeFromChannel(n)}unsubscribeFromTenantChannel(){if(!this.tenantId)return;let e=this.generateChannelName({tenantId:this.tenantId,channelType:"tenant",identifier:"messages"});e&&this.unsubscribeFromChannel(e)}convertMessageDTOToInternal(e){var n,t,i,s,r,o,l,h,c,d,u,g,b,m,p,v,C,f,T,y,k;let w;if(!e.from)throw a.G.error("[PusherClient] MessageDTO.from \xe9 undefined"),Error("MessageDTO.from \xe9 obrigat\xf3rio");let P=e.type;return["audio","image","video","document","interactive","button","template","sticker","location","contacts","contact","reaction","order"].includes(P)?(w=e.content||{}).text||w.caption||["interactive","button","template"].includes(P)||(w.text=this.extractContentText(e)):w=this.extractContentText(e),{id:e.id,content:w,sender_id:e.from.id,sender_name:e.from.name||e.from.id,sender_avatar:e.from.avatar,created_at:e.timestamp,message_type:P,errorMessage:e.errorMessage,metadata:{providerId:e.providerId,sessionId:e.sessionId,tenantId:e.tenantId,channel:null==(n=e.metadata)?void 0:n.channel,channelAccountId:null==(t=e.metadata)?void 0:t.channelAccountId,status:e.status,isFromMe:e.from.isMe,mediaUrl:null==(i=e.content)?void 0:i.url,caption:null==(s=e.content)?void 0:s.caption,mimeType:null==(r=e.content)?void 0:r.mimeType,fileSize:null==(o=e.content)?void 0:o.fileSize,duration:null==(l=e.content)?void 0:l.duration,dimensions:null==(h=e.content)?void 0:h.dimensions,originalContent:e.content,replyTo:null==(c=e.metadata)?void 0:c.replyTo,replyToContent:null==(d=e.metadata)?void 0:d.replyToContent,replyToSender:null==(u=e.metadata)?void 0:u.replyToSender,sentBy:null==(g=e.metadata)?void 0:g.sentBy,sender_name:null==(b=e.metadata)?void 0:b.sender_name,sender_avatar:null==(m=e.metadata)?void 0:m.sender_avatar,source:(null==(v=e.metadata)||null==(p=v.providerData)?void 0:p.source)||(null==(C=e.metadata)?void 0:C.source),sender_type:null==(f=e.metadata)?void 0:f.sender_type,type:(null==(y=e.metadata)||null==(T=y.providerData)?void 0:T.type)||(null==(k=e.metadata)?void 0:k.type)}}}extractContentText(e){var n,t,i,s;if(null==(n=e.content)?void 0:n.text)return e.content.text;if(e.content&&"object"==typeof e.content){let n=e.content;if(n.body)return n.body;if(n.message)return n.message;if(n.caption)return n.caption;if(n.filename)return n.filename;if(null==(t=n.text)?void 0:t.body)return n.text.body;if(null==(i=n.image)?void 0:i.caption)return n.image.caption;if(null==(s=n.document)?void 0:s.filename)return n.document.filename}switch(e.type){case"image":return"\uD83D\uDCF7 Imagem";case"audio":return"\uD83C\uDFB5 \xc1udio";case"video":return"\uD83C\uDFA5 V\xeddeo";case"document":return"\uD83D\uDCC4 Documento";default:return""}}createOptimisticMessage(e,n,t){return{id:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let n=16*Math.random()|0;return("x"==e?n:3&n|8).toString(16)}),providerId:"temp-".concat(Date.now()),sessionId:n,tenantId:t,from:{id:"me",name:"Voc\xea",isMe:!0},type:"text",content:{text:e},status:"sending",timestamp:new Date().toISOString()}}disconnect(){this.tokenRefreshHandler&&(window.removeEventListener("wizebot:auth:token-refreshed",this.tokenRefreshHandler),this.tokenRefreshHandler=null),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null),this.focusHandler&&(window.removeEventListener("focus",this.focusHandler),this.focusHandler=null),this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.stopHealthCheck(),this.pusher&&(a.G.debug("[PusherClient] Disconnecting..."),this.pusher.disconnect(),this.pusher=null,this.channels.clear(),this.initialized=!1)}isConnected(){var e;return(null==(e=this.pusher)?void 0:e.connection.state)==="connected"}isReady(){return this.isConnected()&&!!this.tenantId&&!!this.hashedTenantId}hasTenantId(){return!!this.tenantId}getConnectionState(){var e;return(null==(e=this.pusher)?void 0:e.connection.state)||"disconnected"}constructor(){this.pusher=null,this.channels=new Map,this.authToken=null,this.tenantId=null,this.hashedTenantId=null,this.hashTenantPromise=null,this.config=null,this.initialized=!1,this.authCache=new Map,this.pendingAuth=new Map,this.refreshPromise=null,this.lastTokenHash="",this.tokenSub=null,this.resyncingIdentity=!1,this.AUTH_CACHE_TTL=55e3,this.presenceDebouncer=null,this.tokenRefreshHandler=null,this.visibilityChangeHandler=null,this.focusHandler=null,this.disconnectedAt=null,this.reconnectCallbacks=new Set,this.lastConnectedAt=0,this.healthCheckInterval=null,this.lastHealthCheckTime=0,this.onlineHandler=null,this.HEALTH_CHECK_INTERVAL=3e4,this.SLEEP_DETECTION_THRESHOLD=45e3,this.lastServerActivityAt=0,this.SERVER_ACTIVITY_WINDOW=18e4,this.reconnecting=!1}}let l=new o}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.