|
!function(e){var t={};function n(o){if(t[o])return t[o].exports;var r=t[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(o,r,function(t){return e[t]}.bind(null,r));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=10)}([function(e,t){function n(t){return e.exports=n="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},e.exports.__esModule=!0,e.exports.default=e.exports,n(t)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function n(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}e.exports=function(e,t,o){return t&&n(e.prototype,t),o&&n(e,o),Object.defineProperty(e,"prototype",{writable:!1}),e},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function n(t){return e.exports=n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},e.exports.__esModule=!0,e.exports.default=e.exports,n(t)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return c(u(e),arguments)}function a(e,t){return i.apply(null,[e].concat(t||[]))}function c(e,t){var n,o,a,c,s,u,l,d,p,f=1,g=e.length,b="";for(o=0;o<g;o++)if("string"==typeof e[o])b+=e[o];else if("object"==typeof e[o]){if((c=e[o]).keys)for(n=t[f],a=0;a<c.keys.length;a++){if(null==n)throw new Error(i('[sprintf] Cannot access property "%s" of undefined value "%s"',c.keys[a],c.keys[a-1]));n=n[c.keys[a]]}else n=c.param_no?t[c.param_no]:t[f++];if(r.not_type.test(c.type)&&r.not_primitive.test(c.type)&&n instanceof Function&&(n=n()),r.numeric_arg.test(c.type)&&"number"!=typeof n&&isNaN(n))throw new TypeError(i("[sprintf] expecting number but found %T",n));switch(r.number.test(c.type)&&(d=n>=0),c.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,c.width?parseInt(c.width):0);break;case"e":n=c.precision?parseFloat(n).toExponential(c.precision):parseFloat(n).toExponential();break;case"f":n=c.precision?parseFloat(n).toFixed(c.precision):parseFloat(n);break;case"g":n=c.precision?String(Number(n.toPrecision(c.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=c.precision?n.substring(0,c.precision):n;break;case"t":n=String(!!n),n=c.precision?n.substring(0,c.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=c.precision?n.substring(0,c.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=c.precision?n.substring(0,c.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}r.json.test(c.type)?b+=n:(!r.number.test(c.type)||d&&!c.sign?p="":(p=d?"+":"-",n=n.toString().replace(r.sign,"")),u=c.pad_char?"0"===c.pad_char?"0":c.pad_char.charAt(1):" ",l=c.width-(p+n).length,s=c.width&&l>0?u.repeat(l):"",b+=c.align?p+n+s:"0"===u?p+s+n:s+p+n)}return b}var s=Object.create(null);function u(e){if(s[e])return s[e];for(var t,n=e,o=[],i=0;n;){if(null!==(t=r.text.exec(n)))o.push(t[0]);else if(null!==(t=r.modulo.exec(n)))o.push("%");else{if(null===(t=r.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var a=[],c=t[2],u=[];if(null===(u=r.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=r.key_access.exec(c)))a.push(u[1]);else{if(null===(u=r.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(u[1])}t[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return s[e]=o}t.sprintf=i,t.vsprintf=a,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=a,void 0===(o=function(){return{sprintf:i,vsprintf:a}}.call(t,n,t,e))||(e.exports=o))}()},function(e,t,n){var o=n(8);e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){var o=n(0).default,r=n(9);e.exports=function(e,t){if(t&&("object"===o(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return r(e)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function n(t,o){return e.exports=n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},e.exports.__esModule=!0,e.exports.default=e.exports,n(t,o)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){"use strict";n.r(t),n.d(t,"WebSocketManager",(function(){return We}));var o=n(0),r=n.n(o),i=n(4),a="NULL",c="CLIENT_LOGGER",s="DEBUG",u="AMZ_WEB_SOCKET_MANAGER:",l="Network offline",d="Network online, connecting to WebSocket server",p="Network offline, ignoring this getWebSocketConnConfig request",f="Heartbeat response not received",g="aws/ping deep heartbeat response not received",b="Heartbeat response received",v="aws/ping deep heartbeat received",y="Sending heartbeat",m="Sending aws/ping deep heartbeat",h="Failed to send heartbeat since WebSocket is not open",S="Failed to send aws/ping deep heartbeat since WebSocket is not open",k="Deep Heartbeat is successful. WebSocketManager has received 200 response from aws/ping",w="Deep Heartbeat failed. WebSocketManager does not receive 200 response from aws/ping",C="Generic topic failed.",O="WebSocket connection established!",L="WebSocket connection is closed",T="WebSocketManager Error, error_event: ",_="Scheduling WebSocket reinitialization, after delay ",x="WebSocket URL cannot be used to establish connection",W="WebSocket Initialization failed - Terminating and cleaning subscriptions",I="Terminating WebSocket Manager",N="Fetching new WebSocket connection configuration",M="Successfully fetched webSocket connection configuration",F="Failed to fetch webSocket connection configuration",E="Retrying fetching new WebSocket connection configuration",D="Initializing Websocket Manager",R="Initializing Websocket Manager Failure callback registered",A="Websocket connection open callback registered",j="Websocket connection close callback registered",H="Websocket connection gain callback registered",P="Websocket connection lost callback registered",G="Websocket subscription failure callback registered",z="Reset Websocket state",q="WebSocketManager Message Error",U="Message received for topic ",J="Invalid incoming message",B="WebsocketManager invoke callbacks for topic success ",V="aws/subscribe",X="aws/unsubscribe",$="aws/heartbeat",K="aws/ping",Z="connected",Q="disconnected",Y={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return Y.assertTrue(null!==e&&void 0!==r()(e),Object(i.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==r()(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},ee=new RegExp("^(wss://)\\w*"),te=new RegExp("^(ws://127.0.0.1:)");Y.validWSUrl=function(e){return ee.test(e)||te.test(e)},Y.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},Y.assertIsObject=function(e,t){if(!Y.isObject(e))throw new Error(t+" is not an object!")},Y.addJitter=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;t=Math.min(t,1);var n=Math.random()>.5?1:-1;return Math.floor(e+n*e*Math.random()*t)},Y.isNetworkOnline=function(){return navigator.onLine},Y.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var ne=Y,oe=n(5),re=n.n(oe),ie=n(6),ae=n.n(ie),ce=n(3),se=n.n(ce),ue=n(7),le=n.n(ue),de=n(1),pe=n.n(de),fe=n(2),ge=n.n(fe);function be(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,o=se()(e);if(t){var r=se()(this).constructor;n=Reflect.construct(o,arguments,r)}else n=o.apply(this,arguments);return ae()(this,n)}}function ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function ye(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(n),!0).forEach((function(t){le()(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ve(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var me=function(){function e(){pe()(this,e)}return ge()(e,[{key:"debug",value:function(e){}},{key:"info",value:function(e){}},{key:"warn",value:function(e){}},{key:"error",value:function(e){}},{key:"advancedLog",value:function(e){}}]),e}(),he=u,Se={DEBUG:10,INFO:20,WARN:30,ERROR:40,ADVANCED_LOG:50},ke=function(){function e(t){pe()(this,e),this.logMetaData=t,this.updateLoggerConfig()}return ge()(e,[{key:"hasLogMetaData",value:function(){return!!this.logMetaData}},{key:"writeToClientLogger",value:function(e,t){if(this.hasClientLogger()){var n=function(e){switch(e){case 10:return"DEBUG";case 20:return"INFO";case 30:return"WARN";case 40:return"ERROR";case 50:return"ADVANCED_LOG"}}(e);switch(e){case Se.DEBUG:return this._clientLogger.debug(n,t,this.logMetaData)||t;case Se.INFO:return this._clientLogger.info(n,t,this.logMetaData)||t;case Se.WARN:return this._clientLogger.warn(n,t,this.logMetaData)||t;case Se.ERROR:return this._clientLogger.error(n,t,this.logMetaData)||t;case Se.ADVANCED_LOG:return this._advancedLogWriter?this._clientLogger[this._advancedLogWriter](n,t,this.logMetaData)||t:""}}}},{key:"isLevelEnabled",value:function(e){return e>=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.prefix||he;return e.logMetaData&&this.setLogMetaData(e.logMetaData),this.logMetaData||console.info("*********Missing required option: WebSocketManager:logMetaData**********"),new Ce(this,ye({prefix:t,logMetaData:this.logMetaData},e))}},{key:"setLogMetaData",value:function(e){this.logMetaData=e}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||Se.INFO,this._advancedLogWriter="warn",t.advancedLogWriter&&(this._advancedLogWriter=t.advancedLogWriter),t.customizedLogger&&"object"===r()(t.customizedLogger)&&(this.useClientLogger=!0),this._clientLogger=t.logger||this.selectLogger(t),this._logsDestination=a,t.debug&&(this._logsDestination=s),t.logger&&(this._logsDestination=c)}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"===r()(e.customizedLogger)?e.customizedLogger:e.useDefaultLogger?Oe():null}}]),e}(),we=function(){function e(){pe()(this,e)}return ge()(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}},{key:"advancedLog",value:function(){}}]),e}(),Ce=function(e){re()(n,e);var t=be(n);function n(e,o){var r;return pe()(this,n),(r=t.call(this)).options=o||{},r.prefix=o.prefix||he,r.logManager=e,r}return ge()(n,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this._log(Se.DEBUG,t)}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this._log(Se.INFO,t)}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this._log(Se.WARN,t)}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this._log(Se.ERROR,t)}},{key:"advancedLog",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this._log(Se.ADVANCED_LOG,t)}},{key:"_shouldLog",value:function(e){return this.logManager.hasClientLogger()&&this.logManager.isLevelEnabled(e)}},{key:"_writeToClientLogger",value:function(e,t){return this.logManager.writeToClientLogger(e,t)}},{key:"_log",value:function(e,t){if(this._shouldLog(e)){var n=this.logManager.useClientLogger?t:this._convertToSingleStatement(t);return this._writeToClientLogger(e,n)}}},{key:"_convertToSingleStatement",value:function(e){var t=new Date(Date.now()).toISOString(),n="[".concat(t,"]");this.prefix&&(n+=this.prefix+" "),this.options&&(this.options.prefix?n+=" "+this.options.prefix+":":n+="");for(var o=0;o<e.length;o++){var r=e[o];n+=this._convertToString(r)+" "}return n}},{key:"_convertToString",value:function(e){try{if(!e)return"";if(ne.isString(e))return e;if(ne.isObject(e)&&ne.isFunction(e.toString)){var t=e.toString();if("[object Object]"!==t)return t}return JSON.stringify(e)}catch(t){return console.error("Error while converting argument to string",e,t),""}}}]),n}(we);var Oe=function(){var e=new we;return e.debug=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.debug.apply(window.console,[].concat(t))},e.info=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.info.apply(window.console,[].concat(t))},e.warn=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.warn.apply(window.console,[].concat(t))},e.error=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return console.error.apply(window.console,[].concat(t))},e},Le=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2e3;pe()(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}return ge()(e,[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout((function(){e._execute()}),this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}},{key:"getIsConnected",value:function(){return!this.numAttempts}}]),e}(),Te=null,_e=function(){var e=!1,t=Te.getLogger({prefix:u}),n=ne.isNetworkOnline(),o={primary:null,secondary:null},r={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},i={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},a={pendingResponse:!1,intervalHandle:null},c={pendingResponse:!1,intervalHandle:null},s={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set,deepHeartbeatSuccess:new Set,deepHeartbeatFailure:new Set,topicFailure:new Set},Y={connConfig:null,promiseHandle:null,promiseCompleted:!0},ee={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},te={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},oe=new Le((function(){Ie()})),re=new Set([V,X,$,K]),ie=setInterval((function(){if(n!==ne.isNetworkOnline()){if(!(n=ne.isNetworkOnline()))return t.advancedLog(l),void Fe(t.info(l));var e=pe();n&&(!e||ue(e,WebSocket.CLOSING)||ue(e,WebSocket.CLOSED))&&(t.advancedLog(d),Fe(t.info(d)),Ie())}}),250),ae=function(e,n){e.forEach((function(e){try{e(n)}catch(e){Fe(t.error("Error executing callback",e))}}))},ce=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},se=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";Fe(t.debug("["+e+"] Primary WebSocket: "+ce(o.primary)+" | Secondary WebSocket: "+ce(o.secondary)))},ue=function(e,t){return e&&e.readyState===t},le=function(e){return ue(e,WebSocket.OPEN)},de=function(e){return null===e||void 0===e.readyState||ue(e,WebSocket.CLOSED)},pe=function(){return null!==o.secondary?o.secondary:o.primary},fe=function(){return le(pe())},ge=function(){if(e&&c.pendingResponse&&(t.advancedLog(g),Fe(t.warn(g)),ae(s.deepHeartbeatFailure,{timestamp:Date.now(),error:"aws/ping response is not received"}),clearInterval(c.intervalHandle),c.pendingResponse=!1),a.pendingResponse)return t.advancedLog(f),Fe(t.warn(f)),clearInterval(a.intervalHandle),a.pendingResponse=!1,void Ie();fe()?(e&&(Fe(t.debug(m)),pe().send(xe(K)),c.pendingResponse=!0),Fe(t.debug(y)),pe().send(xe($)),a.pendingResponse=!0):(e&&(t.advancedLog(S),Fe(t.warn(S)),ae(s.deepHeartbeatFailure,{timestamp:Date.now(),error:"Unable to send message to aws/ping because websocket connection is not established."})),t.advancedLog(h),Fe(t.warn(h)),se("sendHeartBeat"),Ie())},be=function(){t.advancedLog(z),r.exponentialBackOffTime=1e3,a.pendingResponse=!1,c.pendingResponse=!1,r.reconnectWebSocket=!0,clearTimeout(r.lifeTimeTimeoutHandle),clearInterval(a.intervalHandle),clearInterval(c.intervalHandle),clearTimeout(r.exponentialTimeoutHandle),clearTimeout(r.webSocketInitCheckerTimeoutId)},ve=function(){te.consecutiveFailedSubscribeAttempts=0,te.consecutiveNoResponseRequest=0,clearInterval(te.responseCheckIntervalId),clearInterval(te.reSubscribeIntervalId)},ye=function(){i.connectWebSocketRetryCount=0,i.connectionAttemptStartTime=null,i.noOpenConnectionsTimestamp=null},me=function(){oe.connected();try{t.advancedLog(O),Fe(t.info(O)),se("webSocketOnOpen"),null!==r.connState&&r.connState!==Q||ae(s.connectionGain),r.connState=Z;var e=Date.now();ae(s.connectionOpen,{connectWebSocketRetryCount:i.connectWebSocketRetryCount,connectionAttemptStartTime:i.connectionAttemptStartTime,noOpenConnectionsTimestamp:i.noOpenConnectionsTimestamp,connectionEstablishedTime:e,timeToConnect:e-i.connectionAttemptStartTime,timeWithoutConnection:i.noOpenConnectionsTimestamp?e-i.noOpenConnectionsTimestamp:null}),ye(),be(),pe().openTimestamp=Date.now(),0===ee.subscribed.size&&le(o.secondary)&&we(o.primary,"[Primary WebSocket] Closing WebSocket"),(ee.subscribed.size>0||ee.pending.size>0)&&(le(o.secondary)&&Fe(t.info("Subscribing secondary websocket to topics of primary websocket")),ee.subscribed.forEach((function(e){ee.subscriptionHistory.add(e),ee.pending.add(e)})),ee.subscribed.clear(),ke()),ge(),a.intervalHandle=setInterval(ge,1e4);var n=1e3*Y.connConfig.webSocketTransport.transportLifeTimeInSeconds;Fe(t.debug("Scheduling WebSocket manager reconnection, after delay "+n+" ms")),r.lifeTimeTimeoutHandle=setTimeout((function(){Fe(t.debug("Starting scheduled WebSocket manager reconnection")),Ie()}),n)}catch(e){Fe(t.error("Error after establishing WebSocket connection",e))}},he=function(e){se("webSocketOnError"),t.advancedLog(T,JSON.stringify(e)),Fe(t.error(T,JSON.stringify(e))),oe.getIsConnected()?Ie():oe.retry()},Se=function(e){var n=JSON.parse(e.data);switch(n.topic){case V:if(Fe(t.debug("Subscription Message received from webSocket server",e.data)),te.requestCompleted=!0,te.consecutiveNoResponseRequest=0,"success"===n.content.status)te.consecutiveFailedSubscribeAttempts=0,n.content.topics.forEach((function(e){ee.subscriptionHistory.delete(e),ee.pending.delete(e),ee.subscribed.add(e)})),0===ee.subscriptionHistory.size?le(o.secondary)&&(Fe(t.info("Successfully subscribed secondary websocket to all topics of primary websocket")),we(o.primary,"[Primary WebSocket] Closing WebSocket")):ke(),ae(s.subscriptionUpdate,n);else{if(clearInterval(te.reSubscribeIntervalId),++te.consecutiveFailedSubscribeAttempts,5===te.consecutiveFailedSubscribeAttempts)return ae(s.subscriptionFailure,n),void(te.consecutiveFailedSubscribeAttempts=0);te.reSubscribeIntervalId=setInterval((function(){ke()}),500)}break;case $:Fe(t.debug(b)),a.pendingResponse=!1;break;case K:Fe(t.debug(v)),c.pendingResponse=!1,200===n.statusCode?ae(s.deepHeartbeatSuccess,{timestamp:Date.now()}):ae(s.deepHeartbeatFailure,{timestamp:Date.now(),statusCode:n.statusCode,statusContent:n.statusContent});break;default:if(n.topic){if(t.advancedLog(U,n.topic),Fe(t.debug(U+n.topic)),le(o.primary)&&le(o.secondary)&&0===ee.subscriptionHistory.size&&this===o.primary)return void Fe(t.warn("Ignoring Message for Topic "+n.topic+", to avoid duplicates"));if(0===s.allMessage.size&&0===s.topic.size)return void Fe(t.warn("No registered callback listener for Topic",n.topic));t.advancedLog(B,n.topic),ae(s.allMessage,n),s.topic.has(n.topic)&&ae(s.topic.get(n.topic),n)}else n.message?(t.advancedLog(q,n),Fe(t.warn(q,n)),ae(s.topicFailure,{timestamp:Date.now(),errorMessage:n.message,connectionId:n.connectionId,requestId:n.requestId})):(t.advancedLog(J,n),Fe(t.warn(J,n)))}},ke=function e(){if(te.consecutiveNoResponseRequest>3)return Fe(t.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void ae(s.subscriptionFailure,ne.getSubscriptionResponse(V,!1,Array.from(ee.pending)));fe()?0!==Array.from(ee.pending).length&&(clearInterval(te.responseCheckIntervalId),pe().send(xe(V,{topics:Array.from(ee.pending)})),te.requestCompleted=!1,te.responseCheckIntervalId=setInterval((function(){te.requestCompleted||(++te.consecutiveNoResponseRequest,e())}),1e3)):Fe(t.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},we=function(e,n){ue(e,WebSocket.CONNECTING)||ue(e,WebSocket.OPEN)?e.close(1e3,n):Fe(t.warn("Ignoring WebSocket Close request, WebSocket State: "+ce(e)))},Ce=function(e){we(o.primary,"[Primary] WebSocket "+e),we(o.secondary,"[Secondary] WebSocket "+e)},Oe=function(){i.connectWebSocketRetryCount++;var e=ne.addJitter(r.exponentialBackOffTime,.3);Date.now()+e<=Y.connConfig.urlConnValidTime?(t.advancedLog(_),Fe(t.debug(_+e+" ms")),r.exponentialTimeoutHandle=setTimeout((function(){return Ne()}),e),r.exponentialBackOffTime*=2):(t.advancedLog(x),Fe(t.warn(x)),Ie())},_e=function(e){be(),ve(),t.advancedLog(W,e),Fe(t.error(W)),r.websocketInitFailed=!0,Ce(I),clearInterval(ie),ae(s.initFailure,{connectWebSocketRetryCount:i.connectWebSocketRetryCount,connectionAttemptStartTime:i.connectionAttemptStartTime,reason:e}),ye()},xe=function(e,t){return JSON.stringify({topic:e,content:t})},We=function(e){return!!(ne.isObject(e)&&ne.isObject(e.webSocketTransport)&&ne.isNonEmptyString(e.webSocketTransport.url)&&ne.validWSUrl(e.webSocketTransport.url)&&1e3*e.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(Fe(t.error("Invalid WebSocket Connection Configuration",e)),!1)},Ie=function(){if(!ne.isNetworkOnline())return t.advancedLog(p),void Fe(t.info(p));if(r.websocketInitFailed)Fe(t.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(Y.promiseCompleted)return be(),t.advancedLog(N),Fe(t.info(N)),i.connectionAttemptStartTime=i.connectionAttemptStartTime||Date.now(),Y.promiseCompleted=!1,Y.promiseHandle=s.getWebSocketTransport(),Y.promiseHandle.then((function(e){return Y.promiseCompleted=!0,t.advancedLog(M),Fe(t.debug(M,e)),We(e)?(Y.connConfig=e,Y.connConfig.urlConnValidTime=Date.now()+85e3,Ne()):(_e("Invalid WebSocket connection configuration: "+e),{webSocketConnectionFailed:!0})}),(function(e){return Y.promiseCompleted=!0,t.advancedLog(F),Fe(t.error(F,e)),ne.isNetworkFailure(e)?(t.advancedLog(E+JSON.stringify(e)),Fe(t.info(E+JSON.stringify(e))),oe.retry()):_e("Failed to fetch webSocket connection configuration: "+JSON.stringify(e)),{webSocketConnectionFailed:!0}}));Fe(t.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}},Ne=function(){if(r.websocketInitFailed)return Fe(t.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!ne.isNetworkOnline())return Fe(t.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};t.advancedLog(D),Fe(t.info(D)),se("initWebSocket");try{if(We(Y.connConfig)){var e=null;return le(o.primary)?(Fe(t.debug("Primary Socket connection is already open")),ue(o.secondary,WebSocket.CONNECTING)||(Fe(t.debug("Establishing a secondary web-socket connection")),oe.numAttempts=0,o.secondary=Me()),e=o.secondary):(ue(o.primary,WebSocket.CONNECTING)||(Fe(t.debug("Establishing a primary web-socket connection")),o.primary=Me()),e=o.primary),r.webSocketInitCheckerTimeoutId=setTimeout((function(){le(e)||Oe()}),1e3),{webSocketConnectionFailed:!1}}}catch(e){return Fe(t.error("Error Initializing web-socket-manager",e)),_e("Failed to initialize new WebSocket: "+e.message),{webSocketConnectionFailed:!0}}},Me=function(){var e=new WebSocket(Y.connConfig.webSocketTransport.url);return e.addEventListener("open",me),e.addEventListener("message",Se),e.addEventListener("error",he),e.addEventListener("close",(function(n){return function(e,n){t.advancedLog(L,JSON.stringify(e)),Fe(t.info(L,JSON.stringify(e))),se("webSocketOnClose before-cleanup"),ae(s.connectionClose,{openTimestamp:n.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-n.openTimestamp,code:e.code,reason:e.reason}),de(o.primary)&&(o.primary=null),de(o.secondary)&&(o.secondary=null),r.reconnectWebSocket&&(le(o.primary)||le(o.secondary)?de(o.primary)&&le(o.secondary)&&(Fe(t.info("[Primary] WebSocket Cleanly Closed")),o.primary=o.secondary,o.secondary=null):(Fe(t.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),r.connState===Q?Fe(t.info("Ignoring connectionLost callback invocation")):(ae(s.connectionLost,{openTimestamp:n.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-n.openTimestamp,code:e.code,reason:e.reason}),i.noOpenConnectionsTimestamp=Date.now()),r.connState=Q,Ie()),se("webSocketOnClose after-cleanup"))}(n,e)})),e},Fe=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(e){if(ne.assertTrue(ne.isFunction(e),"transportHandle must be a function"),null===s.getWebSocketTransport)return s.getWebSocketTransport=e,Ie();Fe(t.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return t.advancedLog(R),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.initFailure.add(e),r.websocketInitFailed&&e(),function(){return s.initFailure.delete(e)}},this.onConnectionOpen=function(e){return t.advancedLog(A),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.connectionOpen.add(e),function(){return s.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return t.advancedLog(j),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.connectionClose.add(e),function(){return s.connectionClose.delete(e)}},this.onConnectionGain=function(e){return t.advancedLog(H),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.connectionGain.add(e),fe()&&e(),function(){return s.connectionGain.delete(e)}},this.onConnectionLost=function(e){return t.advancedLog(P),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.connectionLost.add(e),r.connState===Q&&e(),function(){return s.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.subscriptionUpdate.add(e),function(){return s.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return t.advancedLog(G),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.subscriptionFailure.add(e),function(){return s.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return ne.assertNotNull(e,"topicName"),ne.assertTrue(ne.isFunction(t),"cb must be a function"),s.topic.has(e)?s.topic.get(e).add(t):s.topic.set(e,new Set([t])),function(){return s.topic.get(e).delete(t)}},this.onAllMessage=function(e){return ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.allMessage.add(e),function(){return s.allMessage.delete(e)}},this.subscribeTopics=function(e){ne.assertNotNull(e,"topics"),ne.assertIsList(e),e.forEach((function(e){ee.subscribed.has(e)||ee.pending.add(e)})),te.consecutiveNoResponseRequest=0,ke()},this.sendMessage=function(e){if(ne.assertIsObject(e,"payload"),void 0===e.topic||re.has(e.topic))Fe(t.warn("Cannot send message, Invalid topic",e));else{try{e=JSON.stringify(e)}catch(n){return void Fe(t.warn("Error stringify message",e))}fe()?pe().send(e):Fe(t.warn("Cannot send message, web socket connection is not open"))}},this.deepHeartbeatHandler=function(){e=!0},this.onDeepHeartbeatSuccess=function(e){return t.advancedLog(k),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.deepHeartbeatSuccess.add(e),function(){return s.deepHeartbeatSuccess.delete(e)}},this.onDeepHeartbeatFailure=function(e){return t.advancedLog(w),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.deepHeartbeatFailure.add(e),function(){return s.deepHeartbeatFailure.delete(e)}},this.onTopicFailure=function(e){return t.advancedLog(C),ne.assertTrue(ne.isFunction(e),"cb must be a function"),s.topicFailure.add(e),function(){return s.topicFailure.delete(e)}},this.closeWebSocket=function(){be(),ve(),r.reconnectWebSocket=!1,clearInterval(ie),Ce("User request to close WebSocket")},this.terminateWebSocketManager=_e},xe={create:function(e){return Te||(Te=new ke(e)),Te.hasLogMetaData()||Te.setLogMetaData(e),e||console.info("********Missing metaData for logs from websocketManager: initialize websocketManager using create(metaData)*******"),new _e},setGlobalConfig:function(e){var t=e&&e.loggerConfig;Te||(Te=new ke),Te.updateLoggerConfig(t)},LogLevel:Se,Logger:me};global.connect=global.connect||{},connect.WebSocketManager=xe;var We=xe;t.default=We}]); |