(()=>{var e={60833:(e,t,n)=>{var r;e=n.nmd(e),self,r=r=>(()=>{"use strict";var o={0:(e,t)=>{!function(e){e.AUTHORIZE_CONSUMER="AuthorizeConsumer",e.CASE_CREATED="CaseCreated",e.CASE_INBOX_ASSIGNEE_CHANGED="CaseInboxAssigneeChanged",e.CASE_STATUS_CHANGED="CaseStatusChanged",e.CASE_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED="CaseToRoutingQueueAssignmentChanged",e.CONTACT_CREATED="CaseCreated",e.ASSIGNED_AGENT_CHANGED="CaseInboxAssigneeChanged",e.CONTACT_STATUS_CHANGED="CaseStatusChanged",e.CONTACT_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED="CaseToRoutingQueueAssignmentChanged",e.CONTACT_PREFERRED_USER_CHANGED="ContactPreferredUserChanged",e.CONTACT_PROFICIENCY_CHANGED="ContactProficiencyChanged",e.CONTACT_PRIORITY_CHANGED="ContactPriorityChanged",e.CONTACT_SYNC="ContactSync",e.CHANNEL_CREATED="ChannelCreated",e.CHANNEL_DELETED="ChannelDeleted",e.CHANNEL_UPDATED="ChannelUpdated",e.MESSAGE_ADDED_INTO_CASE="MessageAddedIntoCase",e.MESSAGE_CREATED="MessageCreated",e.MESSAGE_DELIVERED_TO_END_USER="MessageDeliveredToEndUser",e.MESSAGE_DELIVERED_TO_USER="MessageDeliveredToUser",e.MESSAGE_DELIVERY_STATUS_CHANGED="MessageDeliveryStatusChanged",e.MESSAGE_NOTE_CREATED="MessageNoteCreated",e.MESSAGE_NOTE_UPDATED="MessageNoteUpdated",e.MESSAGE_NOTE_DELETED="MessageNoteDeleted",e.MESSAGE_READ_CHANGED="MessageReadChanged",e.MESSAGE_SEEN_BY_END_USER="MessageSeenByEndUser",e.MESSAGE_SEEN_BY_USER="MessageSeenByUser",e.MESSAGE_SEEN_CHANGED="MessageSeenChanged",e.MESSAGE_SENT="MessageSent",e.MESSAGE_UPDATED="MessageUpdated",e.PAGE_VIEW_CREATED="PageViewCreated",e.ROUTING_QUEUE_CREATED="RoutingQueueCreated",e.ROUTING_QUEUE_DELETED="RoutingQueueDeleted",e.ROUTING_QUEUE_UPDATED="RoutingQueueUpdated",e.SUBQUEUE_ASSIGNED_TO_ROUTING_QUEUE="SubqueueAssignedToRoutingQueue",e.SUBQUEUE_UNASSIGNED_TO_ROUTING_QUEUE="SubqueueUnassignedFromRoutingQueue",e.USER_ASSIGNED_TO_ROUTING_QUEUE="UserAssignedToRoutingQueue",e.USER_STATUS_CHANGED="UserStatusChanged",e.USER_UNASSIGNED_FROM_ROUTING_QUEUE="UserUnassignedFromRoutingQueue",e.AGENT_CONTACT_STARTED="AgentContactStarted",e.AGENT_CONTACT_ENDED="AgentContactEnded",e.SENDER_TYPING_STARTED="SenderTypingStarted",e.SENDER_TYPING_ENDED="SenderTypingEnded",e.FIRE_PROACTIVE="FireProactiveAction",e.CONTACT_INBOX_PRE_ASSIGNEE_CHANGED="ConsumerContactInboxPreAssigneeChanged",e.CONTACT_RECIPIENTS_CHANGED="ContactRecipientsChanged",e.MESSAGE_PREVIEW_CREATED="MessagePreviewCreated",e.EVENT_IN_S3="EventInS3"}(t.m||(t.m={}))},10:(e,t)=>{t.C=void 0,t.C=function(e){return Object.keys(e).filter(function(t){return null!==e[t]}).map(function(t){return[t,e[t]].map(encodeURIComponent).join("=")}).join("&")}},155:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getTimeInMinutes=t.getTimeInMilliseconds=t.getTimeInSeconds=t.padDateTimeUnit=void 0,t.padDateTimeUnit=function(e){var t=Math.abs(Math.floor("string"==typeof e?Number(e):e));return(t<10?"0":"")+t},t.getTimeInSeconds=function(e){var t=e.hours,n=e.minutes,r=e.seconds;return 60*(void 0===t?0:t)*60+60*(void 0===n?0:n)+(void 0===r?0:r)},t.getTimeInMilliseconds=function(e){var n=e.hours,r=e.minutes,o=e.seconds,a=e.milliseconds;return 1e3*(0,t.getTimeInSeconds)({hours:void 0===n?0:n,minutes:void 0===r?0:r,seconds:void 0===o?0:o})+(void 0===a?0:a)},t.getTimeInMinutes=function(e){var n=e.hours,r=e.minutes,o=e.seconds;return(0,t.getTimeInSeconds)({hours:void 0===n?0:n,minutes:void 0===r?0:r,seconds:void 0===o?0:o})/60}},168:(e,t,n)=>{var r=n(275);t.P=r.CaseStatus},172:(e,t,n)=>{t.NP=t.nF=void 0,n(547),n(383),n(272);var r=n(402);Object.defineProperty(t,"nF",{enumerable:!0,get:function(){return r.WebSocketClientEvent}});var o=n(720);Object.defineProperty(t,"NP",{enumerable:!0,get:function(){return o.setupSocketConnection}})},198:e=>{e.exports=r},272:function(e,t,n){var r,o=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0}),t.WebSocketClient=t.HEART_BEAT_CHECK_TIMEOUT=t.HEART_BEAT_INTERVAL=void 0;var a=n(802),i=n(906),l=n(383),s=n(547),u=n(402);t.HEART_BEAT_INTERVAL=15e3,t.HEART_BEAT_CHECK_TIMEOUT=3*t.HEART_BEAT_INTERVAL;var c=function(e){function n(n,r,o){var l=e.call(this)||this;return l.heartBeatTimeout=null,l.heartBeatCheckTimeout=null,l.enableDebugMode=function(){l.debugMode||l.log(a.LogLevels.INFO,"websocket-push-updates--loggerEnabled"),l.debugMode=!0},l.disableDebugMode=function(){l.debugMode=!1},l.log=function(e,t,n){l.debugMode&&l.logger&&l.logger[e](t,n)},l.sendHeartBeat=function(){l.log(a.LogLevels.INFO,"websocket-push-updates--sendHeartBeat"),l.send(JSON.stringify({action:"heartbeat"}))},l.handleHeartBeatResponse=function(){l.heartBeatState===s.HeartBeatState.DYING&&(l.heartBeatState=s.HeartBeatState.LIVING,l.dispatchHeartBeatState()),l.setHeartBeatCheckTimeout()},l.setHeartBeatCheckTimeout=function(){null!==l.heartBeatCheckTimeout&&clearTimeout(l.heartBeatCheckTimeout),l.heartBeatCheckTimeout=setTimeout(function(){l.heartBeatState=s.HeartBeatState.DYING,l.dispatchHeartBeatState()},t.HEART_BEAT_CHECK_TIMEOUT)},l.dispatchHeartBeatState=function(){l.log(a.LogLevels.INFO,"websocket-push-updates--dispatchHeartBeatState",[{heartbeatState:l.heartBeatState}]),null!==l.heartBeatState&&l.dispatchEvent(new CustomEvent(l.heartBeatState))},l.isHeartBeatActive=function(){return null!==l.heartBeatState},l.heartBeatState=null,l.debugMode=!1,l.socket=new i.ReconnectingWebSocket(n,r,o),l.socket.onopen=function(){l.dispatchEvent(new CustomEvent(u.WebSocketClientEvent.OPEN))},(null==o?void 0:o.logger)&&(l.logger=o.logger),l.socket.onclose=function(e){l.socket.retryCount===(null==o?void 0:o.maxRetries)?l.heartBeatState=s.HeartBeatState.DIED:l.heartBeatState=s.HeartBeatState.DYING,l.dispatchHeartBeatState(),l.dispatchEvent(new CustomEvent(u.WebSocketClientEvent.CLOSE,{detail:e}))},l.socket.onmessage=function(e){l.handleHeartBeatResponse(),"pong"!==JSON.parse(e.data)&&(l.log(a.LogLevels.INFO,"websocket-push-updates--onmessage",[e]),l.dispatchEvent(new CustomEvent(u.WebSocketClientEvent.MESSAGE,{detail:e})))},l.socket.onerror=function(e){l.log(a.LogLevels.ERROR,"websocket-push-updates--onError",[e]),l.dispatchEvent(new CustomEvent(u.WebSocketClientEvent.ERROR,{detail:e}))},l}return o(n,e),n.prototype.send=function(e){this.socket.send(e)},n.prototype.startHeartBeat=function(){var e=this;this.log(a.LogLevels.INFO,"websocket-push-updates--startHeartBeat",[{interval:t.HEART_BEAT_INTERVAL}]);var n=function(){e.log(a.LogLevels.INFO,"websocket-push-updates--heartBeatCallback"),e.sendHeartBeat(),e.heartBeatTimeout=setTimeout(n,t.HEART_BEAT_INTERVAL)};this.setHeartBeatCheckTimeout(),n(),this.heartBeatState=s.HeartBeatState.LIVING},n.prototype.stopHeartBeat=function(){this.log(a.LogLevels.INFO,"websocket-push-updates--stopHeartBeat"),null!==this.heartBeatTimeout&&clearTimeout(this.heartBeatTimeout),null!==this.heartBeatCheckTimeout&&clearTimeout(this.heartBeatCheckTimeout),this.heartBeatState=null},n}(l.EventTargetPolyfill);t.WebSocketClient=c},275:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),(n=t.CaseStatus||(t.CaseStatus={})).NEW="new",n.OPEN="open",n.PENDING="pending",n.ESCALATED="escalated",n.RESOLVED="resolved",n.CLOSED="closed",n.TRASHED="trashed"},369:(e,t)=>{var n;(n=t.F||(t.F={})).ONLINE="online",n.OFFLINE="offline"},383:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EventTargetPolyfill=void 0;var n=function(){function e(){this.listeners={}}return e.prototype.addEventListener=function(e,t){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push(t)},e.prototype.removeEventListener=function(e,t){if(e in this.listeners){for(var n=this.listeners[e],r=0,o=n.length;r{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.WebSocketClientEvent=void 0,(n=t.WebSocketClientEvent||(t.WebSocketClientEvent={})).CLOSE="close",n.ERROR="error",n.MESSAGE="message",n.OPEN="open",n.AUTHORIZATION_FAILED="authorizationFailed"},434:(e,t)=>{!function(e){e.TEXT="TEXT",e.FILE="FILE",e.FORM="FORM",e.PLUGIN="PLUGIN",e.POSTBACK="POSTBACK",e.QUICK_REPLIES="QUICK_REPLIES",e.RICH_LINK="RICH_LINK",e.LIST_PICKER="LIST_PICKER",e.ADAPTIVE_CARD="ADAPTIVE_CARD",e.TIME_PICKER="TIME_PICKER"}(t.G||(t.G={}))},442:(e,t)=>{var n;(n=t.bq||(t.bq={})).DESKTOP="desktop",n.MOBILE="mobile",n.OTHER="other",n.TABLET="tablet",(t.Xr||(t.Xr={})).BROWSER="browser"},482:(e,t)=>{var n,r;(r=t.ow||(t.ow={})).SENDER_TYPING_STARTED="SenderTypingStarted",r.SENDER_TYPING_ENDED="SenderTypingEnded",r.LOAD_MORE_MESSAGES="LoadMoreMessages",r.RECOVER_LIVECHAT="RecoverLivechat",r.RECOVER_THREAD="RecoverThread",r.SEND_MESSAGE="SendMessage",r.SEND_OUTBOUND="SendOutbound",r.SEND_OFFLINE_MESSAGE="SendOfflineMessage",r.SEND_PAGE_VIEWS="SendPageViews",r.SEND_CONSUMER_CUSTOM_FIELDS="SetConsumerCustomFields",r.SET_CONSUMER_CONTACT_CUSTOM_FIELD="SetConsumerContactCustomFields",r.MESSAGE_SEEN="MessageSeenByConsumer",r.SEND_TRANSCRIPT="SendTranscript",r.FETCH_THREAD_LIST="FetchThreadList",r.END_CONTACT="EndContact",r.EXECUTE_TRIGGER="ExecuteTrigger",r.AUTHORIZE_CONSUMER="AuthorizeConsumer",r.AUTHORIZE_CUSTOMER="AuthorizeCustomer",r.RECONNECT_CONSUMER="ReconnectConsumer",r.UPDATE_THREAD="UpdateThread",r.ARCHIVE_THREAD="ArchiveThread",r.LOAD_THREAD_METADATA="LoadThreadMetadata",r.REFRESH_TOKEN="RefreshToken",r.STORE_VISITOR="StoreVisitor",r.STORE_VISITOR_EVENTS="StoreVisitorEvents",r.CREATE_GROUP_CHAT_INVITE="CreateInvitationToGroupChat",r.SEND_EMAIL_INVITE_TO_GROUP_CHAT="SendEmailInvitationToGroupChat",r.JOIN_GROUP_CHAT="JoinGroupChat",r.LEAVE_GROUP_CHAT="LeaveGroupChat",r.GENERATE_AUTHORIZATION_TOKEN="GenerateAuthorizationToken",r.ADD_VISITOR_TAGS="AddVisitorTags",r.REMOVE_VISITOR_TAGS="RemoveVisitorTags",r.SEND_MESSAGE_PREVIEW="SendMessagePreview",(n=t.vc||(t.vc={})).LIVECHAT_RECOVERED="LivechatRecovered",n.MORE_MESSAGES_LOADED="MoreMessagesLoaded",n.OFFLINE_MESSAGE_SENT="OfflineMessageSent",n.THREAD_LIST_FETCHED="ThreadListFetched",n.THREAD_RECOVERED="ThreadRecovered",n.TRANSCRIPT_SENT="TranscriptSent",n.CONSUMER_AUTHORIZED="ConsumerAuthorized",n.THREAD_METADATA_LOADED="ThreadMetadataLoaded",n.SET_POSITION_IN_QUEUE="SetPositionInQueue",n.GROUP_CHAT_INVITE_CREATED="InvitationToGroupChatCreated",n.GROUP_CHAT_INVITE_SENT="EmailInvitationToGroupChatSent",n.GROUP_CHAT_JOINED="GroupChatJoined",n.TOKEN_REFRESHED="TokenRefreshed",n.AUTHORIZATION_TOKEN_GENERATED="AuthorizationTokenGenerated",n.THREAD_ARCHIVED="ThreadArchived"},521:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.removeEmptyValuesFromObject=void 0,t.removeEmptyValuesFromObject=function(e){return Object.entries(e).filter(function(e){return e[0],null!=e[1]}).reduce(function(e,t){var n=t[0],r=t[1];return e[n]=r,e},{})}},547:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.HeartBeatState=void 0,(n=t.HeartBeatState||(t.HeartBeatState={})).DIED="died",n.DYING="dying",n.LIVING="living"},555:(e,t,n)=>{t.TG=void 0,n(620),n(155),t.TG=function(e){var t=Date.parse(e);return isNaN(t)&&(t=function(e){var t,n=/^(\d{4}-\d\d-\d\d([tT][\d:.]*)?)([zZ]|([+-])(\d\d):?(\d\d))?$/.exec(e)||[];if(n[1]){if((t=n[1].split(/\D/).map(function(e){return parseInt(e,10)||0}))[1]-=1,!(t=new Date(Date.UTC.apply(Date,t))).getDate())return NaN;if(n[5]){var r=60*parseInt(n[5],10);n[6]&&(r+=parseInt(n[6],10)),"+"===n[4]&&(r*=-1),r&&t.setUTCMinutes(t.getUTCMinutes()+r)}return t.getTime()}return NaN}(e)),new Date(t)}},620:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getTimezoneISOOffset=void 0;var r=n(155);t.getTimezoneISOOffset=function(e){void 0===e&&(e=new Date);var t=e.getTimezoneOffset();return"".concat(t>0?"-":"+").concat((0,r.padDateTimeUnit)(t/60),":").concat((0,r.padDateTimeUnit)(t%60))}},668:(e,t)=>{var n;(n=t.V||(t.V={})).CHAT_WINDOW_EVENT="chatWindowEvent",n.REGISTER="register"},720:function(e,t,n){var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,n=1,r=arguments.length;nt.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};Object.defineProperty(t,"__esModule",{value:!0}),t.getPushUpdateWebSocket=t.setupSocketConnection=void 0;var a=n(892),i=n(734),l=n(521),s=n(272),u=null,c={forceSecureProtocol:!1,heartbeatAfterAuthorize:!1,maxRetries:20,maxReconnectionDelay:1e3};t.setupSocketConnection=function(e,t){if(void 0===t&&(t={}),"object"!=typeof t)throw TypeError("Options parameter must be an object not a ".concat(typeof t));var n,d,f,h,p=r(r({},c),t),m=p.forceSecureProtocol,g=p.heartbeatAfterAuthorize,v=p.tenantId,y=p.userId,b=p.brandId,w=o(p,["forceSecureProtocol","heartbeatAfterAuthorize","tenantId","userId","brandId"]);return"string"==typeof e&&(n=e,d={tenantId:v,userId:y,brandId:b},f=(0,a.createQueryParametersAsString)((0,l.removeEmptyValuesFromObject)(d)),h=m||"https:"===window.location.protocol?"wss:":"ws:",e=0===f.length?"".concat(h,"//").concat(n):new URL("".concat(h,"//").concat(n)).search.length>0?"".concat(h,"//").concat(n,"&").concat(f):"".concat(h,"//").concat(n,"?").concat(f)),u=new s.WebSocketClient(e,void 0,w),(0,i.initializeHeartbeat)(g,u,t),u},t.getPushUpdateWebSocket=function(){return u}},734:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initializeHeartbeat=void 0;var r=n(402);t.initializeHeartbeat=function(e,t,n){if(e){var o=function(e){var a;try{var i=JSON.parse(e.detail.data);"authorized"===(null==i?void 0:i.authorizationStatus)&&(t.startHeartBeat(),t.removeEventListener(r.WebSocketClientEvent.MESSAGE,o))}catch(e){null===(a=null==n?void 0:n.logger)||void 0===a||a.warn("JSON cannot be parsed during the heartbeat initialization process.")}};t.addEventListener(r.WebSocketClientEvent.MESSAGE,o)}else t.startHeartBeat()}},796:(e,t)=>{t.Um="X-Caller-Service-ID"},802:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevels=void 0,(n=t.LogLevels||(t.LogLevels={})).ERROR="error",n.INFO="info",n.WARN="warn"},892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createQueryParametersAsString=void 0,t.createQueryParametersAsString=function(e){return Object.keys(e).filter(function(t){return null!==e[t]}).map(function(t){return[t,e[t]].map(encodeURIComponent).join("=")}).join("&")}},906:function(e,t){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,a=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t,n){if(n||2==arguments.length)for(var r,o=0,a=t.length;o"],r(e),!1))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?a.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=void 0===r?a.minReconnectionDelay:r,i=e.maxReconnectionDelay,l=void 0===i?a.maxReconnectionDelay:i,s=0;return this._retryCount>0&&(s=o*Math.pow(n,this._retryCount-1))>l&&(s=l),this._debug("next delay",s),s},e.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(void 0!==t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options.connectionTimeout,n=void 0===t?a.connectionTimeout:t;this._retryCount>=this._maxRetries?this._debug("max retries reached",this._retryCount,">=",this._maxRetries):(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(t){e._closeCalled?e._connectLock=!1:(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new WebSocket(t,e._protocols):new WebSocket(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=window.setTimeout(function(){return e._handleTimeout()},n))}).catch(function(t){e._connectLock=!1,e._handleError(new ErrorEvent(t.message,{error:t}))}))}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new ErrorEvent("TIMEOUT"))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new CloseEvent("CLOSE",{code:e,reason:t}))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();t.ReconnectingWebSocket=i},953:(e,t)=>{!function(e){e.INBOUND="inbound",e.OUTBOUND="outbound"}(t.T||(t.T={}))}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return o[e].call(n.exports,n,n.exports,i),n.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var l={};i.r(l),i.d(l,{AbortError:()=>tU,AbortablePromise:()=>ni,AuthorizationError:()=>v,CHAT_SDK_VERSION:()=>y,CacheStorage:()=>ri,CacheStorageError:()=>rr,ChannelAvailability:()=>rl.F,ChatEvent:()=>tS,ChatSDKError:()=>g,ChatSdk:()=>nX,ContactStatus:()=>t3.P,Customer:()=>eJ,EnvironmentName:()=>tq,LivechatThread:()=>nT,MessageType:()=>tL.G,SdkVersionNotSupported:()=>tc,SecureSessions:()=>tW,SendMessageFailedError:()=>tP,Thread:()=>nS,ThreadRecoverFailedError:()=>nE,UploadAttachmentError:()=>t4,WebSocketClientError:()=>tV,WebSocketClientEvent:()=>u.nF,createAttachmentPayload:()=>t6,createAttachmentUploadMessageData:()=>t8,createCreateInvitationToGroupChatPayloadData:()=>n3,createJoinGroupChatPayloadData:()=>n5,createLeaveGroupChatPayloadData:()=>n8,createReconnectPayloadData:()=>e9,createSendEmailInvitationToGroupChatPayloadData:()=>rt,createTemporaryAttachmentsUpload:()=>t9,default:()=>ru,generateId:()=>b,getAuthor:()=>nu,getBrowserFingerprint:()=>ts,getBrowserLanguage:()=>ta,getBrowserLocation:()=>ti,getDeviceType:()=>tl,isAgentTypingEndedEvent:()=>n0,isAgentTypingStartedEvent:()=>nZ,isAssignedAgentChangedEvent:()=>nJ,isAttachmentUpload:()=>t5,isAuthSuccessEvent:()=>te,isContactCreatedEvent:()=>ne,isContactRecipientsChangedEvent:()=>nn,isContactStatusChangedEvent:()=>t7,isContactToRoutingQueueAssignmentChangedEvent:()=>nt,isCustomerReconnectSuccessPayloadData:()=>rs,isLoadMetadataSuccessPayload:()=>nm,isMessage:()=>nc,isMessageCreatedEvent:()=>nd,isMessageReadChangedEvent:()=>nh,isMessageSentEvent:()=>nf,isMoreMessagesLoadedEvent:()=>no,isRecoverSuccessEvent:()=>ng,isSetPositionInQueueEvent:()=>n1,isThreadArchivedSuccessPayload:()=>nv,isThreadListFetchedPostbackData:()=>nC,isTokenRefreshedSuccessResponse:()=>tt,sendChatEvent:()=>e5,sendCreateInvitationToGroupChatEvent:()=>n4,sendEmailInvitationToGroupChatEvent:()=>rn,sendJoinGroupChatEvent:()=>n9,sendLeaveGroupChatEvent:()=>n7,splitName:()=>e$});var s=i(10),u=i(172),c=i(668),d=i(482);let f=function(e){return null===e},h={};function p(e){h.ACCESS_TOKEN=e.token,h.ACCESS_TOKEN_EXPIRES_IN=e.expiresIn}function m(){var e,t;let n=null!==(e=h.ACCESS_TOKEN)&&void 0!==e?e:null,r=null!==(t=h.ACCESS_TOKEN_EXPIRES_IN)&&void 0!==t?t:null;return f(n)||f(r)?null:{token:n,expiresIn:Number(r)}}class g extends Error{constructor(e,t){if(super(),this.name="ChatSDKError",this.data=t,e instanceof g)return this.message=e.message,this.stack=e.stack,void(this.cause=e.cause);this.message=`[ChatSDKError]: ${this._getErrorMessage(e)}`,e instanceof Error&&(this.stack=e.stack)}_getErrorMessage(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}}class v extends g{constructor(e,t){super(e,t),void 0!==t&&(this.message=`${e} because of (${t.errorMessage})`)}}let y="2.1.0-rc.10";function b(){return crypto.randomUUID?crypto.randomUUID():function(){let e=new Uint8Array(16);return crypto.getRandomValues(e).reduce((e,t,n)=>([4,6,8,10].includes(n)&&(e+="-"),e+(6===n?15&t|64:8===n?63&t|128:t).toString(16).padStart(2,"0")),"")}()}function w(e){return{visitor:{id:e}}}var E=Object.prototype;let S=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||E)},_=(T=Object.keys,C=Object,function(e){return T(C(e))});var T,C,k=Object.prototype.hasOwnProperty;let O="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;var x="object"==typeof self&&self&&self.Object===Object&&self;let I=O||x||Function("return this")(),N=I.Symbol;var A=Object.prototype,R=A.hasOwnProperty,D=A.toString,P=N?N.toStringTag:void 0,L=Object.prototype.toString,M=N?N.toStringTag:void 0;let j=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":M&&M in Object(e)?function(e){var t=R.call(e,P),n=e[P];try{e[P]=void 0;var r=!0}catch(e){}var o=D.call(e);return r&&(t?e[P]=n:delete e[P]),o}(e):L.call(e)},U=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},F=function(e){if(!U(e))return!1;var t=j(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},z=I["__core-js_shared__"];var $,H=($=/[^.]+$/.exec(z&&z.keys&&z.keys.IE_PROTO||""))?"Symbol(src)_1."+$:"",B=Function.prototype.toString;let V=function(e){if(null!=e){try{return B.call(e)}catch(e){}try{return e+""}catch(e){}}return""};var G=/^\[object .+?Constructor\]$/,W=Object.prototype,q=Function.prototype.toString,Q=W.hasOwnProperty,K=RegExp("^"+q.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");let Y=function(e,t){var n,r=null==e?void 0:e[t];return!(!U(n=r)||H&&H in n)&&(F(n)?K:G).test(V(n))?r:void 0},X=Y(I,"DataView"),J=Y(I,"Map"),Z=Y(I,"Promise"),ee=Y(I,"Set"),et=Y(I,"WeakMap");var en="[object Map]",er="[object Promise]",eo="[object Set]",ea="[object WeakMap]",ei="[object DataView]",el=V(X),es=V(J),eu=V(Z),ec=V(ee),ed=V(et),ef=j;(X&&ef(new X(new ArrayBuffer(1)))!=ei||J&&ef(new J)!=en||Z&&ef(Z.resolve())!=er||ee&&ef(new ee)!=eo||et&&ef(new et)!=ea)&&(ef=function(e){var t=j(e),n="[object Object]"==t?e.constructor:void 0,r=n?V(n):"";if(r)switch(r){case el:return ei;case es:return en;case eu:return er;case ec:return eo;case ed:return ea}return t});let eh=ef,ep=function(e){return null!=e&&"object"==typeof e},em=function(e){return ep(e)&&"[object Arguments]"==j(e)};var eg=Object.prototype,ev=eg.hasOwnProperty,ey=eg.propertyIsEnumerable;let eb=em(function(){return arguments}())?em:function(e){return ep(e)&&ev.call(e,"callee")&&!ey.call(e,"callee")},ew=Array.isArray,eE=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991};var eS=t&&!t.nodeType&&t,e_=eS&&e&&!e.nodeType&&e,eT=e_&&e_.exports===eS?I.Buffer:void 0;let eC=(eT?eT.isBuffer:void 0)||function(){return!1};var ek={};ek["[object Float32Array]"]=ek["[object Float64Array]"]=ek["[object Int8Array]"]=ek["[object Int16Array]"]=ek["[object Int32Array]"]=ek["[object Uint8Array]"]=ek["[object Uint8ClampedArray]"]=ek["[object Uint16Array]"]=ek["[object Uint32Array]"]=!0,ek["[object Arguments]"]=ek["[object Array]"]=ek["[object ArrayBuffer]"]=ek["[object Boolean]"]=ek["[object DataView]"]=ek["[object Date]"]=ek["[object Error]"]=ek["[object Function]"]=ek["[object Map]"]=ek["[object Number]"]=ek["[object Object]"]=ek["[object RegExp]"]=ek["[object Set]"]=ek["[object String]"]=ek["[object WeakMap]"]=!1;var eO=t&&!t.nodeType&&t,ex=eO&&e&&!e.nodeType&&e,eI=ex&&ex.exports===eO&&O.process,eN=function(){try{return ex&&ex.require&&ex.require("util").types||eI&&eI.binding&&eI.binding("util")}catch(e){}}(),eA=eN&&eN.isTypedArray;let eR=eA?function(e){return eA(e)}:function(e){return ep(e)&&eE(e.length)&&!!ek[j(e)]};var eD=Object.prototype.hasOwnProperty;let eP=function(e){if(null==e)return!0;if(null!=e&&eE(e.length)&&!F(e)&&(ew(e)||"string"==typeof e||"function"==typeof e.splice||eC(e)||eR(e)||eb(e)))return!e.length;var t=eh(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(S(e))return!function(e){if(!S(e))return _(e);var t=[];for(var n in Object(e))k.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e).length;for(var n in e)if(eD.call(e,n))return!1;return!0},eL=new Map,eM=async(e,t)=>{if(f(t))throw new g("WebSocketClient is not initialized");return eP(e.eventId)&&(e.eventId=b()),new Promise(n=>{eL.set(e.eventId,n),null==t||t.send(e)})},ej=0,eU=null;class eF extends Error{constructor(){super(...arguments),this.name="MaximumRequestCountReached",this.message="Maximum request count reached"}}function ez(){ej=0}function e$(e){let[t,...n]=e.split(" ");return[t,n.join(" ")]}function eH(e,t={}){for(let n of Object.keys(t))e.set(n,t[n])}function eB(e,t=[]){for(let{ident:n,value:r}of t)e.set(n,r)}function eV(e){return Object.fromEntries(e)}function eG(e){return Array.from(e).map(([e,t])=>({ident:e,value:t}))}var eW,eq,eQ,eK=function(e,t,n,r,o){if("m"===r)throw TypeError("Private method is not writable");if("a"===r&&!o)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},eY=function(e,t,n,r){if("a"===n&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};function eX(e,t){let{idOnExternalPlatform:n,firstName:r="",lastName:o="",image:a,customFields:i}=t;e.setId(n),(r||o)&&e.setName(`${null!=r?r:""} ${null!=o?o:""}`.trim()),a&&e.setImage(a),ew(i)&&e.setCustomFieldsFromArray(i)}class eJ{constructor(e,t,n,r){eW.set(this,void 0),eq.set(this,new Map),eQ.set(this,!1),this.id=null,this.name=null,this.image=null,eK(this,eW,null!=r?r:null,"f"),e&&this.setId(e),t&&this.setName(t),n&&this.setImage(n)}getIdOrCreateNewOne(){let e=this.getId();return e||(e=b(),this.id=e),e}destroy(){this.id=null,this.name=null,this.image=null,eK(this,eq,new Map,"f")}getId(){var e;return null!==(e=this.id)&&void 0!==e?e:null}setId(e){this.id=e}getName(){return this.name}setName(e){this.name=e}getImage(){var e;return null!==(e=this.image)&&void 0!==e?e:null}setImage(e){this.image=e}setExists(e){eK(this,eQ,e,"f")}setWebsocketClient(e){eK(this,eW,e,"f")}setCustomField(e,t){return this.setCustomFields({[e]:t})}setCustomFields(e){if(eH(eY(this,eq,"f"),e),eY(this,eQ,"f"))return this.sendCustomFields()}getCustomFields(){return eV(eY(this,eq,"f"))}setCustomFieldsFromArray(e){eB(eY(this,eq,"f"),e)}getCustomFieldsArray(){return eG(eY(this,eq,"f"))}async sendCustomFields(){var e;return e5((e=eG(eY(this,eq,"f")),{eventType:d.ow.SEND_CONSUMER_CUSTOM_FIELDS,data:{customFields:e}}),eY(this,eW,"f"))}}eW=new WeakMap,eq=new WeakMap,eQ=new WeakMap;class eZ{static init(e,t,n,r){return eZ.instance=new eJ(e,t,n,r),eZ.instance}static getInstance(){if(!eZ.instance)throw Error("Init Customer first.");return eZ.instance}}function e0(e,t){let n=eZ.getInstance(),r=null!=e?e:n.getName(),o=null!=t?t:n.getImage(),a={};if("string"==typeof r&&r.length>0){let[e,t]=e$(r);a={firstName:e,lastName:t}}return o&&(a.image=o),Object.assign({idOnExternalPlatform:n.getIdOrCreateNewOne()},a)}let e1=function(e){return null==e};function e2(){let e=h.BRAND_ID,t=h.CHANNEL_ID;if(e1(e)||isNaN(e)||e1(t))throw new g(`Cannot get BrandId and ChannelId from SDKVariableStorage brandId (${e}) | channelId (${t})`);return{brandId:e,channelId:t}}let e3=function(e){return void 0===e};function e4(e){let t=h.DESTINATION,n=h.VISIT_ID,r=h.VISITOR_ID,{eventType:o,data:a,consumerIdentity:i=e0(),destination:l=t?{id:t}:{},visitor:s=r?{id:r}:{},visit:u=n?{id:n}:{}}=e,{brandId:c,channelId:d}=e2();if(e3(o))throw new g(`Cannot create an event payload because of missing eventType (${o})`);return{eventType:o,brand:{id:Number(c)},channel:{id:d},consumerIdentity:i,data:a,destination:l,visitor:s,visit:u}}function e6(e,t=b(),n=c.V.CHAT_WINDOW_EVENT){return{action:n,eventId:t,payload:e}}async function e5(e,t){return h.CLIENT_SIDE_EVENTS_THROTTLING&&function(){if(ej+=1,null===eU&&(eU=setInterval(ez,5e3)),ej>100)throw new g(new eF)}(),eM(e6(e4(e)),t)}function e9(e,t){return Object.assign(Object.assign(Object.assign({},w(t)),e0()),{eventType:d.ow.RECONNECT_CONSUMER,data:{accessToken:{token:e.token}}})}let e8=null;function e7(e,t){null!==e8&&clearTimeout(e8),e8=setTimeout(t,1e3*function(e){let t=Math.round(.9*e);return t<20?20:t}(e.expiresIn))}let te=e=>{var t;let n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.status;return(null==e?void 0:e.type)===d.vc.CONSUMER_AUTHORIZED&&"success"===n};function tt(e){var t,n;return(null==e?void 0:e.type)===d.vc.TOKEN_REFRESHED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.accessToken)||void 0===n?void 0:n.token)}var tn=i(198),tr=i.n(tn),to=i(442);let ta=()=>navigator.language,ti=()=>Intl.DateTimeFormat().resolvedOptions().timeZone;function tl(e){switch(e){case"mobile":return to.bq.MOBILE;case"tablet":return to.bq.TABLET;default:return to.bq.DESKTOP}}let ts=(e={})=>{var t,n,r,o;let a=new(tr())(navigator.userAgent),{country:i="",location:l=ti(),language:s=ta(),ip:u=null}=e;return{browser:null!==(t=a.getBrowser().name)&&void 0!==t?t:null,browserVersion:null!==(n=a.getBrowser().version)&&void 0!==n?n:null,country:i,ip:u,language:s,location:l,os:null!==(r=a.getOS().name)&&void 0!==r?r:null,osVersion:null!==(o=a.getOS().version)&&void 0!==o?o:null,deviceType:tl(a.getDevice().type),applicationType:to.Xr.BROWSER}},tu="SdkVersionNotSupported";class tc extends Error{constructor(){super(...arguments),this.name=tu,this.message="Please update to the latest ChatSDK version"}}function td(e){var t;return(null===(t=null==e?void 0:e.error)||void 0===t?void 0:t.errorCode)===tu}function tf(e){if(td(e))throw new tc;return e}var th=i(796);let tp=()=>{var e;return{Accept:"application/json","Content-Type":"application/json",[th.Um]:null!==(e=h.APP_NAME)&&void 0!==e?e:"","x-sdk-platform":"web","x-sdk-version":y}};async function tm(e){let t;try{t=await e.json()}catch(n){t=e.statusText}return t}async function tg(e,t,n=ta()){let r=`${n}`.split("-").join("_"),o=h.ENDPOINT_CHAT,a=await fetch(`${o}/chat/1.0/brand/${e}/channel/${t}?locale=${r}`,{method:"GET",headers:Object.assign({},tp())});if(!a.ok){if(td(await tm(a)))throw new tc;throw new g(`Failed to fetch channel info. Status (${a.status})`,{response:a})}return a.json()}!function(e){e.ANONYMOUS="anonymous",e.SECURED_COOKIES="securedCookies",e.THIRD_PARTY="thirdParty"}(tW||(tW={}));let tv=()=>{var e;return null!==(e=h.SECURED_SESSION)&&void 0!==e?e:null},ty=()=>h.SECURED_SESSION===tW.ANONYMOUS,tb=()=>null!==tv();!function(e){e.AU1="AU1",e.CA1="CA1",e.EU1="EU1",e.JP1="JP1",e.NA1="NA1",e.UK1="UK1",e.custom="custom"}(tq||(tq={}));let tw=e=>{h.ENDPOINT_GATEWAY=e.gateway,h.ENDPOINT_CHAT=e.chat,h.ENDPOINT_AUTHORIZE=e.authorize};var tE=i(0);let tS=Object.assign(Object.assign(Object.assign({},tE.m),d.vc),{AGENT_TYPING_STARTED:"AgentTypingStarted",AGENT_TYPING_ENDED:"AgentTypingEnded",ASSIGNED_AGENT_CHANGED:"AssignedAgentChanged",CONTACT_CREATED:"ContactCreated",CONTACT_STATUS_CHANGED:"ContactStatusChanged",CONTACT_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED:"ContactToRoutingQueueAssignmentChanged"});class t_ extends CustomEvent{}class tT{constructor(){this.middlewares=[]}register(e){this.middlewares.push(e)}process(e){if(e1(e))return null;let t=e;for(let e of this.middlewares){if(null===t)return null;t=e(t)}return t}}let tC=EventTarget;function tk(e){return"outbound"===(null==e?void 0:e.direction)}var tO=i(555),tx=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};let tI={id:"",data:null,type:void 0,createdAt:new Date};function tN(e){var t;if(!("eventId"in e))return tI;if("error"in e)return{createdAt:(0,tO.TG)(null!==(t=e.createdAt)&&void 0!==t?t:(new Date).toString()),data:null,error:e.error,id:e.eventId};let n="eventType"in e?e.eventType:void 0;if("data"in e)return{createdAt:(0,tO.TG)(e.createdAt),context:e.context,data:e.data,id:e.eventId,type:n};if(!1===eP(null==e?void 0:e.postback)){let{postback:{data:t,eventType:n},eventId:r}=e;return{type:n,data:Object.assign(Object.assign({},tx(e,["postback","eventId"])),t),createdAt:(0,tO.TG)(e.createdAt),id:r}}let{eventId:r}=e;return Object.assign(Object.assign({data:void 0},tx(e,["eventId"])),{id:r,type:n,createdAt:(0,tO.TG)(e.createdAt)})}let tA={[tS.SENDER_TYPING_STARTED]:function(e){return tk(e.data)?Object.assign(Object.assign({},e),{type:tS.AGENT_TYPING_STARTED}):e},[tS.SENDER_TYPING_ENDED]:function(e){return tk(e.data)?Object.assign(Object.assign({},e),{type:tS.AGENT_TYPING_ENDED}):e},[tS.CASE_INBOX_ASSIGNEE_CHANGED]:function(e){return Object.assign(Object.assign({},e),{type:tS.ASSIGNED_AGENT_CHANGED})},[tS.CASE_CREATED]:function(e){return Object.assign(Object.assign({},e),{type:tS.CONTACT_CREATED})},[tS.CASE_STATUS_CHANGED]:function(e){return Object.assign(Object.assign({},e),{type:tS.CONTACT_STATUS_CHANGED})},[tS.CASE_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED]:function(e){return Object.assign(Object.assign({},e),{type:tS.CONTACT_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED})},[tS.LIVECHAT_RECOVERED]:function(e){let t=e.data.contactHistory.map(tN).map(tR).filter(e=>!!e);return Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{contactHistory:t})})},[tS.THREAD_RECOVERED]:function(e){let t=e.data.contactHistory.map(tN).map(tR).filter(e=>!!e);return Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{contactHistory:t})})}};function tR(e){return e.type&&void 0!==tA[e.type]?tA[e.type](e):e}function tD(e){let t=!1===e3(null==e?void 0:e.id);return!1==(!1===e3(e.error))&&t}class tP extends g{}var tL=i(434);let tM="sdkTransactionToken",tj="Cannot refresh ThirdParty token";class tU extends g{constructor(e="Aborted"){super(e),this.name="AbortError"}}async function tF(e,t,n){return async function(e,t){let n=new AbortController,r=Object.assign({headers:Object.assign({},tp()),signal:n.signal},t),o=()=>{n.abort(new tU("Fetch aborted because the window is closing"))};null==window||window.addEventListener("beforeunload",()=>o);let a=await fetch(e,r);if(!a.ok)throw a;return a.json()}(e,Object.assign({method:"POST",body:JSON.stringify(null!=t?t:{})},n))}function tz(){var e,t;if(!h.ENDPOINT_AUTHORIZE)throw new g("Authorize hostname is not set");let n=new URL(h.ENDPOINT_AUTHORIZE);return n.pathname="/oauth/token",n.searchParams.append("brandId",String(h.BRAND_ID)),n.searchParams.append("channelId",null!==(e=h.CHANNEL_ID)&&void 0!==e?e:""),n.searchParams.append("visitorId",null!==(t=h.VISITOR_ID)&&void 0!==t?t:""),n.toString()}function t$(){var e;return null!==(e=h.THIRD_PARTY_TOKEN)&&void 0!==e?e:null}async function tH(){let e=t$();if(f(e))throw new g(tj);let t=tz();try{let{thirdParty:n}=await tF(t,{thirdParty:{grant_type:"refresh_token",refresh_token:e.refresh_token}},{credentials:"include"});if(!n)throw new g(tj);return tB(n)}catch(e){if(e instanceof g)throw e;throw new g(tj,e)}}function tB(e){h.THIRD_PARTY_TOKEN=e,e7({expiresIn:e.expires_in},tH)}class tV extends Error{constructor(e,t=""){super(`[WebSocketClientError]: ${e}${t?` (${t})`:""}`),this.name="WebSocketClientError"}}let tG=EventTarget;var tW,tq,tQ,tK,tY,tX,tJ,tZ,t0=function(e,t,n,r,o){if("m"===r)throw TypeError("Private method is not writable");if("a"===r&&!o)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},t1=function(e,t,n,r){if("a"===n&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class t2{constructor(e,t){this.onError=e,this.socketURLGetter=t,tQ.add(this),tK.set(this,null),tY.set(this,void 0),tX.set(this,!1),tZ.set(this,e=>{t1(this,tY,"f").dispatchEvent(e)}),t0(this,tY,new tG,"f")}async connect(){var e,t;t1(this,tQ,"m",tJ).call(this),null===(t=null===(e=t1(this,tK,"f"))||void 0===e?void 0:e.socket)||void 0===t||t.reconnect()}disconnect(){var e;null===(e=t1(this,tK,"f"))||void 0===e||e.socket.close()}reconnect(){var e;t1(this,tQ,"m",tJ).call(this),null===(e=t1(this,tK,"f"))||void 0===e||e.socket.reconnect()}send(e){var t;let n=JSON.stringify(e);null===(t=t1(this,tK,"f"))||void 0===t||t.send(n)}on(e,t){t1(this,tY,"f").addEventListener(e,t)}off(e,t){t1(this,tY,"f").removeEventListener(e,t)}_errorHandler(e){let t;let n=e.detail;if(n instanceof ErrorEvent&&(t=new tV("Connection error",n.message)),n instanceof CloseEvent&&(t=new tV("Connection closed",n.reason)),void 0===t&&(t=new tV("Unknown error",n.type)),"function"!=typeof this.onError)throw t;this.onError(t)}}tK=new WeakMap,tY=new WeakMap,tX=new WeakMap,tZ=new WeakMap,tQ=new WeakSet,tJ=function(){var e,t,n,r,o,a;let i=!tb(),l=(null!==(e=h.ENDPOINT_GATEWAY)&&void 0!==e?e:"").startsWith("wss");t0(this,tK,(0,u.NP)(this.socketURLGetter,{forceSecureProtocol:l,startClosed:!0,heartbeatAfterAuthorize:i,maxRetries:0}),"f");let s=this._errorHandler.bind(this);null===(t=t1(this,tK,"f"))||void 0===t||t.addEventListener(u.nF.CLOSE,s),null===(n=t1(this,tK,"f"))||void 0===n||n.addEventListener(u.nF.ERROR,s),null===(r=t1(this,tK,"f"))||void 0===r||r.addEventListener(u.nF.OPEN,e=>{var t;null===(t=t1(this,tK,"f"))||void 0===t||t.socket.setMaxRetires(20),t0(this,tX,!0,"f"),t1(this,tZ,"f").call(this,e)}),null===(o=t1(this,tK,"f"))||void 0===o||o.addEventListener(u.nF.CLOSE,e=>{t1(this,tX,"f")||t1(this,tY,"f").dispatchEvent(new CustomEvent(u.nF.AUTHORIZATION_FAILED)),t1(this,tZ,"f").call(this,e)}),null===(a=t1(this,tK,"f"))||void 0===a||a.addEventListener(u.nF.MESSAGE,t1(this,tZ,"f"))};var t3=i(168);class t4 extends g{}let t6=async(e,t,n,r)=>{let o=await (async e=>{let t=await new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{t(r)},r.onerror=e=>{var t,r;return n(null===(r=null===(t=e.target)||void 0===t?void 0:t.error)||void 0===r?void 0:r.message)},r.readAsDataURL(e)});if(null!==t.error)throw new g(`Cannot create payload for attachment upload because of error (${t.error.message})`);if("string"!=typeof t.result)throw new g(`Cannot create payload for attachment upload because of missing: reader result (${t.result})`);return{url:t.result,name:e.name,mimeType:e.type}})(e),a=await async function(e,t,n,r){let{url:o,name:a,mimeType:i}=n,l={content:o.split(";base64,")[1],fileName:a,mimeType:i},s=await fetch(`${h.ENDPOINT_CHAT}/chat/1.0/brand/${e}/channel/${t}/attachment`,{method:"POST",body:JSON.stringify(l),headers:Object.assign({},tp()),signal:r});if(!s.ok){if(td(await tm(s)))throw new tc;throw new g(`Failed to upload Attachments. Status (${s.status})`)}return s.json()}(t,n,o,r);if(!1===e3(null==a?void 0:a.fileUrl))return{url:a.fileUrl,friendlyName:o.name};if(function(e){return!1===e3(null==e?void 0:e.allowedFileSize)}(a))throw new t4("Upload attachment failed",a);throw new g(`Unknown file upload response (${a})`)},t5=e=>Array.from(e).every(e=>"url"in e&&"friendlyName"in e),t9=async(e,t,n,r)=>Promise.all(Array.from(e).map(e=>t6(e,t,n,r))),t8=async(e,t,n={})=>{let{brandId:r,channelId:o}=e2();try{let a=t5(e)?e:await t9(e,r,o),{messageId:i=b(),browserFingerprint:l=ts()}=n;return{messageContent:{type:tL.G.TEXT,payload:{text:""}},attachments:a,browserFingerprint:l,thread:{idOnExternalPlatform:t},idOnExternalPlatform:i,consumer:{customFields:[]},consumerContact:{customFields:[]}}}catch(e){if(e instanceof t4)throw e;if(e instanceof Error)throw new g(`Send attachment failed because of (${e.message})`);throw new g("Unknown error during file upload")}};function t7(e){var t,n;return e.type===tS.CONTACT_STATUS_CHANGED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.case)||void 0===n?void 0:n.id)}function ne(e){var t,n;return e.type===tS.CONTACT_CREATED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.case)||void 0===n?void 0:n.id)}function nt(e){var t,n;return e.type===tS.CONTACT_TO_ROUTING_QUEUE_ASSIGNMENT_CHANGED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.case)||void 0===n?void 0:n.id)}function nn(e){return e.type===tE.m.CONTACT_RECIPIENTS_CHANGED}let nr=(e,t,n,r=ts())=>({messageContent:e,browserFingerprint:r,idOnExternalPlatform:t,thread:{idOnExternalPlatform:n},consumer:{customFields:[]},consumerContact:{customFields:[]},attachments:[]});function no(e){var t;return e.type===d.vc.MORE_MESSAGES_LOADED&&void 0!==(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.messages)}let na=e=>({eventType:d.ow.LOAD_MORE_MESSAGES,data:e});class ni extends Promise{constructor(e){let t=new AbortController,n=t.signal;super((t,r)=>{n.addEventListener("abort",()=>{r(new tU(this.abortReason))}),null==e||e(t,r,n)}),this.abort=e=>{this._abortReason=null!=e?e:"Aborted",t.abort()}}get abortReason(){return this._abortReason}}ni.from=e=>e instanceof ni?e:new ni((t,n)=>{e.then(t).catch(n)});class nl extends g{}var ns=i(953);let nu=e=>{var t,n,r,o,a,i;return e.direction===ns.T.INBOUND?null!==(n=null===(t=e.authorEndUserIdentity)||void 0===t?void 0:t.fullName)&&void 0!==n?n:"":`${null!==(o=null===(r=e.authorUser)||void 0===r?void 0:r.firstName)&&void 0!==o?o:""} ${null!==(i=null===(a=e.authorUser)||void 0===a?void 0:a.surname)&&void 0!==i?i:""}`.trim()};function nc(e){let t=!1===e3(e.id),n=!1===e3(e.direction),r=!1===e3(e.messageContent);return t&&n&&r}function nd(e){return e.type===tE.m.MESSAGE_CREATED}function nf(e){return e.type===tE.m.MESSAGE_SENT}function nh(e){return e.type===tE.m.MESSAGE_READ_CHANGED}class np extends g{}let nm=e=>e.type===d.vc.THREAD_METADATA_LOADED&&void 0!==e.data.lastMessage,ng=e=>{let t=e.data;return!1!=(!1===e1(t))&&!1!=(!1===e1(null==t?void 0:t.messages))&&!1!=(e.type===d.vc.THREAD_RECOVERED||e.type===d.vc.LIVECHAT_RECOVERED)&&!1!==e1(e.error)&&!1!=(!1===e1(null==t?void 0:t.thread))};function nv(e){return e.type===d.vc.THREAD_ARCHIVED}class ny extends g{}function nb(e){let t={eventType:d.ow.RECOVER_THREAD,data:{}};return void 0===e?t:Object.assign(Object.assign({},t),{data:{thread:{idOnExternalPlatform:e}}})}class nw extends g{}class nE extends g{}class nS{constructor(e,t,n,r,o={},a=!1){this._exists=!1,this._typingTimeoutID=void 0,this._isAuthorizationEnabled=!1,this._customFields=new Map,this._typingPreviewText="",this.idOnExternalPlatform=e,this._websocketClient=t,this._messageEmitter=n,this._customer=r,this._isAuthorizationEnabled=a,eH(this._customFields,o),this._registerEventHandlers()}recover(){return new ni(async(e,t)=>{let n=await e5(nb(this.idOnExternalPlatform),this._websocketClient);ng(n)?e(n.data):t(new nE("Thread not found",n))})}async sendMessage(e){return function(e){if(e.messageContent.type===tL.G.TEXT&&!(e.attachments.length>0)&&!1!==eP(e.messageContent.payload.text))throw new tP("Message content cannot be empty for text message")}(e),(async(e,t)=>{let n={eventType:d.ow.SEND_MESSAGE,data:e},r=await e5(n,t);if(tD(r))return r;throw new tP("Send message failed",r)})(this._mergeCustomFieldsAndAccessTokenWithMessageData(e,!1),this._websocketClient)}async sendTextMessage(e,t={}){let{messageId:n=b(),browserFingerprint:r=ts()}=t,o=nr({payload:{text:e},type:tL.G.TEXT},n,this.idOnExternalPlatform,r);return this.sendMessage(o)}async sendPostbackMessage(e,t,n={}){let{messageId:r=b(),browserFingerprint:o=ts()}=n,a=nr({payload:{text:t,postback:e},postback:e,type:tL.G.TEXT},r,this.idOnExternalPlatform,o);return this.sendMessage(a)}async sendOutboundMessage(e){return(async(e,t)=>{let n={eventType:d.ow.SEND_OUTBOUND,data:e},r=await e5(n,t);if(tD(r))return r;throw new tP("Send Outbound message failed",r)})(this._mergeCustomFieldsAndAccessTokenWithMessageData(e,!0),this._websocketClient)}async loadMoreMessages(){var e;let{scrollToken:t,oldestMessageDatetime:n}=null!==(e=h.THREAD_DATA)&&void 0!==e?e:{};if(eP(t))return null;let r={scrollToken:String(t),oldestMessageDatetime:n,thread:{idOnExternalPlatform:this.idOnExternalPlatform}},o=await e5(na(r),this._websocketClient);if(no(o))return o;throw new ny("Load more messages failed",o)}async lastMessageSeen(){var e;return e5((e=this.idOnExternalPlatform,{eventType:d.ow.MESSAGE_SEEN,data:{thread:{idOnExternalPlatform:e}}}),this._websocketClient)}async sendAttachments(e,t={}){if(e3(e)||0===e.length)throw new g("FileList must be provided to sendAttachment method");let n=await t8(e,this.idOnExternalPlatform,t);return this.sendMessage(n)}keystroke(e=1e3,t){var n;this._typingTimeoutID||e5((n=this.idOnExternalPlatform,{eventType:d.ow.SENDER_TYPING_STARTED,data:{thread:{idOnExternalPlatform:n}}}),this._websocketClient),clearTimeout(this._typingTimeoutID),this._typingTimeoutID=setTimeout(()=>{this._stopTypingCallback(t)},e)}stopTyping(){this._stopTypingCallback()}_stopTypingCallback(e){var t;clearTimeout(this._typingTimeoutID),this._typingTimeoutID=void 0,e5((t=this.idOnExternalPlatform,{eventType:d.ow.SENDER_TYPING_ENDED,data:{thread:{idOnExternalPlatform:t}}}),this._websocketClient),"function"==typeof e&&e()}keystrokeForPreview(e,t=1250){this._typingPreviewText=e,this._typingForPreviewTimeoutID||(this._typingForPreviewTimeoutID=setTimeout(()=>{this.stopTypingForPreview()},t))}stopTypingForPreview(e=!0){clearTimeout(this._typingForPreviewTimeoutID),this._typingForPreviewTimeoutID=void 0;let t=this._typingPreviewText;this._typingPreviewText="",!1!==e&&this.sendMessagePreview(t)}async getMetadata(){var e;let t=await e5((e=this.idOnExternalPlatform,{eventType:d.ow.LOAD_THREAD_METADATA,data:{thread:{idOnExternalPlatform:e}}}),this._websocketClient);if(nm(t))return t;throw new np("Get metadata failed",t)}onThreadEvent(e,t){let n;let r=(n=this.idOnExternalPlatform,e=>{var r,o,a,i,l,s,u,c;(null!==(u=null!==(l=null!==(a=null===(o=null==(r=e.detail.data)?void 0:r.thread)||void 0===o?void 0:o.idOnExternalPlatform)&&void 0!==a?a:null===(i=null==r?void 0:r.case)||void 0===i?void 0:i.threadIdOnExternalPlatform)&&void 0!==l?l:null===(s=null==r?void 0:r.message)||void 0===s?void 0:s.threadIdOnExternalPlatform)&&void 0!==u?u:null===(c=null==r?void 0:r.messagePreview)||void 0===c?void 0:c.threadIdOnExternalPlatform)===n&&t(e)});return this._messageEmitter.addEventListener(e,r),()=>{this._messageEmitter.removeEventListener(e,r)}}async sendCustomFields(e){var t,n;return e5((t=eG(this._customFields).filter(t=>!e||e.includes(t.ident)),n=this.idOnExternalPlatform,{eventType:d.ow.SET_CONSUMER_CONTACT_CUSTOM_FIELD,data:{customFields:t,thread:{idOnExternalPlatform:n}}}),this._websocketClient)}async setCustomFields(e){eH(this._customFields,e),!1!==this._exists&&await this.sendCustomFields(Object.keys(e))}setCustomField(e,t){return this.setCustomFields({[e]:t})}async archive(){var e;let t=await e5((e=this.idOnExternalPlatform,{eventType:d.ow.ARCHIVE_THREAD,data:{thread:{idOnExternalPlatform:e}}}),this._websocketClient);if(nv(t))return!0;throw new nl("Archive Thread failed",t)}async setName(e){var t;let n=(t=this.idOnExternalPlatform,{eventType:d.ow.UPDATE_THREAD,data:{thread:{idOnExternalPlatform:t,threadName:e}}}),r=await e5(n,this._websocketClient);if(e3(r.error))return!0;throw new nw("Set Thread name failed",r)}async sendMessagePreview(e){let t;let n=(t=this.idOnExternalPlatform,{eventType:d.ow.SEND_MESSAGE_PREVIEW,data:{thread:{idOnExternalPlatform:t},messageContent:{payload:{text:e},type:tL.G.TEXT}}});await e5(n,this._websocketClient)}async sendTranscript(e,t){return e5({eventType:d.ow.SEND_TRANSCRIPT,data:{consumerContact:{id:e},consumerRecipients:[{idOnExternalPlatform:t}]}},this._websocketClient)}_setThreadAndCustomerExists(){var e;this._exists=!0,null===(e=this._customer)||void 0===e||e.setExists(!0)}_clearCustomFieldsOnContactStatusChangedToClosed(e){let t=e.detail;t7(t)&&t.data.case.status===t3.P.CLOSED&&this._customFields.clear()}_mergeCustomFieldsAndAccessTokenWithMessageData(e,t){var n,r,o,a,i,l;let s,u;let c=t$(),d=m();this._isAuthorizationEnabled&&(c||d)&&(s={token:null!==(n=null==c?void 0:c.access_token)&&void 0!==n?n:null==d?void 0:d.token}),eB(this._customFields,e.consumerContact.customFields);let f={customFields:eG(this._customFields)};return t||(null===(r=this._customer)||void 0===r||r.setCustomFieldsFromArray(null!==(a=null===(o=e.consumer)||void 0===o?void 0:o.customFields)&&void 0!==a?a:[]),u={customFields:null!==(l=null===(i=this._customer)||void 0===i?void 0:i.getCustomFieldsArray())&&void 0!==l?l:[]}),Object.assign(Object.assign({},e),{accessToken:s,consumer:u,consumerContact:f})}_registerEventHandlers(){this.onThreadEvent(tS.CASE_CREATED,()=>this._setThreadAndCustomerExists()),this.onThreadEvent(tS.CONTACT_CREATED,()=>this._setThreadAndCustomerExists()),this.onThreadEvent(tS.THREAD_RECOVERED,()=>this._setThreadAndCustomerExists()),this.onThreadEvent(tS.CONTACT_STATUS_CHANGED,e=>this._clearCustomFieldsOnContactStatusChangedToClosed(e))}}function n_(e){let t={eventType:d.ow.RECOVER_LIVECHAT,data:{}};return void 0===e?t:Object.assign(Object.assign({},t),{data:{thread:{idOnExternalPlatform:e}}})}class nT extends nS{constructor(e,t,n,r,o={},a=!1){super(e,t,n,r,o,a),this._isInitialized=!1,this._canSendMessage=!0,this._registerLivechatEventHandlers()}recover(){return new ni(async(e,t)=>{let n=await e5(n_(this.idOnExternalPlatform),this._websocketClient);ng(n)?e(n.data):t(new nE("Thread not found",n))})}async sendMessage(e){if(!1===this._canSendMessage)throw new g("Cannot send more messages to Contact");return super.sendMessage(e)}async startChat(e="Begin conversation"){if(this._isInitialized)throw new g("Chat is already initialized");try{let t=await this.sendTextMessage(e);return this._isInitialized=!0,t}catch(e){if(e instanceof Error)throw new g(`Sending initial message failed because of (${e.message})`);return}}async endChat(){var e,t;let n=null!==(e=h.THREAD_DATA)&&void 0!==e?e:{},r=null==n?void 0:n.contactId;if(e3(r))throw new g("Cannot end Chat because of missing ContactId in the storage");await e5((t=this.idOnExternalPlatform,{eventType:d.ow.END_CONTACT,data:{thread:{idOnExternalPlatform:t},contact:{id:r}}}),this._websocketClient)}async loadMoreMessages(){var e;let{scrollToken:t,oldestMessageDatetime:n,contactId:r}=null!==(e=h.THREAD_DATA)&&void 0!==e?e:{};if(eP(t)||eP(r))return null;let o={scrollToken:String(t),oldestMessageDatetime:n,thread:{idOnExternalPlatform:this.idOnExternalPlatform},contact:{id:r}},a=await e5(na(o),this._websocketClient);if(no(a))return a;throw new ny("Load more messages failed",a)}_registerLivechatEventHandlers(){this.onThreadEvent(tS.LIVECHAT_RECOVERED,e=>{ng(e.detail)&&this._setThreadAndCustomerExists()})}}let nC=e=>!f(e)&&"threads"in e;function nk(e){var t;let n=null!==(t=h.THREAD_DATA)&&void 0!==t?t:{};h.THREAD_DATA=Object.assign(Object.assign({},n),{contactId:e})}function nO(e){return ne(e)&&nk(e.data.case.id),ng(e)&&nk(e.data.contact.id),e}function nx(e){var t,n,r,o;let a=null===(t=(o=null==(r=e.messages)?0:r.length)?r[o-1]:void 0)||void 0===t?void 0:t.createdAt,i=null!==(n=h.THREAD_DATA)&&void 0!==n?n:{};h.THREAD_DATA=Object.assign(Object.assign({},i),{scrollToken:e.scrollToken,oldestMessageDatetime:e3(a)?"":a})}function nI(e){if(ng(e)){let{messages:t,messagesScrollToken:n}=e.data;nx({messages:t,scrollToken:n})}if(no(e)){let{scrollToken:t,messages:n}=e.data;nx({scrollToken:t,messages:n})}return e}function nN(e){if("function"!=typeof e)throw Error(`Expected a callable function, got ${e}`)}var nA,nR,nD,nP,nL,nM,nj,nU,nF,nz,n$,nH,nB,nV,nG,nW,nq,nQ,nK=function(e,t,n,r,o){if("m"===r)throw TypeError("Private method is not writable");if("a"===r&&!o)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},nY=function(e,t,n,r){if("a"===n&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class nX{constructor(e){var t,n,r;if(nA.add(this),this.channelId="",nR.set(this,void 0),nD.set(this,void 0),nP.set(this,void 0),nL.set(this,void 0),nM.set(this,void 0),nj.set(this,null),nU.set(this,new Map),nF.set(this,new Map),nz.set(this,new tT),n$.set(this,void 0),nH.set(this,function(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}()),nW.set(this,async()=>{var e;let t=m();if(f(t))return;let n=await e5((e=t.token,{eventType:d.ow.REFRESH_TOKEN,data:{accessToken:{token:e}}}),nY(this,nj,"f"));if(tt(n))return p(n.data.accessToken),void e7(n.data.accessToken,nY(this,nW,"f"));throw new v("An error occurred while refreshing the access token",n.error)}),void 0===e)throw new g("No options was provided for initialization of ChatSdk");nK(this,nD,e.customerImage,"f"),nK(this,nP,e.customerName,"f"),nK(this,nL,e.customerId,"f"),h.AUTHORIZATION_CODE=e.authorizationCode,h.BRAND_ID=e.brandId,h.CHANNEL_ID=e.channelId,h.APP_NAME=null!==(t=e.appName)&&void 0!==t?t:"chat-web-sdk",h.APP_VERSION=`${null!==(n=e.appVersion)&&void 0!==n?n:0}`,h.DESTINATION=e.destinationId,h.VISIT_ID=e.visitId,h.VISITOR_ID=e.visitorId,h.LANGUAGE=null!==(r=e.language)&&void 0!==r?r:ta(),h.SECURED_SESSION=(e=>{if(e1(e))return null;if(!1===Object.values(tW).includes(e))throw new g(`Expected a SecureSessions value, got ${e}`);return e})(e.securedSession),h.CLIENT_SIDE_EVENTS_THROTTLING=e.isClientSideEventsThrottlingEnabled,nK(this,nR,eZ.init(),"f"),void 0!==e.customerId&&function(e){if(tb()&&!1===ty()&&void 0!==e)throw new g("The CustomerId cannot be set when secured sessions are enabled");"string"==typeof e&&eZ.getInstance().setId(e)}(e.customerId),e.cacheStorage&&(nN(e.cacheStorage.getItem),nN(e.cacheStorage.setItem),nN(e.cacheStorage.removeItem),h.CACHE_STORAGE=e.cacheStorage);let{brandId:o,channelId:a}=e2();this.onError=e.onError,this.onRawEvent=e.onRawEvent,nY(this,nz,"f").register(tR),nY(this,nz,"f").register(tf),nY(this,nz,"f").register(nI),nY(this,nz,"f").register(nO),nK(this,n$,new tC,"f");try{if(isNaN(o))throw Error("Missing BrandID");if(void 0===a)throw Error("Missing ChannelId");if(void 0===e.customerId&&!tb())throw Error("Missing CustomerId");this.channelId=a,this.isLivechat=e.isLivechat,nK(this,nM,tv()===tW.THIRD_PARTY||e.isAuthorizationEnabled,"f"),nY(this,nA,"m",nq).call(this,e)}catch(e){nY(this,nA,"m",nB).call(this,e)}}async connect(e){return e&&(h.AUTHORIZATION_CODE=e),null===nY(this,nj,"f")&&(await nY(this,nA,"m",nG).call(this),tb()&&await this.ready(),void 0!==nY(this,nL,"f")&&nY(this,nR,"f").setId(nY(this,nL,"f")),void 0!==nY(this,nP,"f")&&nY(this,nR,"f").setName(nY(this,nP,"f")),void 0!==nY(this,nD,"f")&&nY(this,nR,"f").setImage(nY(this,nD,"f")),null!==nY(this,nj,"f")&&nY(this,nR,"f").setWebsocketClient(nY(this,nj,"f")),nY(this,nH,"f").resolve(),!0)}async ready(){return nY(this,nH,"f").promise}async getChannelInfo(){return tg(h.BRAND_ID,h.CHANNEL_ID,h.LANGUAGE)}async getChannelAvailability(){return async function(e,t){let n=h.ENDPOINT_CHAT,r=await fetch(`${n}/chat/1.0/brand/${e}/channel/${t}/availability`,{method:"GET",headers:Object.assign({},tp())});if(!r.ok){if(td(await tm(r)))throw new tc;throw new g(`Failed to fetch channel availability. Status (${r.status})`,{response:r})}return r.json()}(h.BRAND_ID,h.CHANNEL_ID)}async authorize(e,t){var n,r,o,a;await this.ready();let i=m();if(null!==i)try{return await async function(e,t,n,r){let o=e9(n,r),a=await e5(o,e);if(void 0!==a.error)throw new v("Authorization reconnect failed",a.error);return e7(n,t),{reconnected:!0}}(nY(this,nj,"f"),nY(this,nW,"f"),i,t)}catch(e){}let l=async function(e,t){if(!e3(e)&&!e3(t))return{isAuthorizationEnabled:e,isLivechat:t};let n=await tg(h.BRAND_ID,h.CHANNEL_ID);return{isAuthorizationEnabled:n.isAuthorizationEnabled,isLivechat:n.isLiveChat}}(nY(this,nM,"f"),this.isLivechat),s=eM(e6(e4(function(e,t=b()){return Object.assign({eventType:d.ow.AUTHORIZE_CUSTOMER,data:{authorization:{authorizationCode:e},disableChannelInfo:!0,sdkVersion:y,sdkPlatform:"web"}},w(t))}(null!==(n=null!=e?e:h.AUTHORIZATION_CODE)&&void 0!==n?n:null,t)),b(),c.V.REGISTER),nY(this,nj,"f")),[u,f]=await Promise.all([s,l]);if(!te(u))throw null===(r=nY(this,nj,"f"))||void 0===r||r.disconnect(),new v("Authorization failed",u.error);let{consumerIdentity:E,customer:S,contact:_}=u.data,T=null==E?void 0:E.idOnExternalPlatform;if(e1(T)||""===T)throw null===(o=nY(this,nj,"f"))||void 0===o||o.disconnect(),new g("Invalid customer identity");return eX(nY(this,nR,"f"),E),(null==S?void 0:S.customFields)&&nY(this,nR,"f").setCustomFieldsFromArray(S.customFields),(null==_?void 0:_.customFields)&&eB(nY(this,nU,"f"),_.customFields),nK(this,nM,f.isAuthorizationEnabled,"f"),this.isLivechat=f.isLivechat,void 0!==(null===(a=u.data.accessToken)||void 0===a?void 0:a.token)&&(p(u.data.accessToken),e7(u.data.accessToken,nY(this,nW,"f"))),u.data}async generateAuthorizationToken(e,t){let n=await e5({eventType:d.ow.GENERATE_AUTHORIZATION_TOKEN,data:{thread:{idOnExternalPlatform:e},url:t}},nY(this,nj,"f"));if(!("authorizationToken"in n.data))throw new g("Invalid response from generate authorization token (generateAuthorizationToken)");let{authorizationToken:r}=n.data;return r}onChatEvent(e,t){return nY(this,n$,"f").addEventListener(e,t),()=>{nY(this,n$,"f").removeEventListener(e,t)}}getCustomer(){return nY(this,nR,"f")}getThread(e){if(f(nY(this,nj,"f")))throw new g("Cannot get thread because websocket is disconnected");if(e1(e))throw new g("Cannot get thread because id is undefined");let t=nY(this,nF,"f").get(e);if(!e3(t))return t;if(!0===this.isLivechat){let t=new nT(e,nY(this,nj,"f"),nY(this,n$,"f"),nY(this,nR,"f"),this._getContactCustomFieldsFromQueue(),nY(this,nM,"f"));return nY(this,nF,"f").set(e,t),t}let n=new nS(e,nY(this,nj,"f"),nY(this,n$,"f"),nY(this,nR,"f"),this._getContactCustomFieldsFromQueue(),nY(this,nM,"f"));return nY(this,nF,"f").set(e,n),n}async getThreadList(){if(f(nY(this,nj,"f")))throw new g("Cannot get thread list because websocket is disconnected");let e={eventType:d.ow.FETCH_THREAD_LIST,data:{}},t=await e5(e,nY(this,nj,"f"));if(!nC(t.data))throw new g("Invalid response from fetch thread list (getThreadList)");return t.data.threads}getWebsocketClient(){return nY(this,nj,"f")}async sendOfflineMessage(e){return(async(e,t)=>{let n=(e=>{let[t,...n]=e.name.split(" ").reverse(),r=n.reverse().join(" "),o={idOnExternalPlatform:e.email,firstName:r,lastName:t},a={messageContent:{type:tL.G.TEXT,payload:{text:e.message}},authorCustomerIdentity:o};return{eventType:d.ow.SEND_OFFLINE_MESSAGE,data:a}})(e),r=await e5(n,t);if(tD(r))return r;throw new tP("Send offline message failed",r)})(e,nY(this,nj,"f"))}recoverThreadData(e){return new ni(async(t,n)=>{let r=nb(e),o=await e5(r,nY(this,nj,"f"));ng(o)?(this.getThread(o.data.thread.idOnExternalPlatform),nY(this,n$,"f").dispatchEvent(new t_(tS.THREAD_RECOVERED,{detail:o})),t(o)):n(new nE("Thread not found",o))})}recoverLivechatThreadData(e){return new ni(async(t,n)=>{let r=n_(e),o=await e5(r,nY(this,nj,"f"));ng(o)?(this.getThread(o.data.thread.idOnExternalPlatform),nY(this,n$,"f").dispatchEvent(new t_(tS.LIVECHAT_RECOVERED,{detail:o})),t(o)):n(new nE("Thread not found",o))})}async resetSession(e=b(),t="",n="",r="",o=b()){var a;null===(a=nY(this,nj,"f"))||void 0===a||a.disconnect(),nK(this,nj,null,"f"),nY(this,nF,"f").clear(),nY(this,nU,"f").clear(),h.ACCESS_TOKEN=void 0,h.ACCESS_TOKEN_EXPIRES_IN=void 0,h.THIRD_PARTY_TOKEN=void 0,h.CACHE_STORAGE&&h.CACHE_STORAGE.removeItem(tM),nY(this,nR,"f").destroy(),h.VISIT_ID=o,h.VISITOR_ID=r;try{await nY(this,nA,"m",nG).call(this),nK(this,nR,new eJ(e,t,n,nY(this,nj,"f")),"f")}catch(e){nY(this,nA,"m",nB).call(this,e)}}_getContactCustomFieldsFromQueue(){if(nY(this,nU,"f").size>0){let e=eV(nY(this,nU,"f"));return nY(this,nU,"f").clear(),e}return{}}}function nJ(e){var t,n;return e.type===tS.ASSIGNED_AGENT_CHANGED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.case)||void 0===n?void 0:n.id)}function nZ(e){var t,n;return e.type===tS.AGENT_TYPING_STARTED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.thread)||void 0===n?void 0:n.idOnExternalPlatform)}function n0(e){var t,n;return e.type===tS.AGENT_TYPING_ENDED&&void 0!==(null===(n=null===(t=e.data)||void 0===t?void 0:t.thread)||void 0===n?void 0:n.idOnExternalPlatform)}nR=new WeakMap,nD=new WeakMap,nP=new WeakMap,nL=new WeakMap,nM=new WeakMap,nj=new WeakMap,nU=new WeakMap,nF=new WeakMap,nz=new WeakMap,n$=new WeakMap,nH=new WeakMap,nW=new WeakMap,nA=new WeakSet,nB=function(e){let t=e instanceof g?e:new g(e);if("function"!=typeof this.onError)throw t;this.onError(t)},nV=async function(){var e;let t;let{brandId:n,channelId:r}=e2(),o=h.ENDPOINT_GATEWAY,a=h.APP_VERSION;!function(e){if(null==e)throw Error(`Expected non-nullish value, got ${e}`)}(o);let i=null!==(e=h.VISITOR_ID)&&void 0!==e?e:"";if(tb()){let e=ty()?nY(this,nR,"f").getId():null,n=nY(this,nM,"f")?h.AUTHORIZATION_CODE:void 0,r=tv()!==tW.THIRD_PARTY;try{let o=await (async(e,t,n=!1)=>{var r,o;if(n){let e=h.CACHE_STORAGE?h.CACHE_STORAGE.getItem(tM):null;if(e)return{accessToken:e,cached:!0}}let a=tz();try{let n=await tF(a,function(e,t){let n={};return e&&(n.thirdParty={authorization_code:e,grant_type:"authorization_code"}),e1(t)||(n.customerIdentity={idOnExternalPlatform:t}),n}(e,t),{credentials:"include"});return r=n.accessToken,o=n.expiresIn,h.CACHE_STORAGE&&h.CACHE_STORAGE.setItem(tM,r,1e3*o),n}catch(e){if(e instanceof g)throw e;throw new g("Failed to fetch transaction token",e)}})(n,e,r);t=o.accessToken;let{customerIdentity:a,thirdParty:i,contact:l}=o;a&&eX(nY(this,nR,"f"),a),i&&tB(i),(null==l?void 0:l.customFields)&&eB(nY(this,nU,"f"),l.customFields)}catch(e){nY(this,nA,"m",nB).call(this,e)}}nY(this,nH,"f").resolve();let l=Object.assign(Object.assign(Object.assign({v:a,sdkPlatform:"web",sdkVersion:y,brandId:n,channelId:r},tb()?{}:{customerId:nY(this,nR,"f").getId()}),{visitorId:i}),tb()?{transactionToken:t}:{}),u=(0,s.C)(l),c=new URL(o);return c.search=u,c.toString()},nG=async function(){try{nK(this,nj,nY(this,nA,"m",nQ).call(this),"f"),await nY(this,nj,"f").connect()}catch(e){nY(this,nA,"m",nB).call(this,e)}},nq=function(e){if(e.environment===tq.custom){if(eP(e.customEnvironment)||e1(e.customEnvironment))throw new g('customEnvironment must be provided when environment is set to "custom"');return void tw(e.customEnvironment)}tw(function(e){if(!(e in tq))throw new g(`Unknown environment: ${e}`);if(e===tq.custom)throw new g("The custom environment cannot be constructed using the built-in configuration");return{chat:`https://channels-de-${e}.niceincontact.com`.toLowerCase(),name:e,gateway:`wss://chat-gateway-de-${e}.niceincontact.com`.toLowerCase(),authorize:`https://digital-oauth-de-${e}.niceincontact.com`.toLowerCase()}}(e.environment))},nQ=function(){let e=new t2(this.onError,nY(this,nA,"m",nV).bind(this));return e.on(u.nF.MESSAGE,async e=>{try{"function"==typeof this.onRawEvent&&this.onRawEvent(e);let t=await (async e=>{if(e1(e))return null;if(e.type!==tE.m.EVENT_IN_S3)return e;let t=e.data.s3Object.url,n=await fetch(t);if(n.ok)return tN(await n.json());throw new g("Failed to fetch S3 event data")})((e=>{let t;let n=null==e?void 0:e.detail;if(n){try{t=JSON.parse(n.data)}catch(e){return}return tN(t)}})(e)),n=nY(this,nz,"f").process(t);if(!e1(n)){let{type:e}=n;(e=>{let{id:t}=e;if(eL.has(t)){let n=eL.get(t);"function"==typeof n&&n(e),eL.delete(t)}})(n),nY(this,n$,"f").dispatchEvent(new t_(null!=e?e:"",{detail:n}))}}catch(e){nY(this,nA,"m",nB).call(this,e)}}),e};let n1=e=>Number.isInteger(null==e?void 0:e.data.positionInQueue)&&!1===eP(null==e?void 0:e.id)&&(null==e?void 0:e.type)===d.vc.SET_POSITION_IN_QUEUE;class n2 extends g{}function n3(e){return{eventType:d.ow.CREATE_GROUP_CHAT_INVITE,data:{contact:{id:e}}}}async function n4(e,t){let n=await e5(e,t);if(n.type===tS.GROUP_CHAT_INVITE_CREATED)return n;throw new n2("Create invitation failed",n)}class n6 extends g{}function n5(e){return{eventType:d.ow.JOIN_GROUP_CHAT,data:{invitation:{code:e}}}}async function n9(e,t){let n=await e5(e,t);if(n.type===tS.GROUP_CHAT_JOINED)return n;throw new n6("Join Group chat failed",n)}function n8(e){return{eventType:d.ow.LEAVE_GROUP_CHAT,data:{contact:{id:e}}}}async function n7(e,t){return e5(e,t)}class re extends g{}function rt(e,t,n){return{eventType:d.ow.SEND_EMAIL_INVITE_TO_GROUP_CHAT,data:{contact:{id:e},invitation:{code:t},recipients:[{idOnExternalPlatform:n}]}}}async function rn(e,t){let n=await e5(e,t);if(n.type===tS.GROUP_CHAT_INVITE_SENT)return n;throw new re("Send Email Invitation failed",n)}class rr extends Error{constructor(e){super(e),this.name="CacheStorageError"}}var ro,ra=function(e,t,n,r){if("a"===n&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class ri{constructor(e){if(ro.set(this,void 0),!(e&&e.getItem&&e.setItem&&e.removeItem))throw new rr("CacheStorage: Storage is required");!function(e,t,n,r,o){if("function"==typeof t||!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");o?o.value=n:t.set(e,n)}(this,ro,e,"f")}getItem(e){let t=ra(this,ro,"f").getItem(e);if(!t)return null;let{data:n,expiresAt:r=0}=JSON.parse(t);return r<(new Date).getTime()||e3(n)?(ra(this,ro,"f").removeItem(e),null):n}removeItem(e){ra(this,ro,"f").removeItem(e)}setItem(e,t,n){let r={data:t,expiresAt:(new Date).getTime()+n};ra(this,ro,"f").setItem(e,JSON.stringify(r))}}ro=new WeakMap;var rl=i(369);function rs(e){return"object"==typeof e&&null!==e&&"reconnected"in e&&!0===e.reconnected}let ru=nX;return l})(),e.exports=r(n(77232))},53796:(e,t)=>{"use strict";t.Um="X-Caller-Service-ID"},4146:(e,t,n)=>{"use strict";var r=n(73404),o={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},a={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},i={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},l={};function s(e){return r.isMemo(e)?i:l[e.$$typeof]||o}l[r.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},l[r.Memo]=i;var u=Object.defineProperty,c=Object.getOwnPropertyNames,d=Object.getOwnPropertySymbols,f=Object.getOwnPropertyDescriptor,h=Object.getPrototypeOf,p=Object.prototype;e.exports=function e(t,n,r){if("string"!=typeof n){if(p){var o=h(n);o&&o!==p&&e(t,o,r)}var i=c(n);d&&(i=i.concat(d(n)));for(var l=s(t),m=s(n),g=0;g{"use strict";var n="function"==typeof Symbol&&Symbol.for,r=n?Symbol.for("react.element"):60103,o=n?Symbol.for("react.portal"):60106,a=n?Symbol.for("react.fragment"):60107,i=n?Symbol.for("react.strict_mode"):60108,l=n?Symbol.for("react.profiler"):60114,s=n?Symbol.for("react.provider"):60109,u=n?Symbol.for("react.context"):60110,c=n?Symbol.for("react.async_mode"):60111,d=n?Symbol.for("react.concurrent_mode"):60111,f=n?Symbol.for("react.forward_ref"):60112,h=n?Symbol.for("react.suspense"):60113,p=n?Symbol.for("react.suspense_list"):60120,m=n?Symbol.for("react.memo"):60115,g=n?Symbol.for("react.lazy"):60116,v=n?Symbol.for("react.block"):60121,y=n?Symbol.for("react.fundamental"):60117,b=n?Symbol.for("react.responder"):60118,w=n?Symbol.for("react.scope"):60119;function E(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case r:switch(e=e.type){case c:case d:case a:case l:case i:case h:return e;default:switch(e=e&&e.$$typeof){case u:case f:case g:case m:case s:return e;default:return t}}case o:return t}}}function S(e){return E(e)===d}t.AsyncMode=c,t.ConcurrentMode=d,t.ContextConsumer=u,t.ContextProvider=s,t.Element=r,t.ForwardRef=f,t.Fragment=a,t.Lazy=g,t.Memo=m,t.Portal=o,t.Profiler=l,t.StrictMode=i,t.Suspense=h,t.isAsyncMode=function(e){return S(e)||E(e)===c},t.isConcurrentMode=S,t.isContextConsumer=function(e){return E(e)===u},t.isContextProvider=function(e){return E(e)===s},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===r},t.isForwardRef=function(e){return E(e)===f},t.isFragment=function(e){return E(e)===a},t.isLazy=function(e){return E(e)===g},t.isMemo=function(e){return E(e)===m},t.isPortal=function(e){return E(e)===o},t.isProfiler=function(e){return E(e)===l},t.isStrictMode=function(e){return E(e)===i},t.isSuspense=function(e){return E(e)===h},t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===a||e===d||e===l||e===i||e===h||e===p||"object"==typeof e&&null!==e&&(e.$$typeof===g||e.$$typeof===m||e.$$typeof===s||e.$$typeof===u||e.$$typeof===f||e.$$typeof===y||e.$$typeof===b||e.$$typeof===w||e.$$typeof===v)},t.typeOf=E},73404:(e,t,n)=>{"use strict";e.exports=n(3072)},45228:e=>{"use strict";var t=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable;e.exports=!function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};if("abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},o)).join(""))return!1;return!0}catch(e){return!1}}()?function(e,o){for(var a,i,l=function(e){if(null==e)throw TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),s=1;s{"use strict";var r,o,a,i,l,s,u=n(96540),c=n(45228),d=n(69982);function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n