-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathavaya-ccaas-chat-sdk.js
2 lines (2 loc) · 58.5 KB
/
avaya-ccaas-chat-sdk.js
1
2
/* AvayaCCaaSChatSDK Version : 0.1.53 */
var AvayaCCaaSChatSDK=function(e){"use strict";function t(e,t){return`${e.code} : ${e.message}${t?" "+t:""}.`}const s=Object.freeze({ACS201:{code:"ACS-201",message:"Custom configurations not provided, using default configuration"},ACS202:{code:"ACS-202",message:"Removing all event handlers"},ACS203:{code:"ACS-203",message:"Event doesn't exist"},ACS204:{code:"ACS-204",message:"Avaya CCaaS Chat SDK is already initialized, subsequent init attempts will be ignored"},ACS205:{code:"ACS-205",message:"Event handler not registered"},ACS206:{code:"ACS-206",message:"Idle timeout"},ACS207:{code:"ACS-207",message:"Incorrect reconnectionTimeout value"},ACS208:{code:"ACS-208",message:"Incorrect idleTimeout value"},ACS209:{code:"ACS-209",message:"Incorrect idleShutdownGraceTimeout value"},ACS210:{code:"ACS-210",message:"Incorrect logLevel value"},ACS211:{code:"ACS-211",message:"Invalid page size, using default value (10)"},ACS212:{code:"ACS-212",message:"Error occured while reading Session Storage"},ACS213:{code:"ACS-213",message:"Error occured while writing to Session Storage"},ACS301:{code:"ACS-301",message:"Server URL not provided"},ACS302:{code:"ACS-302",message:"Invalid init parameters"},ACS303:{code:"ACS-303",message:"Invalid configuration values"},ACS304:{code:"ACS-304",message:"Server responded unexpectedly"},ACS305:{code:"ACS-305",message:"JWT token is invalid"},ACS306:{code:"ACS-306",message:"Server is unreachable"},ACS307:{code:"ACS-307",message:"Invalid IntegrationId"},ACS308:{code:"ACS-308",message:"JWT Token not provided"},ACS309:{code:"ACS-309",message:"Invalid URL"},ACS310:{code:"ACS-310",message:"Avaya CCaaS Chat SDK not initialized"},ACS311:{code:"ACS-311",message:"Avaya CCaaS Chat SDK failed to initialize"},ACS312:{code:"ACS-312",message:"Unable to join defunct engagement"},ACS313:{code:"ACS-313",message:"Engagement is not activated"},ACS314:{code:"ACS-314",message:"Engagement doesn't exist"},ACS315:{code:"ACS-315",message:"Engagement already active"},ACS316:{code:"ACS-316",message:"PageIterator failed to initialized"},ACS317:{code:"ACS-317",message:"Failed to fetch older messages"},ACS318:{code:"ACS-318",message:"Retry connection is allowed only in case of Event Stream Failure"},ACS319:{code:"ACS-319",message:"Failed to update engagement"},ACS320:{code:"ACS-320",message:"Session not found"},ACS321:{code:"ACS-321",message:"Cannot perform this operation as init/shutdown is in progress"},ACS322:e=>({code:"ACS-322",message:`Constraint violated : ${e}`})}),i=Object.freeze({info:e=>({code:"ACS-100",message:e}),warn:e=>({code:"ACS-200",message:e}),error:e=>({code:"ACS-300",message:e})});var n,a,o,r,g,E,d,h,c;!function(e){e.ERROR="ERROR",e.WARN="WARN",e.INFO="INFO",e.DEBUG="DEBUG",e.OFF="OFF"}(n||(n={})),function(e){e.USER_CLOSED="USER_CLOSED",e.USER_INACTIVE="USER_INACTIVE",e.SYSTEM_CLOSED="SYSTEM_CLOSED"}(a||(a={})),function(e){e.CUSTOMER="CUSTOMER",e.AGENT="AGENT",e.SUPERVISOR="SUPERVISOR",e.SYSTEM="SYSTEM",e.BOT="BOT"}(o||(o={})),function(e){e.PLAINTEXT="PLAINTEXT",e.HTML="HTML",e.MARKDOWN="MARKDOWN"}(r||(r={})),function(e){e.TEXT="TEXT"}(g||(g={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.TERMINATING="TERMINATING",e.TERMINATED="TERMINATED"}(E||(E={})),function(e){e.SYSTEM_CLOSED="SYSTEM_CLOSED",e.USER_CLOSED="USER_CLOSED",e.USER_INACTIVE="USER_INACTIVE"}(d||(d={})),function(e){e.USER_INACTIVE="USER_INACTIVE",e.USER_CLOSED="USER_CLOSED"}(h||(h={}));class l extends Error{constructor(e){super(e.code+" : "+e.message),this._eventCode=e}get code(){return this._eventCode.code}get message(){return this._eventCode.message}toString(){return t(this._eventCode)}}!function(e){e.CCAAS_SESSION_ID_KEY="ccaasClientSessionId",e.SESSION_ID="sessionId",e.ENGAGEMENT_ID="engagementId",e.DIALOG_ID="dialogId",e.REASON="reason",e.CLIENT_TYPE="web",e.SESSION="ccaasClientSession",e.PAGE_SIZE="pageSize",e.PAGE_NUMBER="pageNumber",e.ORDER_BY="orderBy",e.ASC="ASC",e.DSC="DSC",e.INITIALIZATION_COMPLETE="Avaya CCaaS Chat SDK initialized",e.SHUTDOWN_COMPLETE="Avaya CCaaS Chat SDK shutdown",e.ENGAGEMENT_JOINED="Engagement joined",e.ENGAGEMENT_DISCONNECTED="Engagement disconnected",e.MESSAGE_SENT="Message sent",e.MESSAGE_ARRIVED="Message arrived",e.MESSAGE_DELIVERED="Message delivered",e.RECEIVED_UNKNOWN_EVENT="Received unknown event",e.NO_NEW_EVENTS="No new events",e.CCAAS_ACTIVE_ENGAGEMENTS_KEY="ccaasActiveEngagements",e.SESSION_NOT_FOUND="Session not found",e.INIT_CALLED="AvayaCCaaSChatSDK.init() called",e.SESSION_IN_CACHE="Using sessionId from Session Storage",e.SESSION_NOT_IN_CACHE="Creating new session",e.NEW_LOG_LEVEL="Setting LogLevel to : ",e.SESSION_ESTABLISH_SUCCESS="Session created/resumed successfully",e.SHUTDOWN_CALLED="AvayaCCaaSChatSDK.shutdown() called",e.SHUTDOWN_SUCCESSFUL="AvayaCCaaSChatSDK shutdown successful",e.GET_ENGAGEMENTS_CALLED="AvayaCCaaSChatSDK.getEngagements() called",e.GET_ENGAGEMENT_CALLED="AvayaCCaaSChatSDK.getEngagementById() called",e.CREATE_ENGAGEMENT_CALLED="AvayaCCaaSChatSDK.createEngagement() called",e.ON_CALLED="AvayaCCaaSChatSDK.on() called",e.EVENT_HANDLER_ATTACHED="Event handler attached for : ",e.OFF_CALLED="AvayaCCaaSChatSDK.off() called",e.EVENT_HANDLER_REMOVED="Event handler removed for : ",e.OFF_CALLED_PARAM_LESS="AvayaCCaaSChatSDK.off() called without any parameters",e.RESET_IDLE_TIMEOUT_CALLED="AvayaCCaaSChatSDK.resetIdleTimeout() called",e.SET_TOKEN_CALLED="AvayaCCaaSChatSDK.setJwtToken() called",e.TOKEN_EXPIRY_REMINDER="JWT Token about to expire",e.TOKEN_EXPIRED="JWT Token expired",e.RETRY_CONNECTION_CALLED="AvayaCCaaSChatSDK.retryConnection() called",e.FOUND_ACTIVE_ENGAGEMENTS="Found active engagements in Session Storage",e.REMOVING_ENGAGEMENT="Removing engagement",e.NO_ACTIVE_ENGAGEMENTS="No active engagements",e.ENGAGEMENT_ACTIVATED="Engagement activated",e.ENGAGEMENT_STATUS_UPDATED="Engagement status updated",e.PARTICIPANT_ADDED="Participant added",e.PARTICIPANT_UPDATED="Participant updated",e.PARTICIPANT_REMOVED="Participant removed",e.ENGAGEMENT_TERMINATED="Engagement terminated",e.GET_PARTICIPANT_CALLED="Engagement.getParticipantById() called",e.PARTICIPANT_FOUND="Participant Found",e.PARTICIPANT_NOT_FOUND="Participant not found",e.JOIN_CALLED="Engagement.join() called",e.JOIN_SUCCESSFUL="Engagement joined successfully",e.SEND_MESSAGE_CALLED="Engagement.sendMessage() called",e.SEND_MESSAGE_SUCCESSFUL="Message successfully sent",e.GET_MESSAGES_CALLED="Engagement.getMessages() called",e.GET_MESSAGES_SUCCESSFUL="Messages fetched successfully",e.DISCONNECT_ENGAGEMENT_CALLED="Engagement.disconnect() called",e.DISCONNECT_ENGAGEMENT_SUCCESSFUL="Engagement disconnected successfully",e.ITERATOR_PREVIOUS_CALLED="Iterator.previous() called",e.FETCHING_ADDITIONAL_MESSAGES="Fetching more messages",e.FETCHED_ALL_MESSAGES="Fetched all messages",e.ITERATOR_NEXT_CALLED="Iterator.next() called",e.ITERATOR_ITEMS_CALLED="Iterator.items accessed",e.ITERATOR_HAS_PREVIOUS_CALLED="Iterator.hasPrevious() called",e.ITERATOR_HAS_NEXT_CALLED="Iterator.hasNext() called",e.IDLE_TIMER_STARTED="Idle timer started/reset",e.RECONNECTION_TIMER_STARTED="Reconnection timer started",e.GRACE_TIMER_STARTED="Idle shutdown grace timer started",e.ALL_TIMERS_STOPPED="All timers stopped",e.IDLE_TIMEOUT_OCCURED="Idle timeout has occured",e.RECONNECTION_TIMEOUT_OCCURED="Reconnection timeout has occured",e.GRACE_TIMEOUT_OCCURED="Idle shutdown grace timeout has ocured",e.LONG_POLLING_STARTING="Starting long polling",e.LONG_POLLING_STOPPED="Long polling stopped",e.LONG_POLLING_PAUSED="Long polling paused",e.LONG_POLLING_RESUMING="Resuming Long Polling",e.EVENT_STREAM_CONNECTING="Event stream connecting",e.EVENT_STREAM_CONNECTED="Event stream connected",e.EVENT_STREAM_FAILED="Event stream failed",e.EVENT_STREAM_CLOSED="Event stream closed",e.RECEIVED_NEW_EVENTS="Received new events",e.WRITE_SESSION_STORAGE="Write to Session Storage",e.READ_SESSION_STORAGE="Read from Session Storage",e.SERVER_RESPONDED_WITH="Server responded with : ",e.PROCESSING_MESSAGE_EVENT="Received Message Event",e.ENGAGEMENT_CREATION_SUCCESSFUL="Engagement creation successful",e.ENGAGEMENT_CREATED="New engagement created with pending status",e.EVENT_DISPATCHING_DISABLED="Event dispatching disabled as session not available",e.SET_LOG_LEVEL_CALLED="AvayaCCaaSChatSDK.setLogLevel() called",e.RETRY_CONNECTION_ATTEMPTED="Attempted to retry manually",e.JWT_ALMOST_EXPIRED="Provided JWT token is almost about to expire"}(c||(c={}));const T=Object.freeze({HostURL:{shouldBeString:"Host URL should be string",shouldBeHttpsUrl:"Host URL should be a valid URL with HTTPS scheme"},IntegrationId:{shouldBeString:"integrationId should be string",shouldBeUUID:"integrationId should be a UUID"},Token:{shouldBeString:"JWT Token should be string",shouldHaveValidFormat:"JWT Token should have valid format",shouldBeLive:"JWT Token should be live"},DisplayName:{shouldBeString:"Display name should be a string"},SessionParameters:{shouldBeObject:"SessionParameters should be object of type {key: string (64 max length) -> value: string (256 max length)} with maximum 20 records"},LogLevel:{shouldBeOneOf:"Log Level should be one of [SILENT, DEBUG, INFO, WARN, ERROR]"},ShutdownReason:{shouldBeOneOf:"Shutdown Reason should be one of [SYSTEM_CLOSED, USER_CLOSED]"},EngagementId:{shouldBeString:"engagementId should be string",shouldBeUUID:"engagementId should be UUID"},EngagementParameters:{shouldBeObject:"Engagement Parameters should be an object of type {key: string (64 max length) -> value: string (256 max length)} with maximum 20 records"},ParticipantId:{shouldBeString:"participantId should be a string",shouldBeUUID:"participantId should be an UUID"},PageSize:{shouldBeNumber:"Page size should be a number",shouldBeNaturalNumber:"Page size should be a natural number"},Message:{shouldBeString:"Message should be string",shouldNotBeEmpty:"Message should not be empty string",shouldNotBeMoreThan:"Message length should not be more than 4096 characters"},ParentMessageId:{shouldBeUUID:"parentMessageId should be a valid UUID string"},EngagementDisconnectionReason:{shouldBeOneOf:"Engagemen disconnection reason should be one of [SYSTEM_CLOSED, USER_CLOSED, USER_INACTIVE]"},EventHandler:{shouldBeFunction:"Event Handler should a function"}});var S;!function(e){e[e.CONSOLE=0]="CONSOLE"}(S||(S={}));const u=new class{constructor(){this.level=n.WARN}prepareString(e,t,s,i=", "){let n=`${Date()} @ Avaya CCaaS Chat SDK [${e}] : ${t} `;if(s){n+="(";for(const e in s)n+=`${e} = ${JSON.stringify(s[e])}${i}`;n+=")"}return n}setLevel(e){this.debug(c.NEW_LOG_LEVEL+e),this.level=e}getLevel(){return this.level}debug(e,t){if(this.level===n.DEBUG){let s=this.prepareString(n.DEBUG,e,t);console.debug(s)}}info(e,t){this.log(e,t)}log(e,t){if(this.level===n.DEBUG||this.level===n.INFO){let s=this.prepareString(n.INFO,e,t);console.log(s)}}warn(e){this.level!==n.DEBUG&&this.level!==n.INFO&&this.level!==n.WARN||console.warn(`${Date()} @ Avaya CCaaS Chat SDK [${n.WARN}]`,e)}error(e){this.level!==n.OFF&&console.error(`${Date()} @ Avaya CCaaS Chat SDK [${n.ERROR}]`,e)}};function I(){return u}var m;!function(e){e[e.IDLE=0]="IDLE",e[e.RECONNECTION=1]="RECONNECTION",e[e.GRACE=2]="GRACE"}(m||(m={}));const C={URL:new RegExp(/^https?:\/\/(?:www\.)?([-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b)*(\/[\/\d\w\.-]*)*(?:[\?])*(.+)*$/i),HTTPS_URL:new RegExp(/^https:\/\/(?:www\.)?([-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b)*(\/[\/\d\w\.-]*)*(?:[\?])*(.+)*$/i),UUID:new RegExp(/^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$/)},A={notMoreThan:(e,t)=>e.length<=t,notLessThan:(e,t)=>e.length>=t,isUUID:e=>C.UUID.test(e),isURL:e=>C.URL.test(e),isHttpsURL:e=>C.HTTPS_URL.test(e),isOneOf:(e,t)=>t.includes(e),matches:(e,t)=>new RegExp(t).test(e),isOptionalOneOf:(e,t)=>void 0===e||t.includes(e),isJWT(e){const t=e.split(".");return t.length>=3&&"jwt"===t[0]}},N={isString:e=>"string"==typeof e,isOptionalString:e=>void 0===e||"string"==typeof e,isNumber:e=>"number"==typeof e,isOptionalNumber:e=>void 0===e||"number"==typeof e,isFunction:e=>"function"==typeof e,isObject:e=>"object"==typeof e&&!Array.isArray(e),isOptionalObject:e=>void 0===e||"object"==typeof e&&!Array.isArray(e),isMappedData(e,t,s,i){if("object"!=typeof e||Array.isArray(e))return!1;if(t&&Object.keys(e).length>t)return!1;for(const t in e){if(s&&t.length>s)return!1;if("string"!=typeof e[t])return!1;if(i&&e[t].length>i)return!1}return!0},isOptionalMappedData(e,t,s,i){return void 0===e||this.isMappedData(e,t,s,i)}};function p(e,i){if(!e)throw I().error(t(s.ACS322(i))),new l(s.ACS322(i))}const _=e=>JSON.stringify({displayName:e.displayName,clientType:c.CLIENT_TYPE,sessionParameters:e.sessionParameters}),R=e=>JSON.stringify({dialogId:e.dialogId,sessionId:e.sessionId,parentMessageId:e.parentMessageId,body:{elementType:g.TEXT,elementText:{text:e.message,textFormat:r.PLAINTEXT}}}),D=e=>({messageId:e.messageId,dialogId:e.dialogId,engagementId:e.engagementId,body:e.body,messageIndex:e.messageIndex,parentMessageId:e.parentMessageId,senderParticipant:{participantId:e.senderParticipantId,participantType:e.participantType,displayName:e.displayName},receivedAt:e.receivedAt?new Date(e.receivedAt):new Date,lastUpdatedAt:e.lastUpdatedAt?new Date(e.lastUpdatedAt):new Date});function v(e){return{engagementId:e.engagementId,dialogId:e.dialogId,eventDate:e.eventDate,participant:e.participant}}const O=e=>{var t,s;return{engagementId:e.engagementId,dialogId:e.dialogId,eventDate:e.eventDate,messageId:e.message.messageId,parentMessageId:e.message.parentMessageId,messageIndex:e.message.messageIndex,receivedAt:null!==(t=e.message.receivedAt)&&void 0!==t?t:new Date,lastUpdatedAt:null!==(s=e.message.lastUpdatedAt)&&void 0!==s?s:new Date,body:e.message.body,senderParticipant:e.participant}},f=e=>v(e),L=e=>({engagementId:e.engagementId,dialogId:e.dialogId,eventDate:e.eventDate,type:e.error.type,title:e.error.title,detail:e.error.detail}),y=e=>v(e);var w,M,G,b,P;!function(e){e.INITIALIZED="INITIALIZED",e.SHUTDOWN="SHUTDOWN",e.ENGAGEMENT_ACTIVE="ENGAGEMENT_ACTIVE",e.ENGAGEMENT_ERROR="ENGAGEMENT_ERROR",e.MESSAGE_DELIVERED="MESSAGE_DELIVERED",e.MESSAGE_ARRIVED="MESSAGE_ARRIVED",e.PARTICIPANT_ADDED="PARTICIPANT_ADDED",e.PARTICIPANT_DISCONNECTED="PARTICIPANT_DISCONNECTED",e.EVENT_STREAM_CONNECTED="EVENT_STREAM_CONNECTED",e.EVENT_STREAM_CLOSED="EVENT_STREAM_CLOSED",e.EVENT_STREAM_FAILED="EVENT_STREAM_FAILED",e.EVENT_STREAM_CONNECTING="EVENT_STREAM_CONNECTING",e.TOKEN_EXPIRY_REMINDER="TOKEN_EXPIRY_REMINDER",e.TOKEN_EXPIRED="TOKEN_EXPIRED",e.IDLE_TIMEOUT_EXPIRED="IDLE_TIMEOUT_EXPIRED",e.ENGAGEMENT_TERMINATED="ENGAGEMENT_TERMINATED"}(w||(w={})),function(e){e.UNAUTHORIZED="UNAUTHORIZED",e.FORBIDDEN="FORBIDDEN",e.CLIENT_SESSION_INVALIDATED="CLIENT_SESSION_INVALIDATED",e.SERVER_ERROR="SERVER_ERROR",e.SERVER_UNREACHABLE="SERVER_UNREACHABLE",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.RECONNECTION_TIMEOUT="RECONNECTION_TIMEOUT"}(M||(M={})),function(e){e.MESSAGE="MESSAGE",e.PARTICIPANT_ADDED="PARTICIPANT_ADDED",e.PARTICIPANT_DISCONNECTED="PARTICIPANT_DISCONNECTED",e.ENGAGEMENT_CREATED="ENGAGEMENT_CREATED",e.ENGAGEMENT_ERROR="ENGAGEMENT_ERROR"}(G||(G={})),function(e){e[e.AddParticipant=0]="AddParticipant",e[e.RemoveParticipant=1]="RemoveParticipant"}(b||(b={}));function U(e,...t){let s=`${e[0]}`;if(t.length!==e.length-1)throw new l(i.error(`Expected ${e.length-1} arguments, but got ${t.length}`));for(let n=0;n<t.length;n++){if("string"!=typeof t[n]&&"number"!=typeof t[n])throw new l(i.error("Expected argument(s) of type string, but atleast one argument was "+typeof t[n]));s+=`${t[n]}${e[n+1]}`}return s}!function(e){e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE"}(P||(P={}));const k={CREATE_SESSION:{requestType:P.POST,path:e=>U`/v1/integrations/${e}/sessions`},GET_SESSION:{requestType:P.GET,path:(e,t)=>U`/v1/integrations/${e}/sessions/${t}`},DELETE_SESSION:{requestType:P.DELETE,path:(e,t)=>U`/v1/integrations/${e}/sessions/${t}`},CREATE_ENGAGEMENT:{requestType:P.POST,path:e=>U`/v1/integrations/${e}/engagements`},JOIN_ENGAGEMENT:{requestType:P.POST,path:(e,t)=>U`/v1/integrations/${e}/engagements/${t}:join`},SEND_MESSAGE:{requestType:P.POST,path:(e,t)=>U`/v1/integrations/${e}/engagements/${t}/messages`},DISCONNECT_ENGAGEMENT:{requestType:P.POST,path:(e,t)=>U`/v1/integrations/${e}/engagements/${t}:disconnect`},LIST_MESSAGES:{requestType:P.GET,path:(e,t)=>U`/v1/integrations/${e}/engagements/${t}/messages`},GET_ENGAGEMENT:{requestType:P.GET,path:(e,t)=>U`/v1/integrations/${e}/engagements/${t}`}};function V(e,t){switch(e.status){case 200:case 201:case 202:return e.body?null:s.ACS304;case 204:return null;case 401:return s.ACS305;default:return t?t(e):s.ACS304}}var H;!function(e){e[e.Closed=0]="Closed",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.Retry=3]="Retry",e[e.Paused=4]="Paused",e[e.Failed=5]="Failed"}(H||(H={}));class F{constructor(e,t,s,i){this.chatConfig=e,this.dispatchEvents=t,this.timerController=i,this.logger=I(),this.dispatchedEventIds=new Set,this.latestEventId=null,this.state=new B,this.sessionId=s,this.currentDelay=1,this.nextDelay=1,this.disconnectionCheckCount=3,this.maxRequestTimeout=4e4,this.rch=i.addReconnectionTimeoutListener(this.handleReconnectionTimeout.bind(this))}handleReconnectionTimeout(){var e;this.state.toFailed(),null===(e=this.clearSyntheticDelay)||void 0===e||e.call(this),this.dispatchEventStreamFailed(M.RECONNECTION_TIMEOUT)}clearTimeoutHandlers(){this.timerController.removeReconnectionTimeoutListener(this.rch)}async start(){this.state.isClosed&&(this.logger.debug(c.LONG_POLLING_STARTING),this.dispatchedEventIds.clear(),this.currentDelay=1,this.nextDelay=1,this.state.toConnecting(),this.dispatchEventStreamConnecting(),this.poll())}pause(){(this.state.isRetry||this.state.isFailed||this.state.isConnecting||this.state.isConnected)&&(this.state.toPaused(),this.logger.debug(c.LONG_POLLING_PAUSED))}stop(){var e;this.state.toClosed(),this.dispatchedEventIds.clear(),this.currentDelay=1,this.nextDelay=1,null===(e=this.clearSyntheticDelay)||void 0===e||e.call(this),this.logger.debug(c.LONG_POLLING_STOPPED),this.dispatchEventStreamClosed()}async resume(){this.state.isPaused&&(this.logger.debug(c.LONG_POLLING_RESUMING),this.state.toConnecting(),this.poll())}handleDisconnection(){(this.state.isConnecting||this.state.isConnected)&&(this.state.toRetry(),this.timerController.startReconnectionTimer())}handlePositiveReconnection(){(this.state.isRetry||this.state.isFailed)&&(this.state.toConnected(),this.timerController.startIdleTimer(),this.resetBackoffMechanism())}handleNegativeReconnection(){(this.state.isRetry||this.state.isFailed)&&(this.state.toPaused(),this.timerController.startIdleTimer(),this.resetBackoffMechanism())}get pollingAllowed(){return this.state.isConnecting||this.state.isRetry||this.state.isConnected}getDelay(){let e=this.currentDelay+this.nextDelay;return this.currentDelay=this.nextDelay,this.nextDelay=e,this.currentDelay}async syntheticDelay(){const e=1e3*(this.getDelay()+Math.random());return new Promise((t=>{const s=setTimeout((()=>{t(),this.clearSyntheticDelay=void 0}),e);this.clearSyntheticDelay=()=>{window.clearTimeout(s),t()}}))}resetBackoffMechanism(){this.currentDelay=1,this.nextDelay=1}async checkDisconnection(){for(let e=0;e<this.disconnectionCheckCount;e++)try{const e=await fetch(this.prepareURL(),{method:P.GET,headers:{Authorization:`Bearer ${this.chatConfig.jwtToken}`,"x-route-request":this.sessionId,appkey:this.chatConfig.apiGatewayAppKey},keepalive:!0});if(void 0!==e&&200===e.status)return!1;if(void 0!==e&&(401===e.status||403===e.status))return!1}catch(e){this.logger.warn(e);continue}return!0}dispatchEventStreamConnecting(){this.logger.debug(c.EVENT_STREAM_CONNECTING),this.dispatchEvents([{type:w.EVENT_STREAM_CONNECTING,event:{eventDate:new Date}}])}dispatchEventStreamConnected(){this.logger.debug(c.EVENT_STREAM_CONNECTED),this.dispatchEvents([{type:w.EVENT_STREAM_CONNECTED,event:{eventDate:new Date}}])}dispatchEventStreamFailed(e,i=!1){this.logger.warn(c.EVENT_STREAM_FAILED);let n={reason:e,eventDate:new Date,message:""};switch(e){case M.FORBIDDEN:case M.UNAUTHORIZED:n.message=t(s.ACS305);break;case M.RECONNECTION_TIMEOUT:n.message=t(s.ACS306);break;case M.CLIENT_SESSION_INVALIDATED:n.message=t(s.ACS320);break;case M.SERVER_ERROR:case M.SERVER_UNREACHABLE:case M.UNEXPECTED_ERROR:n.message=t(s.ACS304),i||(n.retryAfter=this.nextDelay)}this.dispatchEvents([{type:w.EVENT_STREAM_FAILED,event:n}])}dispatchEventStreamClosed(){this.logger.debug(c.EVENT_STREAM_CLOSED),this.dispatchEvents([{type:w.EVENT_STREAM_CLOSED,event:{eventDate:new Date}}])}async poll(){if(this.state.isRetry&&await this.syntheticDelay(),this.state.isRetry&&this.dispatchEventStreamConnecting(),this.pollingAllowed)return function(e,...t){const s=new AbortController,i=setTimeout((()=>{s.abort()}),e);return fetch(t[0],Object.assign(Object.assign({},t[1]),{signal:s.signal})).finally((()=>{clearTimeout(i)}))}(this.maxRequestTimeout,this.prepareURL(),{method:P.GET,headers:{Authorization:`Bearer ${this.chatConfig.jwtToken}`,appkey:this.chatConfig.apiGatewayAppKey},keepalive:!0}).then((async e=>{await this.processResponse(e)})).catch((e=>{this.processError(e)})).finally((()=>{this.poll()}))}async processResponse(e){return this.state.isRetry?this.processRetryResponse(e):this.state.isConnecting||this.state.isConnected?this.processNormalResponse(e):void 0}async processRetryResponse(e){switch(e.status){case 200:this.handlePositiveReconnection(),this.logger.debug("Reconnected"),this.dispatchEventStreamConnected();break;case 401:this.handleNegativeReconnection(),this.logger.debug("Reconnected with JWT issue"),this.dispatchEventStreamFailed(M.UNAUTHORIZED);break;case 403:this.handleNegativeReconnection(),this.logger.debug("Reconnected with JWT issue"),this.dispatchEventStreamFailed(M.FORBIDDEN);break;case 404:(await e.json()).detail===c.SESSION_NOT_FOUND?(this.logger.error(t(s.ACS320)),this.stop(),this.dispatchEventStreamFailed(M.CLIENT_SESSION_INVALIDATED)):this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE);break;default:this.logger.error(t(s.ACS304,e.status)),this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE)}}async processNormalResponse(e){switch(e.status){case 200:{this.state.isConnecting&&(this.state.toConnected(),this.dispatchEventStreamConnected());const t=await e.json();this.processPositiveResponse(t);break}case 401:this.pause(),this.dispatchEventStreamFailed(M.UNAUTHORIZED);break;case 403:this.pause(),this.dispatchEventStreamFailed(M.FORBIDDEN);break;case 500:await this.checkDisconnection()&&(this.dispatchEventStreamFailed(M.SERVER_ERROR),this.handleDisconnection());break;case 501:await this.checkDisconnection()&&(this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE),this.handleDisconnection());break;default:if(this.logger.error(t(s.ACS304,e.status)),404===e.status){if((await e.json()).detail===c.SESSION_NOT_FOUND){this.stop(),this.dispatchEventStreamFailed(M.CLIENT_SESSION_INVALIDATED);break}}await this.checkDisconnection()&&(this.dispatchEventStreamFailed(M.UNEXPECTED_ERROR),this.handleDisconnection());break}}processPositiveResponse(e){if(e.length){const t=e.filter((e=>!this.dispatchedEventIds.has(e.eventId)));t.length?(this.dispatchedEventIds=new Set(t.map((e=>e.eventId))),this.latestEventId=t[t.length-1].eventId,this.logger.debug(c.RECEIVED_NEW_EVENTS,{session:this.sessionId,events:t.map((e=>({id:e.eventId,type:e.eventType})))}),this.dispatchEvents(t.map((e=>({type:e.eventType,event:e}))))):this.logger.debug(c.NO_NEW_EVENTS)}else this.logger.debug(c.NO_NEW_EVENTS),this.latestEventId=null,this.dispatchedEventIds.clear()}processError(e){this.logger.warn(e),(this.state.isConnecting||this.state.isConnected)&&this.handleDisconnection(),(this.state.isConnecting||this.state.isRetry||this.state.isConnected)&&this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE)}prepareURL(){const e=this.latestEventId?`?lastEventId=${this.latestEventId}`:"";return`${this.chatConfig.ccaasURL}${this.chatConfig.urlBasePath}/v1/integrations/${this.chatConfig.integrationId}/sessions/${this.sessionId}/events${e}`}retry(){var e;if(this.state.isFailed)fetch(this.prepareURL(),{method:P.GET,headers:{Authorization:`Bearer ${this.chatConfig.jwtToken}`,appkey:this.chatConfig.apiGatewayAppKey},keepalive:!0}).then((e=>{switch(e.status){case 200:this.handlePositiveReconnection(),this.dispatchEventStreamConnected(),this.poll();break;case 401:this.handleNegativeReconnection(),this.dispatchEventStreamFailed(M.UNAUTHORIZED,!0);break;case 403:this.handleNegativeReconnection(),this.dispatchEventStreamFailed(M.FORBIDDEN,!0);break;default:this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE,!0)}})).catch((e=>{this.logger.warn(e),this.dispatchEventStreamFailed(M.SERVER_UNREACHABLE,!0)}));else{if(!this.state.isRetry)throw new l(s.ACS318);null===(e=this.clearSyntheticDelay)||void 0===e||e.call(this),this.resetBackoffMechanism()}}}class B{constructor(){this.state=H.Closed}getState(){return this.state}get isClosed(){return this.state===H.Closed}get isFailed(){return this.state===H.Failed}get isRetry(){return this.state===H.Retry}get isPaused(){return this.state===H.Paused}get isConnecting(){return this.state===H.Connecting}get isConnected(){return this.state===H.Connected}toClosed(){this.state=H.Closed}toFailed(){this.isClosed||(this.state=H.Failed)}toRetry(){this.isClosed||(this.state=H.Retry)}toPaused(){this.isClosed||(this.state=this.state=H.Paused)}toConnecting(){this.state=H.Connecting}toConnected(){this.isClosed||(this.state=H.Connected)}}class x{constructor(e,t,s,i,n,a){this.config=e,this.restController=t,this.logger=I(),this.internalDialog=i.dialogs[0],this._engagementId=i.engagementId,this.status=n?E.ACTIVE:E.PENDING,this.sessionId=s.sessionId,this.timerController=a,this.destoryEngagement=s.destructorFunction,this.notifyEngagementActivation=s.activationFunction,this.maxPageSize=50}getEngagementImage(){return Object.freeze({engagementId:this._engagementId,dialogId:this.internalDialog.dialogId,createdAt:this.createdAt,getParticipantById:this.getParticipantById.bind(this),join:this.join.bind(this),getMessages:this.getMessages.bind(this),sendMessage:this.sendMessage.bind(this),disconnect:this.disconnect.bind(this),fetchEngagementStatus:this.fetchEngagementStatus.bind(this),fetchLastUpdateTime:this.fetchLastUpdatedTime.bind(this),fetchParticipantList:this.fetchParticipantList.bind(this),get lastUpdatedAt(){return this.fetchLastUpdateTime()},get participants(){return this.fetchParticipantList()},get engagementStatus(){return this.fetchEngagementStatus()}})}updateStatus(e){this.status=e,this.logger.debug(c.ENGAGEMENT_STATUS_UPDATED,{sessionId:this.sessionId,engagementId:this._engagementId,newStatus:e})}addParticipant(e){this.internalDialog.participants.push(e),this.logger.debug(c.PARTICIPANT_ADDED,{sessionId:this.sessionId,engagementId:this._engagementId,participantId:e.participantId,participantType:e.participantType})}updateParticipant(e){const t=this.internalDialog.participants.findIndex((t=>t.participantId===e.participantId));t>-1?(this.internalDialog.participants[t].displayName=e.displayName,this.logger.debug(c.PARTICIPANT_UPDATED,{sessionId:this.sessionId,engagementId:this._engagementId,participantId:e.participantId,participantType:e.participantType})):this.addParticipant(e)}removeParticipant(e){const t=this.internalDialog.participants.findIndex((t=>t.participantId===e.participantId));t>-1&&(this.internalDialog.participants.splice(t,1),this.logger.debug(c.PARTICIPANT_REMOVED,{sessionId:this.sessionId,engagementId:this._engagementId,participantId:e.participantId,participantType:e.participantType}))}updateEngagement(e){const t=e.dialogs[0].dialogStatus;if(t===E.TERMINATING||t===E.TERMINATED)this.terminate();else{const t=e.dialogs[0].participants;this.syncParticipantList(t)}}syncParticipantList(e){for(const t of this.internalDialog.participants){const s=e.find((e=>e.participantId===t.participantId));s?this.updateParticipant(s):this.removeParticipant(t)}for(const t of e)this.internalDialog.participants.find((e=>e.participantId===t.participantId))||this.addParticipant(t)}terminate(){this.status=E.TERMINATED,this.logger.debug(c.REMOVING_ENGAGEMENT,{sessionId:this.sessionId,engagementId:this._engagementId})}verifyResponse(e){const t=V(e,(e=>404===e.status?s.ACS314:s.ACS304));if((null==t?void 0:t.code)===s.ACS314.code&&(this.status=E.TERMINATED,this.destoryEngagement(this.engagementId)),t)throw this.logger.error(c.SERVER_RESPONDED_WITH+e.status),new l(t);return e}join(){if(this.logger.debug(c.JOIN_CALLED,{sessionId:this.sessionId,engagementId:this._engagementId}),this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);if(this.status===E.ACTIVE)throw this.logger.error(t(s.ACS315)),new l(s.ACS315);return this.timerController.activity(),new Promise(((e,t)=>{this.restController.send(k.JOIN_ENGAGEMENT.requestType,k.JOIN_ENGAGEMENT.path(this.config.integrationId,this.engagementId),JSON.stringify({dialogId:this.internalDialog.dialogId,sessionId:this.sessionId})).catch((e=>{throw new l(s.ACS306)})).then((e=>this.verifyResponse(e).json())).then((t=>{this.notifyEngagementActivation(this.engagementId),this.syncParticipantList(t.dialogs[0].participants),this.logger.debug(c.JOIN_SUCCESSFUL,{sessionId:this.sessionId,engagementId:this._engagementId}),e(this.getEngagementImage())})).catch((e=>{this.logger.error(e),t(e)}))}))}disconnect(e){if(this.logger.debug(c.DISCONNECT_ENGAGEMENT_CALLED,{sessionId:this.sessionId,engagementId:this._engagementId,reason:e}),this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);if(this.status===E.PENDING)throw this.logger.error(t(s.ACS315)),new l(s.ACS313);return this.timerController.activity(),p(N.isOptionalString(e),T.EngagementDisconnectionReason.shouldBeOneOf),p(A.isOptionalOneOf(e,Object.values(d)),T.EngagementDisconnectionReason.shouldBeOneOf),new Promise(((t,i)=>{this.restController.send(k.DISCONNECT_ENGAGEMENT.requestType,k.DISCONNECT_ENGAGEMENT.path(this.config.integrationId,this.engagementId),JSON.stringify({dialogId:this.internalDialog.dialogId,sessionId:this.sessionId,reason:e})).catch((e=>{throw new l(s.ACS306)})).then((e=>{const s=V(e);if(s)throw this.logger.error(c.SERVER_RESPONDED_WITH+e.status),new l(s);this.status=E.TERMINATING,this.logger.debug(c.ENGAGEMENT_TERMINATED,{engagementId:this._engagementId}),t()})).catch((e=>{this.logger.error(e),i(e)}))}))}getParticipantById(e){if(this.logger.debug(c.GET_PARTICIPANT_CALLED,{sessionId:this.sessionId,engagementId:this._engagementId,participantId:e}),this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);p(N.isString(e),T.ParticipantId.shouldBeString);const i=this.internalDialog.participants.find((t=>t.participantId===e));return this.logger.debug(i?c.PARTICIPANT_FOUND:c.PARTICIPANT_NOT_FOUND,{sessionId:this.sessionId,engagementId:this._engagementId,participantId:e}),i}sendMessage(e,i){if(this.logger.debug(c.SEND_MESSAGE_CALLED,{sessionId:this.sessionId,engagementId:this._engagementId}),this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);if(this.status===E.PENDING)throw this.logger.error(t(s.ACS313)),new l(s.ACS313);return this.timerController.activity(),p(N.isString(e),T.Message.shouldBeString),p(A.notLessThan(e,1),T.Message.shouldNotBeEmpty),p(A.notMoreThan(e,4096),T.Message.shouldNotBeMoreThan),p(N.isOptionalString(i),T.ParentMessageId.shouldBeUUID),i&&p(A.isUUID(i),T.ParentMessageId.shouldBeUUID),new Promise(((t,n)=>{this.restController.send(k.SEND_MESSAGE.requestType,k.SEND_MESSAGE.path(this.config.integrationId,this.engagementId),R({dialogId:this.internalDialog.dialogId,sessionId:this.sessionId,message:e,parentMessageId:i})).catch((e=>{throw new l(s.ACS306)})).then((e=>this.verifyResponse(e).json())).then((e=>{this.logger.debug(c.SEND_MESSAGE_SUCCESSFUL,{sessionId:this.sessionId,engagementId:this._engagementId,messageId:e.messageId}),t(D(e))})).catch((e=>{this.logger.error(e),n(e)}))}))}getMessages(e=10){if(this.logger.debug(c.GET_MESSAGES_CALLED,{sessionId:this.sessionId,engagementId:this._engagementId,pageSize:e}),this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return("number"!=typeof e||e<=0||e>50)&&(e=10,this.logger.warn(t(s.ACS211))),new Promise(((t,i)=>{const n=new Map;n.set(c.SESSION_ID,this.sessionId),n.set(c.DIALOG_ID,this.internalDialog.dialogId),n.set(c.PAGE_SIZE,this.maxPageSize.toString()),n.set(c.PAGE_NUMBER,1..toString()),n.set(c.ORDER_BY,c.DSC),this.restController.send(k.LIST_MESSAGES.requestType,k.LIST_MESSAGES.path(this.config.integrationId,this.engagementId),void 0,n).catch((()=>{throw new l(s.ACS306)})).then((e=>{const t=V(e);if(t)throw this.logger.error(c.SERVER_RESPONDED_WITH+e.status),new l(t);return e.json()})).then((s=>{const i=s.messages.map((e=>D(e))),n=s.pagination.pageNumber,a=s.links.next;this.logger.debug(c.GET_MESSAGES_SUCCESSFUL,{sessionId:this.sessionId,engagementId:this._engagementId}),t(new j(e,this.restController,i,a,n,this._engagementId))})).catch((e=>{this.logger.error(e),i(e)}))}))}get engagementId(){return this._engagementId}get dialogId(){if(this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return this.internalDialog.dialogId}get engagementStatus(){if(this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return this.internalDialog.dialogStatus}get createdAt(){if(this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return this.internalDialog.createdAt}get lastUpdatedAt(){if(this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return this.internalDialog.lastUpdatedAt}get participants(){if(this.status===E.TERMINATED||this.status===E.TERMINATING)throw this.logger.error(t(s.ACS314)),new l(s.ACS314);return this.internalDialog.participants}fetchEngagementStatus(){return this.status}fetchParticipantList(){return this.internalDialog.participants}fetchLastUpdatedTime(){return this.internalDialog.lastUpdatedAt}}class j{constructor(e,t,s,i,n,a){const o=e;this.engagementId=a,this.pageNumber=n,this.index=0,this.restController=t,this.messages=s,this.nextPageLink=i,this.capturedAll=!1,this.getPageSize=()=>o,this.logger=I(),""===i&&(this.capturedAll=!0,this.logger.debug(c.FETCHED_ALL_MESSAGES))}get items(){this.logger.debug(c.ITERATOR_ITEMS_CALLED,{engagementId:this.engagementId});const e=Math.min(this.messages.length,this.index+this.getPageSize());return this.messages.slice(this.index,e)}async next(){this.logger.debug(c.ITERATOR_NEXT_CALLED,{engagementId:this.engagementId});const e=Math.max(0,this.index-this.getPageSize());return this.index=e,this}async previous(){this.logger.debug(c.ITERATOR_PREVIOUS_CALLED,{engagementId:this.engagementId});const e=Math.min(this.messages.length,this.index+this.getPageSize());for(;this.messages.length-e<this.getPageSize()&&!this.capturedAll;)try{this.logger.debug(c.FETCHING_ADDITIONAL_MESSAGES,{engagementId:this.engagementId});const e=await this.restController.send(k.LIST_MESSAGES.requestType,this.nextPageLink,void 0,void 0,!0),t=V(e);if(t)throw this.logger.error(`${c.SERVER_RESPONDED_WITH} ${e.status}`),t;const s=await e.json(),i=s.messages.filter((e=>!this.messages.find((t=>t.messageId===e.messageId))&&!(e.messageIndex>this.messages[0].messageIndex))).map((e=>D(e)));if(this.messages=[...this.messages,...i],this.nextPageLink=s.links.next,""===s.links.next){this.capturedAll=!0,this.logger.debug(c.FETCHED_ALL_MESSAGES,{engagementId:this.engagementId});break}}catch(e){throw this.logger.error(e),new l(s.ACS317)}return this.index+this.getPageSize()<=this.messages.length&&(this.index=e),this}hasNext(){return this.logger.debug(c.ITERATOR_HAS_NEXT_CALLED,{engagementId:this.engagementId}),this.index>0}hasPrevious(){return this.logger.debug(c.ITERATOR_HAS_PREVIOUS_CALLED,{engagementId:this.engagementId}),!this.capturedAll||this.index+this.getPageSize()<this.messages.length}}class W{constructor(){this.cachedEngagements=[],this.logger=I();try{this.logger.debug(c.READ_SESSION_STORAGE);const e=window.sessionStorage.getItem(c.CCAAS_ACTIVE_ENGAGEMENTS_KEY);this.cachedEngagements=e?JSON.parse(e):[]}catch(e){this.logger.warn(e),this.logger.warn(t(s.ACS212))}}put(e){return this.cachedEngagements.push(e),this.syncSessionStorage(),this.cachedEngagements}remove(e){const t=this.cachedEngagements.findIndex((t=>t===e));return t>=0&&(this.cachedEngagements.splice(t,1),this.syncSessionStorage()),this.cachedEngagements}getAll(){return this.cachedEngagements}getSize(){return this.cachedEngagements.length}exists(e){return!!this.cachedEngagements.find((t=>t===e))}clear(){this.cachedEngagements=[]}syncSessionStorage(){if(window.sessionStorage)try{window.sessionStorage.setItem(c.CCAAS_ACTIVE_ENGAGEMENTS_KEY,JSON.stringify(this.cachedEngagements)),this.logger.debug(c.WRITE_SESSION_STORAGE)}catch(e){this.logger.warn(e),this.logger.warn(t(s.ACS213))}else this.logger.warn(t(s.ACS213))}}class K{constructor(e,t,s,i,n){this.clientType="web",this.sessionParameters=e.sessionParameters,this.sessionId=e.sessionId,this.sessionStorage=window.sessionStorage,this.chatConfig=t,this.restController=s,this.eventDispatcher=i,this.logger=I(),this.engagementCache=new W,this.timerController=n,this.eventReceiver=new F(t,i.getDispatchFunction(),this.sessionId,n),this.ith=this.timerController.addIdleTimeoutListener(this.handleIdleTimeout.bind(this)),window.sessionStorage.setItem(c.CCAAS_SESSION_ID_KEY,this.sessionId);const a=this.engagementCache.getAll().filter((t=>!e.engagements.find((e=>e.engagementId===t))));for(const e of a)this.engagementCache.remove(e);const o=this.engagementCache.getAll();o.length&&(this.logger.debug(c.FOUND_ACTIVE_ENGAGEMENTS,{sessionId:this.sessionId,activeEngagements:o}),this.eventReceiver.start()),this._engagements=new Map,this.eventDispatcher.setEngagementUpdateMethod(this.partiallyUpdateEngagement.bind(this)),this.eventDispatcher.setEngagementTerminateMethod(this.terminateEngagement.bind(this));for(const i of e.engagements)this._engagements.set(i.engagementId,new x(t,s,{sessionId:this.sessionId,destructorFunction:this.engagementSelfDestroy.bind(this),activationFunction:this.pesudoEngagementActivation.bind(this)},i,!!o.find((e=>e===i.engagementId)),n));n.startIdleTimer()}resumeEventReceiver(){this.eventReceiver.resume()}retryConnection(){this.eventReceiver.retry()}handleIdleTimeout(){this.timerController.startGraceTimer(),this.eventDispatcher.invokeEventHandler(w.IDLE_TIMEOUT_EXPIRED,{eventDate:new Date,gracePeriod:this.chatConfig.graceTimeout})}async engagementSelfDestroy(e){this.logger.debug(c.REMOVING_ENGAGEMENT,{sessionId:this.sessionId,engagementId:e}),this._engagements.delete(e),this.engagementCache.remove(e),0===this.engagementCache.getSize()&&(this.logger.debug(c.NO_ACTIVE_ENGAGEMENTS,{sessionId:this.sessionId}),this.eventReceiver.stop())}async pesudoEngagementActivation(){0===this.engagementCache.getSize()&&this.eventReceiver.start()}terminateEngagement(e){var t;this.logger.debug(c.REMOVING_ENGAGEMENT,{sessionId:this.sessionId,engagementId:e}),null===(t=this._engagements.get(e))||void 0===t||t.terminate(),this._engagements.delete(e),this.engagementCache.remove(e),0===this.engagementCache.getSize()&&(this.logger.debug(c.NO_ACTIVE_ENGAGEMENTS,{sessionId:this.sessionId}),this.eventReceiver.stop())}partiallyUpdateEngagement(e,t,s){const i=this._engagements.get(e);if(void 0===i)return!1;switch(t){case b.AddParticipant:i.updateParticipant(s),s.participantType===o.CUSTOMER&&(i.updateStatus(E.ACTIVE),this.engagementCache.put(i.engagementId),this.logger.debug(c.ENGAGEMENT_ACTIVATED,{sessionId:this.sessionId,engagementId:e}));break;case b.RemoveParticipant:i.removeParticipant(s),s.participantType===o.CUSTOMER&&(this.logger.debug(c.REMOVING_ENGAGEMENT,{sessionId:this.sessionId,engagementId:e}),i.terminate(),this._engagements.delete(e),this.engagementCache.remove(e),0===this.engagementCache.getSize()&&(this.logger.debug(c.NO_ACTIVE_ENGAGEMENTS,{sessionId:this.sessionId}),this.eventReceiver.stop()))}return!0}get engagements(){return[...this._engagements.values()]}verifyResponse(e){const t=V(e);if(t)throw this.logger.error(`${c.SERVER_RESPONDED_WITH} ${e.status}`),new l(t);return e}getEngagements(){return new Promise(((e,t)=>{this.restController.send(k.GET_SESSION.requestType,k.GET_SESSION.path(this.chatConfig.integrationId,this.sessionId)).catch((e=>{throw new l(s.ACS306)})).then((e=>this.verifyResponse(e).json())).then((t=>{var s,i;const n=t.engagements;for(const e of this._engagements.keys()){const t=n.find((t=>t.engagementId===e));t?null===(s=this._engagements.get(e))||void 0===s||s.updateEngagement(t):(null===(i=this._engagements.get(e))||void 0===i||i.terminate(),this._engagements.delete(e))}const a=n.filter((e=>!this._engagements.has(e.engagementId)));for(const e of a)this._engagements.set(e.engagementId,new x(this.chatConfig,this.restController,{sessionId:this.sessionId,destructorFunction:this.engagementSelfDestroy.bind(this),activationFunction:this.pesudoEngagementActivation.bind(this)},e,!1,this.timerController));e(this.engagements.map((e=>e.getEngagementImage())))})).catch((e=>{this.logger.error(e),t(e)}))}))}getEngagementById(e){var t;return null===(t=this.engagements.find((t=>t.engagementId===e)))||void 0===t?void 0:t.getEngagementImage()}createEngagement(e){return new Promise(((t,i)=>{this.restController.send(k.CREATE_ENGAGEMENT.requestType,k.CREATE_ENGAGEMENT.path(this.chatConfig.integrationId),JSON.stringify({sessionId:this.sessionId,engagementParameters:null!=e?e:{}})).catch((e=>{throw new l(s.ACS306)})).then((e=>this.verifyResponse(e).json())).then((e=>{this.logger.debug(c.ENGAGEMENT_CREATION_SUCCESSFUL,{sessionId:this.sessionId,engagementId:e.engagementId});const s=new x(this.chatConfig,this.restController,{sessionId:this.sessionId,destructorFunction:this.engagementSelfDestroy.bind(this),activationFunction:this.pesudoEngagementActivation.bind(this)},e,!1,this.timerController);this._engagements.set(s.engagementId,s),this.pesudoEngagementActivation(),t(s.getEngagementImage())})).catch((e=>{this.logger.error(e),i(e)}))}))}terminate(e){return new Promise(((i,n)=>{if(void 0===this.chatConfig.integrationId)throw this.logger.error(t(s.ACS307)),new l(s.ACS307);let a;e&&(a=new Map,a.set(c.REASON,e)),this.restController.send(k.DELETE_SESSION.requestType,k.DELETE_SESSION.path(this.chatConfig.integrationId,this.sessionId),void 0,a).then((e=>{const s=V(e);s&&(this.logger.error(c.SERVER_RESPONDED_WITH+e.status),this.logger.error(t(s)))})).catch((e=>{this.logger.error(e)})).finally((()=>{for(const e of this._engagements.values())e.terminate();this._engagements.clear(),this.eventDispatcher.removeSessionMethods(),this.eventReceiver.stop(),this.eventReceiver.clearTimeoutHandlers(),this.engagementCache.clear(),this.timerController.stopAllTimers(),this.timerController.removeIdleTimeoutListener(this.ith),i()}))}))}}const $=I(),z=new class{constructor(){this._reconnectionTimeout=200,this._idleTimeout=90,this._graceTimeout=30,this._logLevel="DEBUG",this._isSecure=!0,this._messagesPageSize=10,this._urlBasePath="/sdk/digital/chat",this._tokenExpiryWarningTime=18e4}get reconnectionTimeout(){return this._reconnectionTimeout}set reconnectionTimeout(e){"number"==typeof e&&(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{rct:this._reconnectionTimeout}),this._reconnectionTimeout=e)}get idleTimeout(){return this._idleTimeout}set idleTimeout(e){"number"==typeof e&&(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{idt:this._idleTimeout}),this._idleTimeout=e)}get graceTimeout(){return this._graceTimeout}set graceTimeout(e){"number"==typeof e&&(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{gct:this._graceTimeout}),this._graceTimeout=e)}get logLevel(){return this._logLevel}set logLevel(e){"string"==typeof e&&(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{ll:this._logLevel}),this._logLevel=e)}get ccaasURL(){return this._ccaasURL}set ccaasURL(e){"string"!=typeof e&&void 0!==e||(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{url:this._ccaasURL}),this._ccaasURL=e)}get jwtToken(){return this._jwtToken}set jwtToken(e){"string"!=typeof e&&void 0!==e||(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{jwt:this._jwtToken}),this._jwtToken=e)}get isSecure(){return this._isSecure}set isSecure(e){"boolean"==typeof e&&(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{sec:this._isSecure}),this._isSecure=e)}get messagesPageSize(){return this._messagesPageSize}get urlBasePath(){return this._urlBasePath}set urlBasePath(e){this._urlBasePath=e}set messagesPageSize(e){"number"==typeof e&&(this._messagesPageSize=e)}get integrationId(){return this._integrationId}set integrationId(e){void 0!==e&&"string"!=typeof e||(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{intId:this._integrationId}),this._integrationId=e)}get apiGatewayAppKey(){return this._apiGatewayAppKey}set apiGatewayAppKey(e){void 0!==e&&"string"!=typeof e||(this.backupConfig=Object.assign(Object.assign({},this.backupConfig),{aKey:this._apiGatewayAppKey}),this._apiGatewayAppKey=e)}get tokenExpiryWarningTime(){return this._tokenExpiryWarningTime}revert(){void 0!==this.backupConfig&&(this.revertTimeoutConfigs(),this.revertConnectionConfigs(),this.backupConfig.ll&&(this._logLevel=this.backupConfig.ll),this.backupConfig.jwt&&(this._jwtToken=this.backupConfig.jwt),this.backupConfig=void 0)}revertTimeoutConfigs(){var e,t,s;(null===(e=this.backupConfig)||void 0===e?void 0:e.rct)&&(this._reconnectionTimeout=this.backupConfig.rct),(null===(t=this.backupConfig)||void 0===t?void 0:t.idt)&&(this._idleTimeout=this.backupConfig.idt),(null===(s=this.backupConfig)||void 0===s?void 0:s.gct)&&(this._graceTimeout=this.backupConfig.gct)}revertConnectionConfigs(){var e,t,s,i;(null===(e=this.backupConfig)||void 0===e?void 0:e.url)&&(this._ccaasURL=this.backupConfig.url),(null===(t=this.backupConfig)||void 0===t?void 0:t.sec)&&(this._isSecure=this.backupConfig.sec),(null===(s=this.backupConfig)||void 0===s?void 0:s.intId)&&(this._integrationId=this.backupConfig.intId),(null===(i=this.backupConfig)||void 0===i?void 0:i.aKey)&&(this._apiGatewayAppKey=this.backupConfig.aKey)}commit(){this.backupConfig=void 0}},J=new class{constructor(e){this.eventHandlers=new Map,this.config=e,this.shouldDispatch=!1,this.logger=I()}addEventHandler(e,t){this.eventHandlers.set(e,t)}removeEventHandler(e){this.eventHandlers.delete(e)}removeAllHandlers(){this.eventHandlers.clear()}async invokeEventHandler(e,t){var s;null===(s=this.eventHandlers.get(e))||void 0===s||s(t)}async dispatchEvents(e){if(this.shouldDispatch)for(const t of e)this.processEvent(t);else this.logger.debug(c.EVENT_DISPATCHING_DISABLED)}processEvent(e){var t;switch(e.type){case G.ENGAGEMENT_CREATED:{const t=e.event;this.logger.debug(c.ENGAGEMENT_CREATED,{sessionId:t.sessionId,engagementId:t.engagementId});break}case G.ENGAGEMENT_ERROR:null===(t=this.engagementTerminateMethod)||void 0===t||t.call(this,e.event.engagementId),this.invokeEventHandler(w.ENGAGEMENT_ERROR,L(e.event));break;case G.PARTICIPANT_ADDED:{const t=e.event;this.processParticipantAddedEvent(t);break}case G.PARTICIPANT_DISCONNECTED:{const t=e.event;this.processParticipantDisconnectedEvent(t);break}case G.MESSAGE:{const t=e.event;this.processMessageEvent(t);break}case w.EVENT_STREAM_FAILED:this.invokeEventHandler(w.EVENT_STREAM_FAILED,e.event);break;case w.EVENT_STREAM_CONNECTED:this.invokeEventHandler(w.EVENT_STREAM_CONNECTED,{eventDate:new Date});break;case w.EVENT_STREAM_CONNECTING:this.invokeEventHandler(w.EVENT_STREAM_CONNECTING,{eventDate:new Date});break;case w.EVENT_STREAM_CLOSED:this.invokeEventHandler(w.EVENT_STREAM_CLOSED,{eventDate:new Date});break;default:this.logger.debug(c.RECEIVED_UNKNOWN_EVENT,{eventName:e.type})}}processMessageEvent(e){this.logger.debug(c.PROCESSING_MESSAGE_EVENT,{messageId:e.message.messageId,senderParticipantId:e.participant.participantId,senderParticipantType:e.participant.participantType}),e.participant.participantType===o.CUSTOMER?this.invokeEventHandler(w.MESSAGE_DELIVERED,O(e)):this.invokeEventHandler(w.MESSAGE_ARRIVED,O(e))}processParticipantDisconnectedEvent(e){var i;(null===(i=this.engagementUpdateMethod)||void 0===i?void 0:i.call(this,e.engagementId,b.RemoveParticipant,e.participant))?(this.invokeEventHandler(w.PARTICIPANT_DISCONNECTED,y(e)),e.participant.participantType===o.CUSTOMER&&this.invokeEventHandler(w.ENGAGEMENT_TERMINATED,{engagementId:e.engagementId,dialogId:e.dialogId,eventDate:new Date})):this.logger.debug(t(s.ACS319),{sesionId:e.sessionId,engagementId:e.engagementId})}processParticipantAddedEvent(e){var i;(null===(i=this.engagementUpdateMethod)||void 0===i?void 0:i.call(this,e.engagementId,b.AddParticipant,e.participant))?(e.participant.participantType===o.CUSTOMER&&this.invokeEventHandler(w.ENGAGEMENT_ACTIVE,{engagementId:e.engagementId,dialogId:e.dialogId,eventDate:new Date}),this.invokeEventHandler(w.PARTICIPANT_ADDED,f(e))):this.logger.debug(t(s.ACS319),{sesionId:e.sessionId,engagementId:e.engagementId})}getDispatchFunction(){return this.dispatchEvents.bind(this)}setEngagementUpdateMethod(e){this.engagementUpdateMethod=e,this.shouldDispatch=!0}setEngagementTerminateMethod(e){this.engagementTerminateMethod=e,this.shouldDispatch=!0}removeSessionMethods(){this.engagementUpdateMethod=void 0,this.engagementTerminateMethod=void 0,this.shouldDispatch=!1}}(z),X=new class{constructor(e){this._config=e}send(e,t,s,i,n=!1){var a,o,r,g;let E,d,h={Authorization:"Bearer "+(null===(a=this._config)||void 0===a?void 0:a.jwtToken),appkey:null===(o=this._config)||void 0===o?void 0:o.apiGatewayAppKey};e!==P.POST&&e!==P.PUT||(h["Content-Type"]="application/json");let c={method:e,headers:h};return s&&Object.defineProperty(c,"body",{value:s,writable:!1}),n||(d=null===(r=this._config)||void 0===r?void 0:r.urlBasePath,t=(null===(g=this._config)||void 0===g?void 0:g.ccaasURL)+(d||"")+t),i&&(t+=this.appendQueryParams(i)),E=new Request(t,c),fetch(E)}appendQueryParams(e){let t="";for(let s of e.entries())t=t+s[0]+"="+s[1]+"&";return"?"+new URLSearchParams(t).toString()}}(z),Y=new class{constructor(e){this.TTL=e,this.tokenExpiryWarnPeriod=e,this.beforeWarnPeriod=0}clear(){clearTimeout(this.tokenExpiryWarningTimer),clearTimeout(this.tokenExpiryTimer)}start(e,t,s){this.TTL=e,this.beforeWarnPeriod=e-this.tokenExpiryWarnPeriod,this.clear(),this.tokenExpiryWarningTimer=window.setTimeout((()=>{const i=e>=this.tokenExpiryWarnPeriod?this.tokenExpiryWarnPeriod:e;this.tokenExpiryTimer=setTimeout(s,i),t(i)}),this.beforeWarnPeriod)}restart(e,t,s){this.start(e,t,s)}}(z.tokenExpiryWarningTime),q=new class{constructor(e){this.atomicHandle=0,this.chatConfig=e,this.logger=I(),this.reconnectionTimeoutHandlers=new Map,this.idleTimeoutHandlers=new Map,this.graceTimeoutHandlers=new Map,this.current=void 0}addReconnectionTimeoutListener(e){const t=this.atomicHandle++;return this.reconnectionTimeoutHandlers.set(t,e),t}addIdleTimeoutListener(e){const t=this.atomicHandle++;return this.idleTimeoutHandlers.set(t,e),t}addGraceTimeoutListener(e){const t=this.atomicHandle++;return this.graceTimeoutHandlers.set(t,e),t}removeReconnectionTimeoutListener(e){this.reconnectionTimeoutHandlers.delete(e)}removeIdleTimeoutListener(e){this.idleTimeoutHandlers.delete(e)}removeGraceTimeoutListener(e){this.graceTimeoutHandlers.delete(e)}stopCurrentTimer(){switch(this.current){case m.RECONNECTION:window.clearTimeout(this.reconnectionTimer);break;case m.IDLE:window.clearTimeout(this.idleTimer);break;case m.GRACE:window.clearTimeout(this.graceTimer)}this.current=void 0}startReconnectionTimer(){this.stopCurrentTimer(),this.current=m.RECONNECTION,this.reconnectionTimer=window.setTimeout(this.invokeReconnectionTimeoutHandlers.bind(this),1e3*this.chatConfig.reconnectionTimeout),this.logger.debug(c.RECONNECTION_TIMER_STARTED)}stopReconnectionTimer(){this.current===m.RECONNECTION&&(window.clearTimeout(this.reconnectionTimer),this.current=void 0)}startIdleTimer(){this.stopCurrentTimer(),this.current=m.IDLE,this.idleTimer=window.setTimeout(this.invokeIdleTimeoutHandlers.bind(this),1e3*this.chatConfig.idleTimeout),this.logger.debug(c.IDLE_TIMER_STARTED)}stopIdleTimer(){this.current===m.IDLE&&(window.clearTimeout(this.idleTimer),this.current=void 0)}startGraceTimer(){this.stopCurrentTimer(),this.current=m.GRACE,this.graceTimer=window.setTimeout(this.invokeGraceTimeoutHandlers.bind(this),1e3*this.chatConfig.graceTimeout),this.logger.debug(c.GRACE_TIMER_STARTED)}stopGraceTimer(){this.current===m.GRACE&&(window.clearTimeout(this.graceTimer),this.current=void 0)}stopAllTimers(){window.clearTimeout(this.reconnectionTimer),window.clearTimeout(this.idleTimer),window.clearTimeout(this.graceTimer),this.current=void 0,this.logger.debug(c.ALL_TIMERS_STOPPED)}invokeReconnectionTimeoutHandlers(){this.logger.debug(c.RECONNECTION_TIMEOUT_OCCURED),this.current=void 0;const e=this.reconnectionTimeoutHandlers.values();for(const t of e)t()}invokeIdleTimeoutHandlers(){this.logger.debug(c.IDLE_TIMEOUT_OCCURED),this.current=void 0;const e=this.idleTimeoutHandlers.values();for(const t of e)t()}invokeGraceTimeoutHandlers(){this.logger.debug(c.GRACE_TIMEOUT_OCCURED),this.current=void 0;const e=this.graceTimeoutHandlers.values();for(const t of e)t()}activity(){this.current!==m.IDLE&&this.current!==m.GRACE||this.startIdleTimer()}}(z);let Z,Q=!1;function ee(){Q=!0}function te(){Q=!1}function se(e){if($.debug(c.SHUTDOWN_CALLED,{reason:e}),Q)throw $.error(t(s.ACS321)),new l(s.ACS321);if(void 0===Z)throw $.error(t(s.ACS310)),new l(s.ACS310);return p(A.isOptionalOneOf(e,Object.values(h)),T.ShutdownReason.shouldBeOneOf),ee(),window.sessionStorage.removeItem(c.CCAAS_SESSION_ID_KEY),window.sessionStorage.removeItem(c.CCAAS_ACTIVE_ENGAGEMENTS_KEY),Z.terminate(e).then((()=>{Z=void 0,Y.clear(),z.jwtToken=void 0,z.commit(),$.debug(c.SHUTDOWN_SUCCESSFUL);const t={eventDate:new Date};e&&(t.reason=e),J.invokeEventHandler(w.SHUTDOWN,t),te()}))}function ie(e){try{const t=e.split(".")[2],s=window.atob(t),i=JSON.parse(s).exp,n=new Date(0);return n.setUTCSeconds(i),n}catch(e){throw $.error(e),new l(s.ACS305)}}function ne(e){const t=new Date;$.debug(c.TOKEN_EXPIRY_REMINDER),J.invokeEventHandler(w.TOKEN_EXPIRY_REMINDER,{eventDate:t,expiryDate:new Date(t.getTime()+e)})}function ae(){const e=new Date;$.debug(c.TOKEN_EXPIRED),J.invokeEventHandler(w.TOKEN_EXPIRED,{eventDate:new Date,expiredDate:e})}return q.addGraceTimeoutListener((()=>{se(h.USER_INACTIVE)})),e.createEngagement=function(e){if($.debug(c.CREATE_ENGAGEMENT_CALLED),void 0===Z)throw $.error(t(s.ACS310)),new l(s.ACS310);return p(N.isOptionalMappedData(e,20,64,256),T.EngagementParameters.shouldBeObject),q.activity(),Z.createEngagement(e)},e.getEngagementById=function(e){if($.debug(c.GET_ENGAGEMENT_CALLED,{engagementId:e}),void 0===Z)throw $.error(t(s.ACS310)),new l(s.ACS310);return p(N.isString(e),T.EngagementId.shouldBeString),p(A.isUUID(e),T.EngagementId.shouldBeUUID),Z.getEngagementById(e)},e.getEngagements=function(){if($.debug(c.GET_ENGAGEMENTS_CALLED),void 0===Z)throw $.error(t(s.ACS310)),new l(s.ACS310);return Z.getEngagements()},e.init=function(e,i){if(console.debug(`${Date()} @ Avaya CCaaS Chat SDK [DEBUG] : ${c.INIT_CALLED} (integrationId = ${e.integrationId}, reconnectionTimeout = ${null==i?void 0:i.reconnectionTimeout}, idleTimeout = ${null==i?void 0:i.idleTimeout}, idleShutdownGraceTimeout = ${null==i?void 0:i.idleShutdownGraceTimeout}, logLevel = ${null==i?void 0:i.logLevel})`),Q)throw $.error(t(s.ACS321)),new l(s.ACS321);if(void 0!==Z)return $.warn(t(s.ACS204)),Promise.reject(s.ACS204);if(a=e,!(N.isString(a.hostURL)&&N.isString(a.integrationId)&&N.isString(a.token)&&N.isString(a.appkey)&&N.isOptionalString(a.displayName)&&(void 0===a.displayName||A.notMoreThan(a.displayName,70))&&A.isHttpsURL(a.hostURL)&&A.isUUID(a.integrationId)&&A.isJWT(a.token)&&N.isOptionalMappedData(a.sessionParameters,20,64,256)))throw $.error(t(s.ACS302)),new l(s.ACS302);var a;if(!function(e){if(void 0===e)return!0;if("number"!=typeof e.reconnectionTimeout||e.reconnectionTimeout<120||e.reconnectionTimeout>900)return $.warn(t(s.ACS207)),!1;if("number"!=typeof e.idleTimeout||e.idleTimeout<300||e.idleTimeout>3300)return $.warn(t(s.ACS208)),!1;if("number"!=typeof e.idleShutdownGraceTimeout||e.idleShutdownGraceTimeout<30||e.idleShutdownGraceTimeout>300)return $.warn(t(s.ACS209)),!1;const i=e.logLevel;if(void 0!==i&&"string"!=typeof i)return!1;if(null!=i&&!Object.values(n).includes(i))return $.warn(t(s.ACS210)),!1;return!0}(i))throw $.error(t(s.ACS303)),new l(s.ACS303);const o=ie(e.token);return p(o>new Date,T.Token.shouldBeLive),ee(),function(e,t){var s,i,n,a;z.ccaasURL=e.hostURL,z.reconnectionTimeout=null!==(s=null==t?void 0:t.reconnectionTimeout)&&void 0!==s?s:z.reconnectionTimeout,z.idleTimeout=null!==(i=null==t?void 0:t.idleTimeout)&&void 0!==i?i:z.idleTimeout,z.graceTimeout=null!==(n=null==t?void 0:t.idleShutdownGraceTimeout)&&void 0!==n?n:z.graceTimeout,z.logLevel=null!==(a=null==t?void 0:t.logLevel)&&void 0!==a?a:z.logLevel,z.integrationId=e.integrationId,z.jwtToken=e.token,z.apiGatewayAppKey=e.appkey}(e,i),(null==i?void 0:i.logLevel)&&$.setLevel(i.logLevel),new Promise(((t,i)=>{let n,a,r;const g=window.sessionStorage.getItem(c.CCAAS_SESSION_ID_KEY);null===g?($.debug(c.SESSION_NOT_IN_CACHE),n=k.CREATE_SESSION.requestType,a=k.CREATE_SESSION.path(z.integrationId),r=_(e)):($.debug(c.SESSION_IN_CACHE,{sessionId:g}),n=k.GET_SESSION.requestType,a=k.GET_SESSION.path(z.integrationId,g),r=void 0),X.send(n,a,r).catch((()=>{throw new l(s.ACS306)})).then((e=>{const t=V(e);if(t)throw $.error(c.SERVER_RESPONDED_WITH+e.status),new l(t);return e.json()})).then((e=>{Z=new K(e,z,X,J,q),z.commit(),$.debug(c.SESSION_ESTABLISH_SUCCESS,{sessionId:e.sessionId,engagements:e.engagements.map((e=>e.engagementId))});const s={displayName:e.displayName,sessionParameters:e.sessionParameters,engagements:Z.engagements&&Z.engagements.length?Z.engagements.map((e=>e.getEngagementImage())):[]},i=o.getTime()-(new Date).getTime();Y.start(i,ne,ae),$.debug(c.INITIALIZATION_COMPLETE),J.invokeEventHandler(w.INITIALIZED,s),t(s)})).catch((e=>{$.error(e),z.revert(),i(e)})).finally((()=>{te()}))}))},e.off=function(e){e?$.debug(c.OFF_CALLED,{eventName:e}):$.debug(c.OFF_CALLED_PARAM_LESS),null==e||Object.values(w).includes(e)?e?(J.removeEventHandler(e),$.debug(c.EVENT_HANDLER_REMOVED+e)):($.warn(t(s.ACS202)),J.removeAllHandlers()):$.warn(t(s.ACS203))},e.on=function(e,i){$.debug(c.ON_CALLED,{eventName:e}),null==e||Object.values(w).includes(e)?(p(N.isFunction(i),T.EventHandler.shouldBeFunction),J.addEventHandler(e,i),$.debug(c.EVENT_HANDLER_ATTACHED+e)):$.warn(t(s.ACS203))},e.resetIdleTimeout=function(){$.debug(c.RESET_IDLE_TIMEOUT_CALLED),Z&&q.activity()},e.retryConnection=function(){if($.debug(c.RETRY_CONNECTION_CALLED),void 0===Z)throw $.error(t(s.ACS310)),new l(s.ACS310);Z.retryConnection(),$.debug(c.RETRY_CONNECTION_ATTEMPTED)},e.setJwtToken=function(e){$.debug(c.SET_TOKEN_CALLED),p(N.isString(e),T.Token.shouldBeString),p(A.isJWT(e),T.Token.shouldHaveValidFormat);const t=ie(e).getTime()-(new Date).getTime();p(t>0,T.Token.shouldBeLive),t<z.tokenExpiryWarningTime&&$.warn(c.JWT_ALMOST_EXPIRED),z.jwtToken=e,Y.restart(t,ne,ae),void 0!==Z&&Z.resumeEventReceiver()},e.setLogLevel=function(e){$.debug(c.SET_LOG_LEVEL_CALLED,{logLevel:e}),p(N.isString(e),T.LogLevel.shouldBeOneOf),p(A.isOneOf(e,Object.values(n)),T.LogLevel.shouldBeOneOf),z.logLevel=e,$.setLevel(e),z.commit()},e.shutdown=se,e.version=function(){return"0.1.53"},e}({});