text: !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).VoicenterEventsSDK=t()}(this,function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function i(e,t,i){return t&&n(e.prototype,t),i&&n(e,i),e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e){return function(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var s={LOGIN_STATUS:"loginStatus",LOGIN:"login",LOGIN_USER:"loginUser",LOGIN_CODE:"loginUserCode",LOGIN_ACCOUNT:"loginAccount",LOGIN_RESPONSE:"loginResponse",QUEUE_EVENT:"QueueEvent",QUEUES_UPDATED:"QueuesUpdated",DIALERS_UPDATED:"DialersUpdated",EXTENSION_EVENT:"ExtensionEvent",EXTENSION_UPDATED:"ExtensionsUpdated",ALL_EXTENSION_STATUS:"AllExtensionsStatus",CONNECT:"connect",CONNECT_ERROR:"connect_error",CONNECT_TIMEOUT:"connect_timeout",DISCONNECT:"disconnect",PONG:"pong",RECONNECT:"reconnect",RECONNECT_ATTEMPT:"reconnect_attempt",RESYNC:"resync",RECONNECTING:"reconnecting",RECONNECT_ERROR:"reconnect_error",RECONNECT_FAILED:"reconnect_failed",KEEP_ALIVE:"keepalive",KEEP_ALIVE_RESPONSE:"keepaliveResponse",CLOSE:"closeme",ERROR:"error"},a=[{URLID:59,Priority:5,Version:2,Domain:"monitor1.voicenter.co"},{URLID:3,Priority:4,Version:2,Domain:"monitor3.voicenter.co.il"},{URLID:4,Priority:3,Version:2,Domain:"monitor4.voicenter.co.il"},{URLID:11,Priority:2,Version:2,Domain:"monitor11.voicenter.co"},{URLID:5,Priority:0,Version:2,Domain:"monitor5.voicenter.co.il"}],c=function(){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this,e),this.debug=n.debug}return i(e,[{key:"_log",value:function(e,t){var n=t?"".concat(e,", %c Data -> ").concat(JSON.stringify(t)):"".concat(e),i=(new Date).toUTCString();console.log("%c ".concat(i,": %c ").concat(n),"color: #276749;","color: #4299e1;","color: #2c3e50;")}},{key:"_error",value:function(e,t){var n=t?"".concat(e,", Data -> ").concat(JSON.stringify(t)):"".concat(e),i=(new Date).toUTCString();console.error("".concat(i,": ").concat(n))}},{key:"log",value:function(e,t){this.debug&&(e&&!t?this._log(e):this._log(e,t))}},{key:"error",value:function(e,t){this.debug&&(e&&!t?this._error(e):this._error(e,t))}}]),e}();var l=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},u="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},h="object"==typeof u&&u&&u.Object===Object&&u,v="object"==typeof self&&self&&self.Object===Object&&self,f=h||v||Function("return this")(),p=function(){return f.Date.now()},E=f.Symbol,y=Object.prototype,d=y.hasOwnProperty,m=y.toString,g=E?E.toStringTag:void 0;var T=function(e){var t=d.call(e,g),n=e[g];try{e[g]=void 0;var i=!0}catch(e){}var o=m.call(e);return i&&(t?e[g]=n:delete e[g]),o},_=Object.prototype.toString;var k=function(e){return _.call(e)},S="[object Null]",N="[object Undefined]",O=E?E.toStringTag:void 0;var C=function(e){return null==e?void 0===e?N:S:O&&O in Object(e)?T(e):k(e)};var D=function(e){return null!=e&&"object"==typeof e},R="[object Symbol]";var A=function(e){return"symbol"==typeof e||D(e)&&C(e)==R},I=NaN,b=/^\s+|\s+$/g,L=/^[-+]0x[0-9a-f]+$/i,w=/^0b[01]+$/i,x=/^0o[0-7]+$/i,U=parseInt;var P=function(e){if("number"==typeof e)return e;if(A(e))return I;if(l(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=l(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(b,"");var n=w.test(e);return n||x.test(e)?U(e.slice(2),n?2:8):L.test(e)?I:+e},M="Expected a function",j=Math.max,F=Math.min;var Q=function(e,t,n){var i,o,r,s,a,c,u=0,h=!1,v=!1,f=!0;if("function"!=typeof e)throw new TypeError(M);function E(t){var n=i,r=o;return i=o=void 0,u=t,s=e.apply(r,n)}function y(e){var n=e-c;return void 0===c||n>=t||n<0||v&&e-u>=r}function d(){var e=p();if(y(e))return m(e);a=setTimeout(d,function(e){var n=t-(e-c);return v?F(n,r-(e-u)):n}(e))}function m(e){return a=void 0,f&&i?E(e):(i=o=void 0,s)}function g(){var e=p(),n=y(e);if(i=arguments,o=this,c=e,n){if(void 0===a)return function(e){return u=e,a=setTimeout(d,t),h?E(e):s}(c);if(v)return clearTimeout(a),a=setTimeout(d,t),E(c)}return void 0===a&&(a=setTimeout(d,t)),s}return t=P(t)||0,l(n)&&(h=!!n.leading,r=(v="maxWait"in n)?j(P(n.maxWait)||0,t):r,f="trailing"in n?!!n.trailing:f),g.cancel=function(){void 0!==a&&clearTimeout(a),u=0,i=c=o=a=void 0},g.flush=function(){return void 0===a?s:m(p())},g},V=[s.CONNECT_ERROR,s.CONNECT_TIMEOUT,s.DISCONNECT,s.RECONNECT_ATTEMPT,s.RECONNECTING,s.RECONNECT_ERROR,s.RECONNECT_FAILED,{NEWCALL:"NEWCALL",ANSWER:"ANSWER",HANGUP:"HANGUP"}.CLOSE];function G(e){var t=e.eventData,n=e.store,i=e.extensionsModuleName,o=e.queuesModuleName,r=t.name,a=t.data;switch(n.commit("".concat(i,"/SET_IS_SOCKET_OFFLINE"),function(e){var t=e.name;return V.includes(t)}(t)),r){case s.ALL_EXTENSION_STATUS:n.dispatch("".concat(i,"/setExtensions"),a.extensions);break;case s.EXTENSION_EVENT:var c=a.data;c.lastEvent={reason:a.reason,ivrid:a.ivruniqueid};var l=n.state[i].extensions.findIndex(function(e){return e.userID===c.userID});-1!==l&&n.dispatch("".concat(i,"/updateExtension"),{index:l,extension:c});break;case s.LOGIN_STATUS:n.commit("".concat(i,"/SET_SERVER_TIME"),a),n.dispatch("".concat(o,"/setQueues"),a.queues);break;case s.QUEUE_EVENT:var u=a.data,h=(n.state[o].all||[]).findIndex(function(e){return e.QueueID===u.QueueID});-1!==h&&n.dispatch("".concat(o,"/updateQueue"),{index:h,queue:u})}}var K,q=100,W=101,X="hold",J="SET_EXTENSIONS",$="UPDATE_EXTENSIONS",B="SET_SERVER_TIME",Y="SET_IS_SOCKET_OFFLINE";function H(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.callstatus||"";return t=t.toLowerCase(),e.answered&&t===X}var z,Z={namespaced:!0,state:{extensions:[],serverTime:null,serverDelta:0,serverOffset:0,isSocketOffline:!1,offlineSocketTimestamp:null},mutations:(o(K={},J,function(e,t){e.extensions=t}),o(K,$,function(e,t){var n=t.index,i=t.extension;e.extensions.splice(n,1,i)}),o(K,B,function(e,t){e.serverOffset=60*t.servertimeoffset*1e3||108e5,e.serverTime=1e3*t.servertime-e.serverOffset,e.serverDelta=(new Date).getTime()-e.serverTime}),o(K,Y,function(e,t){e.isSocketOffline=t,e.offlineSocketTimestamp=t?(new Date).getTime():null}),K),actions:{setExtensions:async function(e,t){(0,e.commit)(J,t)},updateExtension:async function(e,t){(0,e.commit)($,t)}},getters:{isSocketOffline:function(e){if(!e.offlineSocketTimestamp||isNaN(e.offlineSocketTimestamp))return!1;var t=(new Date).getTime();return e.isSocketOffline&&t-e.offlineSocketTimestamp>6e4},extensionsWithCalls:function(e){return function(t){var n=[];return e.extensions.forEach(function(e){e.calls.length>0&&(e.calls.filter(H).length?e.representativeStatus=W:e.representativeStatus=q),n.push(e)}),t?n.filter(function(e){return 2!==e.representativeStatus}):n}},extensionCountByStatus:function(e,t){return function(e){return t.extensionsWithCalls.filter(function(t){return t.representativeStatus===e}).length||0}}}},ee="SET_QUEUES",te="UPDATE_QUEUES",ne={namespaced:!0,state:{all:[]},mutations:(o(z={},ee,function(e,t){e.all=t}),o(z,te,function(e,t){var n=t.index,i=t.queue;e.all.splice(n,1,i)}),z),actions:{setQueues:async function(e,t){(0,e.commit)(ee,t)},updateQueue:async function(e,t){(0,e.commit)(te,t)}},getters:{queueWithActiveCalls:function(e){return e.all.filter(function(e){return e.Calls.length})},allQueueCalls:function(e,t){var n=[];return t.queueWithActiveCalls.forEach(function(e){var t=e.Calls||[];n.push.apply(n,r(t))}),n},filterQueuesByIds:function(e){return function(t){return t&&Array.isArray(t)?e.all.filter(function(e){return t.includes(e.QueueID)}):e.all}}}};var ie={url:"https://monitorapi.voicenter.co.il/monitorAPI/getMonitorUrls",fallbackServer:{Domain:"monitor5.voicenter.co.il",Priority:0},loginUrl:"https://loginapi.voicenter.co.il/monitorAPI/Login",refreshTokenUrl:"https://loginapi.voicenter.co.il/monitorAPI/RefreshIdentityToken",servers:a,token:null,loginType:"token",forceNew:!0,reconnectionDelay:1e4,reconnectionDelayMax:1e4,maxReconnectAttempts:2,timeout:1e4,keepAliveTimeout:6e4,idleInterval:3e5,protocol:"https",transports:["websocket"],upgrade:!1,store:null,extensionsModuleName:"sdkExtensions",queuesModuleName:"sdkQueues",serverFetchStrategy:"remote",serverType:null},oe=[],re=new Map,se=function(){function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t(this,n),this.options=Object.assign({},ie,{},e),this.argumentOptions=Object.assign({},e),!this.options.loginType)throw new Error("A login type should be provided");this.Logger=new c(this.options),this.servers=[],this.server=null,this.socket=null,this.connected=!1,this.connectionEstablished=!1,this._lastEventTimestamp=(new Date).getTime(),this._initReconnectOptions(),this._listenersMap=re,this._retryConnection=Q(this._connect.bind(this),this.reconnectOptions.reconnectionDelay,{leading:!0,trailing:!1}),this._lastLoginTimestamp=null,this._handleLocalEvents=!1,this._registerExtensionsModule(),this._registerQueueModule()}return i(n,[{key:"getLastEventTimestamp",value:function(){return this._lastEventTimestamp}},{key:"_reSync",value:function(){this.emit(s.RESYNC,{cache:!1})}},{key:"_registerExtensionsModule",value:function(){var e=this.options.extensionsModuleName||"sdkExtensions";this._validateStoreModule(e)&&(this.options.store.registerModule(e,Z),this._handleLocalEvents=!0)}},{key:"_registerQueueModule",value:function(){var e=this.options.queuesModuleName||"sdkQueues";this._validateStoreModule(e)&&(this.options.store.registerModule(e,ne),this._handleLocalEvents=!0)}},{key:"_validateStoreModule",value:function(e){var t=this.options.store;return!!t&&(t.state[e]&&t.unregisterModule(e),!0)}},{key:"_initReconnectOptions",value:function(){this.reconnectOptions={retryCount:1,maxReconnectAttempts:this.options.maxReconnectAttempts,reconnectionDelay:this.options.reconnectionDelay,minReconnectionDelay:this.options.reconnectionDelay,maxReconnectionDelay:3e5}}},{key:"_onConnect",value:function(){this._initReconnectDelays(),this.connected=!0,this.Logger.log(s.CONNECT,this.reconnectOptions)}},{key:"_initReconnectDelays",value:function(){this.reconnectOptions.retryCount=1;var e=this.reconnectOptions.minReconnectionDelay;this.reconnectOptions.reconnectionDelay=e,this.socket.io.reconnectionDelay(e),this.socket.io.reconnectionDelayMax(e)}},{key:"_onConnectError",value:function(e){this._retryConnection("next"),this.connected=!1,this.Logger.log(s.CONNECT_ERROR,e)}},{key:"_onError",value:function(e){this.Logger.log(s.ERROR,e)}},{key:"_onReconnectFailed",value:function(){this._retryConnection("next"),this.Logger.log(s.RECONNECT_FAILED,this.reconnectOptions)}},{key:"_onConnectTimeout",value:function(){this._retryConnection("next"),this.Logger.log(s.CONNECT_TIMEOUT,this.reconnectOptions)}},{key:"_onReconnectAttempt",value:function(){if(this.reconnectOptions.retryCount>=this.reconnectOptions.maxReconnectAttempts)this._retryConnection("next");else{if(this.reconnectOptions.reconnectionDelay<this.reconnectOptions.maxReconnectionDelay){var e=this.reconnectOptions.minReconnectionDelay*this.reconnectOptions.retryCount;this.reconnectOptions.reconnectionDelay=e,this.socket.io.reconnectionDelay(e),this.socket.io.reconnectionDelayMax(e)}this.reconnectOptions.retryCount++,this.Logger.log(s.RECONNECT_ATTEMPT,this.reconnectOptions)}}},{key:"_onDisconnect",value:function(e){this.connected=!1,this.Logger.log(s.DISCONNECT,e),this._connect("next")}},{key:"_onKeepAlive",value:function(t){("object"!==e(t)||0===t.errorCode)&&t&&this.connected?(this.Logger.log(s.KEEP_ALIVE_RESPONSE),this._lastEventTimestamp=(new Date).getTime()):this._initSocketConnection()}},{key:"_onLoginResponse",value:async function(e){var t;e.Client&&await(t=e.Client,new Promise(function(e){var n=document.createElement("script");n.src=t,n.onload=function(){e()},n.onerror=function(){reject()},document.body.append(n)})),e.URL&&(this.server={Priority:0,Domain:e.URL.replace("https://","")}),e.URLList&&Array.isArray(e.URLList)&&(this.servers=e.URLList.map(function(e,t){return{Priority:t,Domain:e.replace("https://","")}})),e.Token&&(this.options.token=e.Token,this.token=e.Token,await this._connect("default",!0)),e.RefreshToken&&(this.options.refreshToken=e.RefreshToken,this._handleTokenExpiry()),e.TokenExpiry&&(this.options.tokenExpiry=e.TokenExpiry)}},{key:"_handleTokenExpiry",value:function(){var e=this,t=new Date(this.options.tokenExpiry);if(function(e){return!isNaN(e.getTime())}(t)){var n=t.getTime()-(new Date).getTime()-5e3;setTimeout(async function(){var t=await async function(e,t){return(await fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(t)}})).json()}(e.options.refreshTokenUrl,e.options.refreshToken);await e._onLoginResponse(t)},n)}}},{key:"_parsePacket",value:function(e){return e.data?{name:e.data[0],data:e.data[1]}:{}}},{key:"_connect",value:async function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default",t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=null;if("default"===e)n=this._findCurrentServer();else if("next"===e)n=this._findNextAvailableServer();else{if("prev"!==e)throw new Error("Incorrect 'server' parameter passed to connect function ".concat(e,". Should be 'default' or 'next'"));n=this._findMaxPriorityServer()}n||(this.server=this._findCurrentServer()),this._initSocketConnection(),this._initSocketEvents(),this._initKeepAlive(),this._initReconnectDelays(),t||await this.login(this.options.loginType)}},{key:"_checkInit",value:function(){if(!this.connectionEstablished)throw new Error('Make sure you call "sdk.init()" before doing other operations.')}},{key:"_initSocketConnection",value:function(){var e=this.server.Domain,t=this.options.protocol,n="".concat(t,"://").concat(e);this.Logger.log("Connecting to..",n),this.closeAllConnections();var i=Object.assign({},this.options,{debug:!1});this.token&&(i.query={token:this.token}),this.socket=window.io(n,i),oe.push(this.socket),this.connectionEstablished=!0}},{key:"_initSocketEvents",value:function(){this.socket.onevent=this._onEvent.bind(this)}},{key:"_initKeepAlive",value:function(){var e=this;this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.idleInterval&&clearInterval(this.idleInterval),this.keepAliveInterval=setInterval(async function(){var t=(new Date).getTime(),n=2*e.options.keepAliveTimeout;t>e.getLastEventTimestamp()+n?await e._connect("next",!0):e.socket?t>e.getLastEventTimestamp()+e.options.keepAliveTimeout&&e.emit(s.KEEP_ALIVE,e.options.token):e._initSocketConnection()},this.options.keepAliveTimeout),this.idleInterval=setInterval(function(){e.reSync(!1)},this.options.idleInterval)}},{key:"_findCurrentServer",value:function(){var e=null;return this.servers.length&&(e=this.servers[0]),this.server=e,this.server||(this.server=this.options.fallbackServer),this.server}},{key:"_findNextAvailableServer",value:function(){var e=this.server.Priority;if(this.Logger.log("Failover -> Trying to find another server"),e===this.servers.length-1)return this._findMaxPriorityServer();var t=e+1,n=this.servers.find(function(e){return e.Priority===t});return n||(n=this._findMaxPriorityServer())?this.server.Domain!==n.Domain?(this.server=n,this.server):(this.Logger.log("Failover -> Found new server. Connecting to it...",this.server),null):void 0}},{key:"_findMaxPriorityServer",value:function(){this.Logger.log("Fallback -> Trying to find previous server","_findMaxPriorityServer");var e,t,n,i=(e=this.servers,t=null,n=Number.MAX_SAFE_INTEGER,e.forEach(function(e){e.Priority<n&&(n=e.Priority,t=e)}),t);return this.server?this.server&&i.Domain!==this.server.Domain?(this.server=i,this.Logger.log("Fallback -> Trying to find previous server",this.server),this.server):null:(this.server=i,this.server)}},{key:"_getServers",value:async function(){"static"===this.options.serverFetchStrategy&&this.argumentOptions.servers&&Array.isArray(this.argumentOptions.servers)&&this.argumentOptions.servers.length>1&&(this.servers=this.argumentOptions.servers)}},{key:"_onEvent",value:function(e){var t,n=this;if(e.data){var i=this._parsePacket(e);this.Logger.log("New event -> ".concat(i.name),i),this._lastEventTimestamp=(new Date).getTime(),this._listenersMap.forEach(function(e,t){"*"===t?e(i):i.name===t&&e(i)});var r=(o(t={},s.RECONNECT_ATTEMPT,this._onReconnectAttempt),o(t,s.RECONNECT_FAILED,this._onReconnectFailed),o(t,s.CONNECT,this._onConnect),o(t,s.DISCONNECT,this._onDisconnect),o(t,s.ERROR,this._onError),o(t,s.CONNECT_ERROR,this._onConnectError),o(t,s.CONNECT_TIMEOUT,this._onConnectTimeout),o(t,s.KEEP_ALIVE_RESPONSE,this._onKeepAlive),o(t,s.LOGIN_RESPONSE,this._onLoginResponse),o(t,s.EXTENSION_UPDATED,this._reSync),o(t,s.QUEUES_UPDATED,this._reSync),o(t,s.DIALERS_UPDATED,this._reSync),o(t,s.LOGIN_STATUS,function(){n.connected||n._onConnect()}),t)[i.name];r&&"function"==typeof r&&r.call(this,i.data),this._handleLocalEvents&&G(Object.assign({eventData:i},this.options))}}},{key:"init",value:async function(){return!!this.connectionEstablished||(this.socket&&this.emit(s.CLOSE),await this._getToken(),await this.login(this.options.loginType),await this._getServers(),!0)}},{key:"setToken",value:async function(e){this.options.token=e,this.disconnect(),await this.init()}},{key:"closeAllConnections",value:function(){oe.forEach(function(e){e.close(),e.disconnect()}),oe=[],this.socket&&(this.socket.disconnect(),this.socket=null)}},{key:"disconnect",value:function(){this._listenersMap=new Map,this.closeAllConnections()}},{key:"on",value:function(e,t){this._listenersMap.set(e,t),this._checkInit()}},{key:"emit",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._checkInit(),this.Logger.log("EMIT -> ".concat(e),t),this.socket.emit(e,t)}},{key:"reSync",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.emit(s.RESYNC,{cache:e})}},{key:"setMonitorUrl",value:async function(e){var t=this.options.url,n=this.options.serverFetchStrategy;try{if(!e)return;this.options.url=e,this.options.serverFetchStrategy="remote",await this.init()}catch(e){this._onError(e),this.options.url=t,this.options.serverFetchStrategy=n,await this.init()}}},{key:"_getToken",value:function(){var e=this.options.loginType;if(this.token=this.options.token,"token"===e&&!this.token)throw new Error("Token login type expects the token option to be provided")}},{key:"login",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"token";return this._lastLoginTimestamp+1e3>(new Date).getTime()?Promise.resolve():(this._lastLoginTimestamp=(new Date).getTime(),new Promise(async function(n,i){try{var o=(s=e.options.loginUrl,"user"===(c=t)?"".concat(s,"/User"):"token"===c?"".concat(s,"/Token"):"account"===c?"".concat(s,"/Account"):s),r=await async function(e,t){var n=t.email,i=t.password,o=t.token,r=t.username,s=null;s=o?JSON.stringify({token:o}):r?JSON.stringify({username:r,password:i}):JSON.stringify({email:n,pin:i});var a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:s}),c=await a.json();if(c.error)throw new Error(c.error);return c.Data.Socket}(o,{token:e.options.token,email:e.options.email,username:e.options.username,password:e.options.password});await e._onLoginResponse(r),n(r)}catch(t){e.servers=e.argumentOptions.servers||a,i(t)}var s,c}))}}]),n}();return"undefined"!=typeof window&&(window.EventsSDK=se),se});
  //# sourceMappingURL=voicenter-events-sdk.umd.js.map
  