=t||n<0||m&&e-u>=o}function v(){var e=p();if(y(e))return k(e);l=setTimeout(v,function(e){var n=t-(e-c);return m?h(n,o-(e-u)):n}(e))}function k(e){return l=void 0,F&&r?b(e):(r=a=void 0,s)}function E(){var e=p(),n=y(e);if(r=arguments,a=this,c=e,n){if(void 0===l)return function(e){return u=e,l=setTimeout(v,t),f?b(e):s}(c);if(m)return l=setTimeout(v,t),b(c)}return void 0===l&&(l=setTimeout(v,t)),s}return t=_(t)||0,g(i)&&(f=!!i.leading,o=(m="maxWait"in i)?d(_(i.maxWait)||0,t):o,F="trailing"in i?!!i.trailing:F),E.cancel=function(){void 0!==l&&clearTimeout(l),u=0,r=c=a=l=void 0},E.flush=function(){return void 0===l?s:k(p())},E}(e,t,{leading:r,maxWait:t,trailing:a})}},604:function(e,t,n){var i;!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 a(e){return function(e,t){var n,i,o,s,l,c,u,f,d,h=1,p=e.length,g="";for(i=0;i=0),s.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,s.width?parseInt(s.width):0);break;case"e":n=s.precision?parseFloat(n).toExponential(s.precision):parseFloat(n).toExponential();break;case"f":n=s.precision?parseFloat(n).toFixed(s.precision):parseFloat(n);break;case"g":n=s.precision?String(Number(n.toPrecision(s.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=s.precision?n.substring(0,s.precision):n;break;case"t":n=String(!!n),n=s.precision?n.substring(0,s.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=s.precision?n.substring(0,s.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=s.precision?n.substring(0,s.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(s.type)?g+=n:(!r.number.test(s.type)||f&&!s.sign?d="":(d=f?"+":"-",n=n.toString().replace(r.sign,"")),c=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",u=s.width-(d+n).length,l=s.width&&u>0?c.repeat(u):"",g+=s.align?d+n+l:"0"===c?d+l+n:l+d+n)}return g}(function(e){if(s[e])return s[e];for(var t,n=e,i=[],a=0;n;){if(null!==(t=r.text.exec(n)))i.push(t[0]);else if(null!==(t=r.modulo.exec(n)))i.push("%");else{if(null===(t=r.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){a|=1;var o=[],l=t[2],c=[];if(null===(c=r.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(o.push(c[1]);""!==(l=l.substring(c[0].length));)if(null!==(c=r.key_access.exec(l)))o.push(c[1]);else{if(null===(c=r.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");o.push(c[1])}t[2]=o}else a|=2;if(3===a)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.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]=i}(e),arguments)}function o(e,t){return a.apply(null,[e].concat(t||[]))}var s=Object.create(null);t.sprintf=a,t.vsprintf=o,"undefined"!=typeof window&&(window.sprintf=a,window.vsprintf=o,void 0===(i=function(){return{sprintf:a,vsprintf:o}}.call(t,n,t,e))||(e.exports=i))}()}},_={};function F(e){var t=_[e];if(void 0!==t)return t.exports;var i=_[e]={exports:{}};return n[e](i,i.exports,F),i.exports}F.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return F.d(t,{a:t}),t},F.d=function(e,t){for(var n in t)F.o(t,n)&&!F.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},F.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(e){"use strict";var t=function(e){function t(e){var n;return h(this,t),(n=s(this,l(t).call(this,e))).name="ValueError",n}return c(t,e),t}(u(Error)),n=function(e){function t(e){var n;return h(this,t),(n=s(this,l(t).call(this,e))).name="UnImplementedMethod",n}return c(t,e),t}(u(Error)),a=function(e){function t(e,n){var i;return h(this,t),(i=s(this,l(t).call(this,e))).name="IllegalArgument",i.argument=n,i}return c(t,e),t}(u(Error));Error,Error;var o=F(639),g="MESSAGE_RECEIPTS_ENABLED",_={AGENT:"AGENT",CUSTOMER:"CUSTOMER"},b="API",y={SEND_MESSAGE:"SendMessage",SEND_ATTACHMENT:"SendAttachment",DOWNLOAD_ATTACHMENT:"DownloadAttachment",SEND_EVENT:"SendEvent",GET_TRANSCRIPT:"GetTranscript",DISCONNECT_PARTICIPANT:"DisconnectParticipant",CREATE_PARTICIPANT_CONNECTION:"CreateParticipantConnection",DESCRIBE_VIEW:"DescribeView"},v="InitWebsocket",k={INCOMING_MESSAGE:"INCOMING_MESSAGE",INCOMING_TYPING:"INCOMING_TYPING",INCOMING_READ_RECEIPT:"INCOMING_READ_RECEIPT",INCOMING_DELIVERED_RECEIPT:"INCOMING_DELIVERED_RECEIPT",CONNECTION_ESTABLISHED:"CONNECTION_ESTABLISHED",CONNECTION_LOST:"CONNECTION_LOST",CONNECTION_BROKEN:"CONNECTION_BROKEN",CONNECTION_ACK:"CONNECTION_ACK",CHAT_ENDED:"CHAT_ENDED",MESSAGE_METADATA:"MESSAGEMETADATA",PARTICIPANT_IDLE:"PARTICIPANT_IDLE",PARTICIPANT_RETURNED:"PARTICIPANT_RETURNED",PARTICIPANT_INVITED:"PARTICIPANT_INVITED",AUTODISCONNECTION:"AUTODISCONNECTION",DEEP_HEARTBEAT_SUCCESS:"DEEP_HEARTBEAT_SUCCESS",DEEP_HEARTBEAT_FAILURE:"DEEP_HEARTBEAT_FAILURE",AUTHENTICATION_INITIATED:"AUTHENTICATION_INITIATED",AUTHENTICATION_SUCCESSFUL:"AUTHENTICATION_SUCCESSFUL",AUTHENTICATION_FAILED:"AUTHENTICATION_FAILED",AUTHENTICATION_TIMEOUT:"AUTHENTICATION_TIMEOUT",AUTHENTICATION_EXPIRED:"AUTHENTICATION_EXPIRED",AUTHENTICATION_CANCELED:"AUTHENTICATION_CANCELED",PARTICIPANT_DISPLAY_NAME_UPDATED:"PARTICIPANT_DISPLAY_NAME_UPDATED",CHAT_REHYDRATED:"CHAT_REHYDRATED"},E={textPlain:"text/plain",textMarkdown:"text/markdown",textCsv:"text/csv",applicationDoc:"application/msword",applicationDocx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",applicationJson:"application/json",applicationPdf:"application/pdf",applicationPpt:"application/vnd.ms-powerpoint",applicationPptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",applicationXls:"application/vnd.ms-excel",applicationXlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",authenticationInitiated:"application/vnd.amazonaws.connect.event.authentication.initiated",authenticationSuccessful:"application/vnd.amazonaws.connect.event.authentication.succeeded",authenticationFailed:"application/vnd.amazonaws.connect.event.authentication.failed",authenticationTimeout:"application/vnd.amazonaws.connect.event.authentication.timeout",authenticationExpired:"application/vnd.amazonaws.connect.event.authentication.expired",authenticationCanceled:"application/vnd.amazonaws.connect.event.authentication.cancelled",participantDisplayNameUpdated:"application/vnd.amazonaws.connect.event.participant.displayname.updated",imageJpg:"image/jpeg",imagePng:"image/png",audioWav:"audio/wav",audioXWav:"audio/x-wav",audioVndWave:"audio/vnd.wave",connectionAcknowledged:"application/vnd.amazonaws.connect.event.connection.acknowledged",typing:"application/vnd.amazonaws.connect.event.typing",participantJoined:"application/vnd.amazonaws.connect.event.participant.joined",participantLeft:"application/vnd.amazonaws.connect.event.participant.left",participantActive:"application/vnd.amazonaws.connect.event.participant.active",participantInactive:"application/vnd.amazonaws.connect.event.participant.inactive",transferSucceeded:"application/vnd.amazonaws.connect.event.transfer.succeeded",transferFailed:"application/vnd.amazonaws.connect.event.transfer.failed",chatEnded:"application/vnd.amazonaws.connect.event.chat.ended",interactiveMessage:"application/vnd.amazonaws.connect.message.interactive",interactiveMessageResponse:"application/vnd.amazonaws.connect.message.interactive.response",readReceipt:"application/vnd.amazonaws.connect.event.message.read",deliveredReceipt:"application/vnd.amazonaws.connect.event.message.delivered",participantIdle:"application/vnd.amazonaws.connect.event.participant.idle",participantReturned:"application/vnd.amazonaws.connect.event.participant.returned",participantInvited:"application/vnd.amazonaws.connect.event.participant.invited",autoDisconnection:"application/vnd.amazonaws.connect.event.participant.autodisconnection",chatRehydrated:"application/vnd.amazonaws.connect.event.chat.rehydrated"},w=(f(f(f(f(f(f(f(f(f(f(e={},E.typing,k.INCOMING_TYPING),E.readReceipt,k.INCOMING_READ_RECEIPT),E.deliveredReceipt,k.INCOMING_DELIVERED_RECEIPT),E.participantIdle,k.PARTICIPANT_IDLE),E.authenticationInitiated,k.AUTHENTICATION_INITIATED),E.authenticationSuccessful,k.AUTHENTICATION_SUCCESSFUL),E.authenticationFailed,k.AUTHENTICATION_FAILED),E.authenticationTimeout,k.AUTHENTICATION_TIMEOUT),E.authenticationExpired,k.AUTHENTICATION_EXPIRED),E.authenticationCanceled,k.AUTHENTICATION_CANCELED),f(f(f(f(f(f(e,E.participantDisplayNameUpdated,k.PARTICIPANT_DISPLAY_NAME_UPDATED),E.participantReturned,k.PARTICIPANT_RETURNED),E.participantInvited,k.PARTICIPANT_INVITED),E.autoDisconnection,k.AUTODISCONNECTION),E.chatRehydrated,k.CHAT_REHYDRATED),"default",k.INCOMING_MESSAGE)),C=3540,T=F(604),x={assertTrue:function(e,n){if(!e)throw new t(n)},assertNotNull:function(e,t){return x.assertTrue(null!=e,(0,T.sprintf)("%s must be provided",t||"A value")),e},now:function(){return(new Date).getTime()},isString:function(e){return"string"==typeof e},randomId:function(){return(0,T.sprintf)("%s-%s",x.now(),Math.random().toString(36).slice(2))},assertIsNonEmptyString:function(e,t){if(!e||"string"!=typeof e)throw new a(t+" is not a non-empty string!")},assertIsList:function(e,t){if(!Array.isArray(e))throw new a(t+" is not an array")},assertIsEnum:function(e,t,n){var i;for(i=0;i3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,a=new Date;return t(i)?e(i).catch((function(r){var o=Math.max(0,n-(new Date).valueOf()+a.valueOf());return x.delay(o).then((function(){return x.asyncWhileInterval(e,t,n,i+1,r)}))})):Promise.reject(r||new Error("async while aborted"))},isAttachmentContentType:function(e){return e===E.applicationPdf||e===E.imageJpg||e===E.imagePng||e===E.applicationDoc||e===E.applicationXls||e===E.applicationPpt||e===E.textCsv||e===E.audioWav}},D=x,S={DEBUG:10,INFO:20,WARN:30,ERROR:40,ADVANCED_LOG:50},A=new(function(){function e(){h(this,e),this.updateLoggerConfig()}return p(e,[{key:"writeToClientLogger",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.hasClientLogger()){var i="string"==typeof t?t:JSON.stringify(t,M()),r="string"==typeof n?n:JSON.stringify(n,M()),a="".concat(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)," ").concat(i," ").concat(r);switch(e){case S.DEBUG:return this._clientLogger.debug(a)||a;case S.INFO:return this._clientLogger.info(a)||a;case S.WARN:return this._clientLogger.warn(a)||a;case S.ERROR:return this._clientLogger.error(a)||a;case S.ADVANCED_LOG:return this._advancedLogWriter&&this._clientLogger[this._advancedLogWriter](a)||a}}}},{key:"isLevelEnabled",value:function(e){return e>=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(){return new I(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||S.INFO,this._advancedLogWriter="warn",function(e,t){var n=t&&Object.keys(t);if(n&&-1===n.indexOf(e))return console.error("customizedLogger: incorrect value for loggerConfig:advancedLogWriter; use valid values from list ".concat(n," but used ").concat(e)),!1;var i=["warn","info","debug","log"];return!e||-1!==i.indexOf(e)||(console.error("incorrect value for loggerConfig:advancedLogWriter; use valid values from list ".concat(i," but used ").concat(e)),!1)}(t.advancedLogWriter,t.customizedLogger)&&(this._advancedLogWriter=t.advancedLogWriter),(t.customizedLogger&&"object"==typeof t.customizedLogger||t.logger&&"object"==typeof t.logger)&&(this.useClientLogger=!0),this._clientLogger=this.selectLogger(t)}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"==typeof e.customizedLogger?e.customizedLogger:e.logger&&"object"==typeof e.logger?e.logger:e.useDefaultLogger?P():null}}]),e}()),O=function(){function e(){h(this,e)}return p(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),I=function(e){function t(e){var n;return h(this,t),(n=s(this,l(t).call(this))).options=e||{},n}return c(t,e),p(t,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:432e5;if(!(arguments.length>0&&void 0!==arguments[0]&&arguments[0]))return this.connectionDetailsProvider.fetchConnectionDetails().then((function(n){return e.logger.info("Connection token polling succeeded."),t=e.getTimeToConnectionTokenExpiry(),e.timeout=setTimeout(e.startConnectionTokenPolling.bind(e),t),n})).catch((function(n){return e.logger.error("An error occurred when attempting to fetch the connection token during Connection Token Polling",n),e.timeout=setTimeout(e.startConnectionTokenPolling.bind(e),t),n}));this.logger.info("First time polling connection token."),this.timeout=setTimeout(this.startConnectionTokenPolling.bind(this),t)}},{key:"start",value:function(){return this.isStarted?this.getConnectionToken():(this.isStarted=!0,this.startConnectionTokenPolling(!0,this.getTimeToConnectionTokenExpiry()))}},{key:"end",value:function(){clearTimeout(this.timeout)}},{key:"getConnectionToken",value:function(){return this.connectionDetailsProvider.getFetchedConnectionToken()}},{key:"getConnectionTokenExpiry",value:function(){return this.connectionDetailsProvider.getConnectionTokenExpiry()}},{key:"getTimeToConnectionTokenExpiry",value:function(){return new Date(this.getConnectionTokenExpiry()).getTime()-(new Date).getTime()-6e4}}]),e}(),ae="<>",oe=function(e,t,n){this.subMap=e,this.id=D.randomId(),this.eventName=t,this.f=n};oe.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var se=function(){this.subIdMap={},this.subEventNameMap={}};se.prototype.subscribe=function(e,t){var n=new oe(this,e,t);this.subIdMap[n.id]=n;var i=this.subEventNameMap[e]||[];return i.push(n),this.subEventNameMap[e]=i,function(){return n.unsubscribe()}},se.prototype.unsubscribe=function(e,t){D.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==t})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),D.contains(this.subIdMap,t)&&delete this.subIdMap[t]},se.prototype.getAllSubscriptions=function(){return D.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},se.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var le=function(e){var t=e||{};this.subMap=new se,this.logEvents=t.logEvents||!1};le.prototype.subscribe=function(e,t){return D.assertNotNull(e,"eventName"),D.assertNotNull(t,"f"),D.assertTrue(D.isFunction(t),"f must be a function"),this.subMap.subscribe(e,t)},le.prototype.subscribeAll=function(e){return D.assertNotNull(e,"f"),D.assertTrue(D.isFunction(e),"f must be a function"),this.subMap.subscribe(ae,e)},le.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},le.prototype.trigger=function(e,t){D.assertNotNull(e,"eventName");var n=this,i=this.subMap.getSubscriptions(ae),r=this.subMap.getSubscriptions(e);i.concat(r).forEach((function(i){try{i.f(t||null,e,n)}catch(e){}}))},le.prototype.triggerAsync=function(e,t){var n=this;setTimeout((function(){return n.trigger(e,t)}),0)},le.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},le.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))};var ce="Category",ue=new(function(){function e(){h(this,e),this.widgetType="CustomChatWidget",this.logger=A.getLogger({prefix:"ChatJS-csmService"}),this.csmInitialized=!1,this.metricsToBePublished=[],this.agentMetricToBePublished=[],this.MAX_RETRY=5}return p(e,[{key:"loadCsmScriptAndExecute",value:function(){try{var e=document.createElement("script");e.type="text/javascript",e.innerHTML="(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n csm.EVENT_TYPE = {\n LOG: 'LOG',\n METRIC: 'METRIC',\n CONFIG: 'CONFIG',\n WORKFLOW_EVENT: 'WORKFLOW_EVENT',\n CUSTOM: 'CUSTOM',\n CLOSE: 'CLOSE',\n SET_AUTH: 'SET_AUTH',\n SET_CONFIG: 'SET_CONFIG',\n };\n\n csm.UNIT = {\n COUNT: 'Count',\n SECONDS: 'Seconds',\n MILLISECONDS: 'Milliseconds',\n MICROSECONDS: 'Microseconds',\n };\n})();\n\n(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n const MAX_METRIC_DIMENSIONS = 10;\n\n /** ********* Dimension Classes ***********/\n\n const Dimension = function(name, value) {\n csm.Util.assertExist(name, 'name');\n csm.Util.assertExist(value, 'value');\n\n this.name = name;\n this.value = value == null ? 'null' : (value === '' ? ' ' : value.toString());\n };\n\n\n /** ********* Metric Classes ***********/\n\n const Metric = function(metricName, unit, value, dedupeOptions) {\n csm.Util.assertExist(metricName, 'metricName');\n csm.Util.assertExist(value, 'value');\n csm.Util.assertExist(unit, 'unit');\n csm.Util.assertTrue(csm.Util.isValidUnit(unit));\n if (dedupeOptions) {\n csm.Util.assertInObject(dedupeOptions, 'dedupeOptions', 'dedupeIntervalMs');\n }\n\n this.metricName = metricName;\n this.unit = unit;\n this.value = value;\n this.timestamp = new Date();\n this.dimensions = csm.globalDimensions ? csm.Util.deepCopy(csm.globalDimensions): [];\n this.namespace = csm.configuration.namespace;\n this.dedupeOptions = dedupeOptions; // optional. { dedupeIntervalMs: (int; required), context: (string; optional) }\n\n // Currently, CloudWatch can't aggregate metrics by a subset of dimensions.\n // To bypass this limitation, we introduce the optional dimensions concept to CSM.\n // The CSM metric publisher will publish a default metric without optional dimension\n // For each optional dimension, the CSM metric publisher publishes an extra metric with that dimension.\n this.optionalDimensions = csm.globalOptionalDimensions ? csm.Util.deepCopy(csm.globalOptionalDimensions): [];\n };\n\n Metric.prototype.addDimension = function(name, value) {\n this._addDimensionHelper(this.dimensions, name, value);\n };\n\n Metric.prototype.addOptionalDimension = function(name, value) {\n this._addDimensionHelper(this.optionalDimensions, name, value);\n };\n\n Metric.prototype._addDimensionHelper = function(targetDimensions, name, value) {\n // CloudWatch metric allows maximum 10 dimensions\n // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricData-property\n if ((this.dimensions.length + this.optionalDimensions.length) >= MAX_METRIC_DIMENSIONS) {\n throw new csm.ExceedDimensionLimitException(name);\n }\n\n const existing = targetDimensions.find(function(dimension) {\n return dimension.name === name;\n });\n\n if (existing) {\n existing.value = value == null ? 'null' : (value === '' ? ' ' : value.toString());\n } else {\n targetDimensions.push(new Dimension(name, value));\n }\n };\n\n\n /** ********* Telemetry Classes ***********/\n\n const WorkflowEvent = function(params) {\n this.timestamp = params.timestamp || new Date().getTime();\n this.workflowType = params.workflow.type;\n this.instanceId = params.workflow.instanceId;\n this.userId = params.userId;\n this.organizationId = params.organizationId;\n this.accountId = params.accountId;\n this.event = params.event;\n this.appName = params.appName;\n this.data = [];\n\n // Convert 'data' map into the KeyValuePairList structure expected by the Lambda API\n for (const key in params.data) {\n if (Object.prototype.hasOwnProperty.call(params.data, key)) {\n this.data.push({'key': key, 'value': params.data[key]});\n }\n }\n };\n\n /** ********* Exceptions ***********/\n\n const NullOrUndefinedException = function(paramName) {\n this.name = 'NullOrUndefinedException';\n this.message = paramName + ' is null or undefined. ';\n };\n NullOrUndefinedException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const AssertTrueException = function() {\n this.name = 'AssertTrueException';\n this.message = 'Assertion failed. ';\n };\n AssertTrueException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const ExceedDimensionLimitException = function(dimensionName) {\n this.name = 'ExceedDimensionLimitException';\n this.message = 'Could not add dimension \\'' + dimensionName + '\\'. Metric has maximum 10 dimensions. ';\n };\n ExceedDimensionLimitException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const InitializationException = function() {\n this.name = 'InitializationException';\n this.message = 'Initialization failed. ';\n };\n InitializationException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n\n csm.Dimension = Dimension;\n csm.Metric = Metric;\n csm.WorkflowEvent = WorkflowEvent;\n csm.NullOrUndefinedException = NullOrUndefinedException;\n csm.AssertTrueException = AssertTrueException;\n csm.InitializationException = InitializationException;\n csm.ExceedDimensionLimitException = ExceedDimensionLimitException;\n})();\n\n(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n const validTimeUnits = [csm.UNIT.SECONDS, csm.UNIT.MILLISECONDS, csm.UNIT.MICROSECONDS];\n const validUnits = validTimeUnits.concat(csm.UNIT.COUNT);\n\n const Util = {\n assertExist: function(value, paramName) {\n if (value === null || value === undefined) {\n throw new csm.NullOrUndefinedException(paramName);\n }\n },\n assertTrue: function(value) {\n if (!value) {\n throw new csm.AssertTrueException();\n }\n },\n assertInObject: function(obj, objName, key) {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n throw new csm.NullOrUndefinedException(objName);\n }\n if (key === null || key === undefined || !obj[key]) {\n throw new csm.NullOrUndefinedException(`${objName}[${key}]`);\n }\n },\n isValidUnit: function(unit) {\n return validUnits.includes(unit);\n },\n isValidTimeUnit: function(unit) {\n return validTimeUnits.includes(unit);\n },\n isEmpty: function(value) {\n if (value !== null && typeof val === 'object') {\n return Objects.keys(value).length === 0;\n }\n return !value;\n },\n deepCopy: function(obj) {\n // NOTE: this will fail if obj has a circular reference\n return JSON.parse(JSON.stringify(obj));\n },\n\n /**\n * This function is used before setting the page location for default metrics and logs,\n * and the APIs that set page location\n * Can be overridden by calling csm.API.setPageLocationTransformer(function(){})\n * @param {string} pathname path for page location\n * @return {string} pathname provided\n */\n pageLocationTransformer: function(pathname) {\n return pathname;\n },\n\n /**\n * As of now, our service public claims only support for Firefox and Chrome\n * Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent\n *\n * This function will only return firefox, chrome and others\n *\n * Best practice as indicated in MDN, \"Avoiding user agent detection\"\n */\n getBrowserDetails: function() {\n const userAgent = window.navigator.userAgent;\n const details = {};\n if (userAgent.includes('Firefox') && !userAgent.includes('Seamonkey')) {\n details.name = 'Firefox';\n details.version = getBrowserVersion('Firefox');\n } else if (userAgent.includes('Chrome') && !userAgent.includes('Chromium')) {\n details.name = 'Chrome';\n details.version = getBrowserVersion('Chrome');\n }\n },\n\n randomId: function() {\n return new Date().getTime() + '-' + Math.random().toString(36).slice(2);\n },\n\n getOrigin: function() {\n return document.location.origin;\n },\n\n getReferrerUrl: function() {\n const referrer = document.referrer || '';\n return this.getURLOrigin(referrer);\n },\n\n getWindowParent: function() {\n let parentLocation = '';\n try {\n parentLocation = window.parent.location.href;\n } catch (e) {\n parentLocation = '';\n }\n return parentLocation;\n },\n\n getURLOrigin: function(urlValue) {\n let origin = '';\n const originArray = urlValue.split( '/' );\n if (originArray.length >= 3) {\n const protocol = originArray[0];\n const host = originArray[2];\n origin = protocol + '//' + host;\n }\n return origin;\n },\n\n };\n\n const getBrowserVersion = function(browserName) {\n const userAgent = window.navigator.userAgent;\n const browserNameIndex = userAgent.indexOf(browserName);\n const nextSpaceIndex = userAgent.indexOf(' ', browserNameIndex);\n if (nextSpaceIndex === -1) {\n return userAgent.substring(browserNameIndex + browserName.length + 1, userAgent.length);\n } else {\n return userAgent.substring(browserNameIndex + browserName.length + 1, nextSpaceIndex);\n }\n };\n\n csm.Util = Util;\n})();\n\n(function() {\n const global = window;\n const csm = global.csm || {};\n global.csm = csm;\n\n csm.globalDimensions = []; // These dimensions are added to all captured metrics.\n csm.globalOptionalDimensions = [];\n csm.initFailureDimensions = [];\n\n const API = {\n getWorkflow: function(workflowType, instanceId, data) {\n return csm.workflow(workflowType, instanceId, data);\n },\n\n addMetric: function(metric) {\n csm.Util.assertExist(metric, 'metric');\n csm.putMetric(metric);\n },\n\n addMetricWithDedupe: function(metric, dedupeIntervalMs, context) {\n csm.Util.assertExist(metric, 'metric');\n csm.Util.assertExist(metric, 'dedupeIntervalMs');\n // context is optional; if present it will only dedupe on metrics with the same context. ex.) tabId\n metric.dedupeOptions = {dedupeIntervalMs, context: context || 'global'};\n csm.putMetric(metric);\n },\n\n addCount: function(metricName, count) {\n csm.Util.assertExist(metricName, 'metricName');\n csm.Util.assertExist(count, 'count');\n\n const metric = new csm.Metric(metricName, csm.UNIT.COUNT, count);\n csm.putMetric(metric);\n },\n\n addCountWithPageLocation: function(metricName) {\n csm.Util.assertExist(metricName, 'metricName');\n\n const metric = new csm.Metric(metricName, csm.UNIT.COUNT, 1.0);\n metric.addDimension('WindowLocation', csm.Util.pageLocationTransformer(window.location.pathname));\n csm.putMetric(metric);\n },\n\n addError: function(metricName, count) {\n csm.Util.assertExist(metricName, 'metricName');\n\n if (count === undefined || count == null) {\n count = 1.0;\n }\n const metric = new csm.Metric(metricName, csm.UNIT.COUNT, count);\n metric.addDimension('Metric', 'Error');\n csm.putMetric(metric);\n },\n\n addSuccess: function(metricName) {\n API.addError(metricName, 0);\n },\n\n addTime: function(metricName, time, unit) {\n csm.Util.assertExist(metricName, 'metricName');\n csm.Util.assertExist(time, 'time');\n\n let timeUnit = csm.UNIT.MILLISECONDS;\n if (unit && csm.Util.isValidTimeUnit(unit)) {\n timeUnit = unit;\n }\n const metric = new csm.Metric(metricName, timeUnit, time);\n metric.addDimension('Metric', 'Time');\n csm.putMetric(metric);\n },\n\n addTimeWithPageLocation: function(metricName, time, unit) {\n csm.Util.assertExist(metricName, 'metricName');\n csm.Util.assertExist(time, 'time');\n\n let timeUnit = csm.UNIT.MILLISECONDS;\n if (unit && csm.Util.isValidTimeUnit(unit)) {\n timeUnit = unit;\n }\n const metric = new csm.Metric(metricName, timeUnit, time);\n metric.addDimension('WindowLocation', csm.Util.pageLocationTransformer(window.location.pathname));\n csm.putMetric(metric);\n },\n\n pageReady: function() {\n if (window.performance && window.performance.now) {\n const pageLoadTime = window.performance.now();\n const metric = new csm.Metric('PageReadyLatency', csm.UNIT.MILLISECONDS, pageLoadTime);\n metric.addDimension('WindowLocation', csm.Util.pageLocationTransformer(window.location.pathname));\n csm.putMetric(metric);\n }\n },\n\n setPageLocationTransformer: function(transformFunc) {\n csm.Util.assertExist(transformFunc, 'transformFunc');\n csm.Util.assertTrue((typeof transformFunc) === 'function');\n csm.Util.pageLocationTransformer = transformFunc;\n },\n\n setGlobalDimensions: function(dimensions) {\n csm.Util.assertExist(dimensions, 'dimensions');\n csm.globalDimensions = dimensions;\n },\n\n setGlobalOptionalDimensions: function(dimensions) {\n csm.Util.assertExist(dimensions, 'dimensions');\n csm.globalOptionalDimensions = dimensions;\n },\n\n setInitFailureDimensions: function(dimensions) {\n csm.Util.assertExist(dimensions, 'dimensions');\n csm.initFailureDimensions = dimensions;\n },\n\n putCustom: function(endpoint, headers, data) {\n csm.Util.assertExist(data, 'data');\n csm.Util.assertExist(endpoint, 'endpoint');\n csm.Util.assertExist(headers, 'headers');\n csm.putCustom(endpoint, headers, data);\n },\n\n setAuthParams: function(authParams) {\n csm.setAuthParams(authParams);\n },\n\n setConfig: function(key, value) {\n csm.Util.assertExist(key, 'key');\n csm.Util.assertExist(value, 'value');\n if (!csm.configuration[key]) {\n csm.setConfig(key, value); // set configuration variables such as accountId, instanceId, userId\n }\n },\n };\n\n csm.API = API;\n})();\n\n(function() {\n const global = window;\n const csm = global.csm || {};\n global.csm = csm;\n\n const WORKFLOW_KEY_PREFIX = 'csm.workflow';\n\n /**\n * Calculates the local storage key used to store a workflow of the specified type.\n * @param {string} type of workflow\n * @return {string} storage key\n */\n const getWorkflowKeyForType = function(type) {\n return [\n WORKFLOW_KEY_PREFIX,\n type,\n ].join('.');\n };\n\n /**\n * Constructor for new Workflow objects.\n *\n * If you need to be able to share a workflow across tabs, it is recommended\n * to use \"csm.workflow\" to create/hydrate your workflows instead.\n * @param {string} type of workflow\n * @param {string} instanceId of workflow\n * @param {JSON} data blob associated with workflow\n */\n const Workflow = function(type, instanceId, data) {\n this.type = type;\n this.instanceId = instanceId || csm.Util.randomId();\n this.instanceSpecified = instanceId || false;\n this.eventMap = {};\n this.data = data || {};\n\n // Merge global dimensions into the data map.\n const dimensionData = {};\n csm.globalDimensions.forEach(function(dimension) {\n dimensionData[dimension.name] = dimension.value;\n });\n csm.globalOptionalDimensions.forEach(function(dimension) {\n dimensionData[dimension.name] = dimension.value;\n });\n this.data = this._mergeData(dimensionData);\n };\n\n /**\n * Create a new workflow or rehydrate an existing shared workflow.\n *\n * @param {string} type The type of workflow to be created.\n * @param {string} instanceId The instanceId of the workflow. If not provided, it will be\n * assigned a random ID and will not be automatically saved to local storage.\n * If provided, we will attempt to load an existing workflow of the same type\n * from local storage and rehydrate it.\n * @param {JSON} data An optional map of key/value pairs to be added as data to every\n * workflow event created with this workflow.\n * @return {Workflow} workflow event\n * NOTE: Only one workflow of each type can be stored at the same time, to avoid\n * overloading localStorage with unused workflow records.\n */\n csm.workflow = function(type, instanceId, data) {\n let workflow = new Workflow(type, instanceId, data);\n\n if (instanceId) {\n const savedWorkflow = csm._loadWorkflow(type);\n if (savedWorkflow && savedWorkflow.instanceId === instanceId) {\n workflow = savedWorkflow;\n workflow.addData(data || {});\n }\n }\n\n return workflow;\n };\n\n csm._loadWorkflow = function(type) {\n let workflow = null;\n const workflowJson = localStorage.getItem(getWorkflowKeyForType(type));\n const workflowStruct = workflowJson ? JSON.parse(workflowJson) : null;\n if (workflowStruct) {\n workflow = new Workflow(type, workflowStruct.instanceId);\n workflow.eventMap = workflowStruct.eventMap;\n }\n return workflow;\n };\n\n /**\n * Creates a new workflow event and returns it. Then this workflow event is sent upstream\n * to the CSMSharedWorker where it is provided to the backend.\n *\n * If an instanceId was specified when the workflow was created, this will also save the workflow\n * and all of its events to localStorage.\n *\n * @param {string} event The name of the event that occurred.\n * @param {JSON} data An optional free-form key attribute pair of metadata items that will be stored\n * and reported backstream with the workflow event.\n * @return {WorkflowEvent} workflowEvent\n */\n Workflow.prototype.event = function(event, data) {\n const mergedData = this._mergeData(data || {});\n const workflowEvent = new csm.WorkflowEvent({\n workflow: this,\n event: event,\n data: mergedData,\n userId: csm.configuration.userId || '',\n organizationId: csm.configuration.organizationId || '',\n accountId: csm.configuration.accountId || '',\n appName: csm.configuration.namespace || '',\n });\n csm.putWorkflowEvent(workflowEvent);\n this.eventMap[event] = workflowEvent;\n if (this.instanceSpecified) {\n this.save();\n }\n return workflowEvent;\n };\n\n /**\n * Creates a new workflow event and returns it, if the same event is not happened in ths past\n * dedupeIntervalMs milliseconds.\n * @param {string} event The name of the event that occurred.\n * @param {JSON} data An optional free-form key attribute pair of metadata items that will be stored\n * and reported backstream with the workflow event.\n * @param {int} dedupeIntervalMs defaults to 200 MS\n * @return {WorkflowEvent} workflowEvent\n */\n Workflow.prototype.eventWithDedupe = function(event, data, dedupeIntervalMs) {\n const pastEvent = this.getPastEvent(event);\n const now = new Date().getTime();\n const interval = dedupeIntervalMs || 200;\n\n // Crafting the expected workflow event data result\n const mergedData = this._mergeData(data);\n const expectedData = [];\n for (const key in mergedData) {\n if (Object.prototype.hasOwnProperty.call(mergedData, key)) {\n expectedData.push({'key': key, 'value': mergedData[key]});\n }\n }\n\n // Deduplicate same events that happened within interval\n if (!pastEvent || (pastEvent && JSON.stringify(pastEvent.data) !== JSON.stringify(expectedData)) ||\n (pastEvent && (now - pastEvent.timestamp > interval))) {\n return this.event(event, data);\n }\n return null;\n };\n\n /**\n * Get a past event if it exists in this workflow, otherwise returns null.\n * This can be helpful to emit metrics in real time based on the differences\n * between workflow event timestamps, especially for workflows shared across tabs.\n * @param {string} event key to see if workflow exists for this event\n * @return {WorkflowEvent} workflow event retrieved\n */\n Workflow.prototype.getPastEvent = function(event) {\n return event in this.eventMap ? this.eventMap[event] : null;\n };\n\n /**\n * Save the workflow to local storage. This only happens automatically when an\n * instanceId is specified on workflow creation, however if this method is called\n * explicitly by the client, the randomly generated workflow instance id can be\n * used to retrieve the workflow later and automatic save on events will be enabled.\n */\n Workflow.prototype.save = function() {\n this.instanceSpecified = true;\n localStorage.setItem(getWorkflowKeyForType(this.type), JSON.stringify(this));\n };\n\n /**\n * Remove this workflow if it is the saved instance for this workflow type in localStorage.\n */\n Workflow.prototype.close = function() {\n const storedWorkflow = csm._loadWorkflow(this.type);\n if (storedWorkflow && storedWorkflow.instanceId === this.instanceId) {\n localStorage.removeItem(getWorkflowKeyForType(this.type));\n }\n };\n\n Workflow.prototype.addData = function(data) {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n this.data[key] = data[key];\n }\n }\n };\n\n Workflow.prototype._mergeData = function(data) {\n const mergedData = {};\n let key = null;\n for (key in this.data) {\n if (Object.prototype.hasOwnProperty.call(this.data, key)) {\n mergedData[key] = this.data[key] == null ? 'null' : (this.data[key] === '' ? ' ' : this.data[key].toString());\n }\n }\n for (key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n mergedData[key] = data[key] == null ? 'null' : (data[key] === '' ? ' ' : data[key].toString());\n }\n }\n return mergedData;\n };\n})();\n\n(function() {\n const global = window;\n const csm = global.csm || {};\n global.csm = csm;\n\n let worker = null;\n let portId = null;\n\n const MAX_INIT_MILLISECONDS = 5000;\n const preInitTaskQueue = [];\n csm.configuration = {};\n\n /**\n * Initialize CSM variables\n * @param {object} params for CSM\n * @params.namespace Define your metric namespace used in CloudWatch metrics\n * @params.sharedWorkerUrl Specify the relative url to the connect-csm-worker.js file in your service\n * @params.endpoint Specify an LDAS endpoint to use.\n * @params.dryRunMode When CSM is initialized with dry run mode, it won't actually publish metrics.\n * @params.defaultMetrics Enable default metrics. Default to false.\n */\n csm.initCSM = function(params) {\n csm.Util.assertExist(params.namespace, 'namespace');\n csm.Util.assertExist(params.sharedWorkerUrl, 'sharedWorkerUrl');\n csm.Util.assertExist(params.endpoint, 'endpoint');\n\n try {\n console.log('Starting csm shared worker with', params.sharedWorkerUrl);\n worker = new SharedWorker(params.sharedWorkerUrl, 'CSM_SharedWorker');\n worker.port.start();\n } catch (e) {\n console.log('Failed to initialize csm shared worker with', params.sharedWorkerUrl);\n console.log(e.message);\n }\n\n /**\n * Configure shared worker\n */\n csm.configuration = {\n namespace: params.namespace,\n userId: params.userId || '',\n accountId: params.accountId || '',\n organizationId: params.organizationId || '',\n endpointUrl: params.endpoint || null,\n batchSettings: params.batchSettings || null,\n addPageVisibilityDimension: params.addPageVisibilityDimension || false,\n addUrlDataDimensions: params.addUrlDataDimensions || false,\n dryRunMode: params.dryRunMode || false, // When csm is in dryRunMode it won't actually publish metrics to CSM\n };\n\n postEventToWorker(csm.EVENT_TYPE.CONFIG, csm.configuration);\n\n /**\n * Receive message from shared worker\n * @param {MessageEvent} messageEvent from shared worker\n */\n worker.port.onmessage = function(messageEvent) {\n const messageType = messageEvent.data.type;\n onMessageFromWorker(messageType, messageEvent.data);\n };\n\n /**\n * Inform shared worker window closed\n */\n global.onbeforeunload = function() {\n worker.port.postMessage(\n {\n type: csm.EVENT_TYPE.CLOSE,\n portId: portId,\n },\n );\n };\n\n /**\n * Check if initialization success\n */\n global.setTimeout(function() {\n if (!isCSMInitialized()) {\n console.log('[FATAL] CSM initialization failed! Please make sure the sharedWorkerUrl is reachable.');\n }\n }, MAX_INIT_MILLISECONDS);\n\n // Emit out of the box metrics\n if (params.defaultMetrics) {\n emitDefaultMetrics();\n }\n };\n // Final processing before sending to SharedWorker\n const processMetric = function(metric) {\n if (csm.configuration.addPageVisibilityDimension && document.visibilityState) {\n metric.addOptionalDimension('VisibilityState', document.visibilityState);\n }\n };\n\n const processWorkflowEvent = function(event) {\n if (csm.configuration.addUrlDataDimensions) {\n event.data.push({'key': 'ReferrerUrl', 'value': csm.Util.getReferrerUrl()});\n event.data.push({'key': 'Origin', 'value': csm.Util.getOrigin()});\n event.data.push({'key': 'WindowParent', 'value': csm.Util.getWindowParent()});\n }\n if (['initFailure', 'initializationLatencyInfo'].includes(event.event)) {\n csm.initFailureDimensions.forEach((dimension) => {\n Object.keys(dimension).forEach((key) => {\n event.data.push({'key': key, 'value': dimension[key]});\n });\n });\n }\n return event;\n };\n\n csm.putMetric = function(metric) {\n processMetric(metric);\n postEventToWorker(csm.EVENT_TYPE.METRIC, metric);\n };\n\n csm.putLog = function(log) {\n postEventToWorker(csm.EVENT_TYPE.LOG, log);\n };\n\n csm.putWorkflowEvent = function(event) {\n const processedEvent = processWorkflowEvent(event);\n postEventToWorker(csm.EVENT_TYPE.WORKFLOW_EVENT, processedEvent);\n };\n\n csm.putCustom = function(endpoint, headers, data) {\n postEventToWorker(csm.EVENT_TYPE.CUSTOM, data, endpoint, headers);\n };\n\n csm.setAuthParams = function(authParams) {\n postEventToWorker(csm.EVENT_TYPE.SET_AUTH, authParams);\n };\n\n csm.setConfig = function(key, value) {\n csm.configuration[key] = value;\n postEventToWorker(csm.EVENT_TYPE.SET_CONFIG, {key, value});\n };\n /** ********************** PRIVATE METHODS ************************/\n\n const onMessageFromWorker = function(messageType, data) {\n if (messageType === csm.EVENT_TYPE.CONFIG) {\n portId = data.portId;\n onCSMInitialized();\n }\n };\n\n const onCSMInitialized = function() {\n // Purge the preInitTaskQueue\n preInitTaskQueue.forEach(function(task) {\n postEventToWorker(task.type, task.message, task.endpoint, task.headers);\n });\n\n // TODO: Capture on errors and publish log to shared worker\n /**\n window.onerror = function(message, fileName, lineNumber, columnNumber, errorstack) {\n var log = new csm.Log(message, fileName, lineNumber, columnNumber, errorstack.stack);\n csm.putLog(log);\n };\n */\n };\n\n /**\n * Emit out of the box metrics automatically\n *\n * TODO allow configuration\n */\n const emitDefaultMetrics = function() {\n window.addEventListener('load', function() {\n // loadEventEnd is avaliable after the onload function finished\n // https://www.w3.org/TR/navigation-timing-2/#processing-model\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n global.setTimeout(function() {\n try {\n const perfData = window.performance.getEntriesByType('navigation')[0];\n const pageLoadTime = perfData.loadEventEnd - perfData.startTime;\n const connectTime = perfData.responseEnd - perfData.requestStart;\n const domRenderTime = perfData.domComplete - perfData.domInteractive;\n csm.API.addCountWithPageLocation('PageLoad');\n csm.API.addTimeWithPageLocation('PageLoadTime', pageLoadTime);\n csm.API.addTimeWithPageLocation('ConnectTime', connectTime);\n csm.API.addTimeWithPageLocation('DomRenderTime', domRenderTime);\n } catch (err) {\n console.log('Error emitting default metrics', err);\n }\n }, 0);\n });\n };\n\n /**\n * Try posting message to shared worker\n * If shared worker hasn't been initialized, put the task to queue to be clean up once initialized\n * @param {csm.EVENT_TYPE} eventType for CSM\n * @param {object} message event following type of eventType\n * @param {string} [endpoint] optional parameter for putCustom function (put any data to specified endpoint)\n * @param {object} [headers] optional parameter for putCustom function\n */\n const postEventToWorker = function(eventType, message, endpoint, headers) {\n if (eventType === csm.EVENT_TYPE.CONFIG || isCSMInitialized()) {\n worker.port.postMessage(\n {\n type: eventType,\n portId: portId,\n message: message,\n endpoint: endpoint,\n headers: headers,\n },\n );\n } else {\n preInitTaskQueue.push({\n type: eventType,\n message: message,\n endpoint: endpoint,\n headers: headers,\n });\n }\n };\n\n const isCSMInitialized = function() {\n return portId !== null;\n };\n})()",document.head.appendChild(e),this.initializeCSM()}catch(e){this.logger.error("Load csm script error: ",e)}}},{key:"initializeCSM",value:function(){try{if(this.csmInitialized)return;var e=N.getRegionOverride()||N.getRegion(),t=N.getCell(),n="(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n csm.EVENT_TYPE = {\n LOG: 'LOG',\n METRIC: 'METRIC',\n CONFIG: 'CONFIG',\n WORKFLOW_EVENT: 'WORKFLOW_EVENT',\n CUSTOM: 'CUSTOM',\n CLOSE: 'CLOSE',\n SET_AUTH: 'SET_AUTH',\n SET_CONFIG: 'SET_CONFIG',\n };\n\n csm.UNIT = {\n COUNT: 'Count',\n SECONDS: 'Seconds',\n MILLISECONDS: 'Milliseconds',\n MICROSECONDS: 'Microseconds',\n };\n})();\n\n(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n const MAX_METRIC_DIMENSIONS = 10;\n\n /** ********* Dimension Classes ***********/\n\n const Dimension = function(name, value) {\n csm.Util.assertExist(name, 'name');\n csm.Util.assertExist(value, 'value');\n\n this.name = name;\n this.value = value == null ? 'null' : (value === '' ? ' ' : value.toString());\n };\n\n\n /** ********* Metric Classes ***********/\n\n const Metric = function(metricName, unit, value, dedupeOptions) {\n csm.Util.assertExist(metricName, 'metricName');\n csm.Util.assertExist(value, 'value');\n csm.Util.assertExist(unit, 'unit');\n csm.Util.assertTrue(csm.Util.isValidUnit(unit));\n if (dedupeOptions) {\n csm.Util.assertInObject(dedupeOptions, 'dedupeOptions', 'dedupeIntervalMs');\n }\n\n this.metricName = metricName;\n this.unit = unit;\n this.value = value;\n this.timestamp = new Date();\n this.dimensions = csm.globalDimensions ? csm.Util.deepCopy(csm.globalDimensions): [];\n this.namespace = csm.configuration.namespace;\n this.dedupeOptions = dedupeOptions; // optional. { dedupeIntervalMs: (int; required), context: (string; optional) }\n\n // Currently, CloudWatch can't aggregate metrics by a subset of dimensions.\n // To bypass this limitation, we introduce the optional dimensions concept to CSM.\n // The CSM metric publisher will publish a default metric without optional dimension\n // For each optional dimension, the CSM metric publisher publishes an extra metric with that dimension.\n this.optionalDimensions = csm.globalOptionalDimensions ? csm.Util.deepCopy(csm.globalOptionalDimensions): [];\n };\n\n Metric.prototype.addDimension = function(name, value) {\n this._addDimensionHelper(this.dimensions, name, value);\n };\n\n Metric.prototype.addOptionalDimension = function(name, value) {\n this._addDimensionHelper(this.optionalDimensions, name, value);\n };\n\n Metric.prototype._addDimensionHelper = function(targetDimensions, name, value) {\n // CloudWatch metric allows maximum 10 dimensions\n // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricData-property\n if ((this.dimensions.length + this.optionalDimensions.length) >= MAX_METRIC_DIMENSIONS) {\n throw new csm.ExceedDimensionLimitException(name);\n }\n\n const existing = targetDimensions.find(function(dimension) {\n return dimension.name === name;\n });\n\n if (existing) {\n existing.value = value == null ? 'null' : (value === '' ? ' ' : value.toString());\n } else {\n targetDimensions.push(new Dimension(name, value));\n }\n };\n\n\n /** ********* Telemetry Classes ***********/\n\n const WorkflowEvent = function(params) {\n this.timestamp = params.timestamp || new Date().getTime();\n this.workflowType = params.workflow.type;\n this.instanceId = params.workflow.instanceId;\n this.userId = params.userId;\n this.organizationId = params.organizationId;\n this.accountId = params.accountId;\n this.event = params.event;\n this.appName = params.appName;\n this.data = [];\n\n // Convert 'data' map into the KeyValuePairList structure expected by the Lambda API\n for (const key in params.data) {\n if (Object.prototype.hasOwnProperty.call(params.data, key)) {\n this.data.push({'key': key, 'value': params.data[key]});\n }\n }\n };\n\n /** ********* Exceptions ***********/\n\n const NullOrUndefinedException = function(paramName) {\n this.name = 'NullOrUndefinedException';\n this.message = paramName + ' is null or undefined. ';\n };\n NullOrUndefinedException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const AssertTrueException = function() {\n this.name = 'AssertTrueException';\n this.message = 'Assertion failed. ';\n };\n AssertTrueException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const ExceedDimensionLimitException = function(dimensionName) {\n this.name = 'ExceedDimensionLimitException';\n this.message = 'Could not add dimension ' + dimensionName + ' . Metric has maximum 10 dimensions. ';\n };\n ExceedDimensionLimitException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n const InitializationException = function() {\n this.name = 'InitializationException';\n this.message = 'Initialization failed. ';\n };\n InitializationException.prototype.toString = function() {\n return this.name + ': ' + this.message;\n };\n\n\n csm.Dimension = Dimension;\n csm.Metric = Metric;\n csm.WorkflowEvent = WorkflowEvent;\n csm.NullOrUndefinedException = NullOrUndefinedException;\n csm.AssertTrueException = AssertTrueException;\n csm.InitializationException = InitializationException;\n csm.ExceedDimensionLimitException = ExceedDimensionLimitException;\n})();\n\n(function() {\n const global = self;\n const csm = global.csm || {};\n global.csm = csm;\n\n const validTimeUnits = [csm.UNIT.SECONDS, csm.UNIT.MILLISECONDS, csm.UNIT.MICROSECONDS];\n const validUnits = validTimeUnits.concat(csm.UNIT.COUNT);\n\n const Util = {\n assertExist: function(value, paramName) {\n if (value === null || value === undefined) {\n throw new csm.NullOrUndefinedException(paramName);\n }\n },\n assertTrue: function(value) {\n if (!value) {\n throw new csm.AssertTrueException();\n }\n },\n assertInObject: function(obj, objName, key) {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n throw new csm.NullOrUndefinedException(objName);\n }\n if (key === null || key === undefined || !obj[key]) {\n throw new csm.NullOrUndefinedException(`${objName}[${key}]`);\n }\n },\n isValidUnit: function(unit) {\n return validUnits.includes(unit);\n },\n isValidTimeUnit: function(unit) {\n return validTimeUnits.includes(unit);\n },\n isEmpty: function(value) {\n if (value !== null && typeof val === 'object') {\n return Objects.keys(value).length === 0;\n }\n return !value;\n },\n deepCopy: function(obj) {\n // NOTE: this will fail if obj has a circular reference\n return JSON.parse(JSON.stringify(obj));\n },\n\n /**\n * This function is used before setting the page location for default metrics and logs,\n * and the APIs that set page location\n * Can be overridden by calling csm.API.setPageLocationTransformer(function(){})\n * @param {string} pathname path for page location\n * @return {string} pathname provided\n */\n pageLocationTransformer: function(pathname) {\n return pathname;\n },\n\n /**\n * As of now, our service public claims only support for Firefox and Chrome\n * Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent\n *\n * This function will only return firefox, chrome and others\n *\n * Best practice as indicated in MDN, \"Avoiding user agent detection\"\n */\n getBrowserDetails: function() {\n const userAgent = window.navigator.userAgent;\n const details = {};\n if (userAgent.includes('Firefox') && !userAgent.includes('Seamonkey')) {\n details.name = 'Firefox';\n details.version = getBrowserVersion('Firefox');\n } else if (userAgent.includes('Chrome') && !userAgent.includes('Chromium')) {\n details.name = 'Chrome';\n details.version = getBrowserVersion('Chrome');\n }\n },\n\n randomId: function() {\n return new Date().getTime() + '-' + Math.random().toString(36).slice(2);\n },\n\n getOrigin: function() {\n return document.location.origin;\n },\n\n getReferrerUrl: function() {\n const referrer = document.referrer || '';\n return this.getURLOrigin(referrer);\n },\n\n getWindowParent: function() {\n let parentLocation = '';\n try {\n parentLocation = window.parent.location.href;\n } catch (e) {\n parentLocation = '';\n }\n return parentLocation;\n },\n\n getURLOrigin: function(urlValue) {\n let origin = '';\n const originArray = urlValue.split( '/' );\n if (originArray.length >= 3) {\n const protocol = originArray[0];\n const host = originArray[2];\n origin = protocol + '//' + host;\n }\n return origin;\n },\n\n };\n\n const getBrowserVersion = function(browserName) {\n const userAgent = window.navigator.userAgent;\n const browserNameIndex = userAgent.indexOf(browserName);\n const nextSpaceIndex = userAgent.indexOf(' ', browserNameIndex);\n if (nextSpaceIndex === -1) {\n return userAgent.substring(browserNameIndex + browserName.length + 1, userAgent.length);\n } else {\n return userAgent.substring(browserNameIndex + browserName.length + 1, nextSpaceIndex);\n }\n };\n\n csm.Util = Util;\n})();\n\n(function() {\n const XHR_DONE_READY_STATE = 4; // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState\n\n const global = self;\n const configuration = {};\n const batchSettings = {\n maxMetricsSize: 30,\n maxWorkflowEventsSize: 30,\n putMetricsIntervalMs: 30000,\n putWorkflowEventsIntervalMs: 2000,\n };\n const metricLists = {}; // metricList per CloudWatch Namespace\n const metricMap = {};\n const ports = {};\n let workflowEvents = {workflowEventList: []};\n\n // SharedWorker wiki: https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker\n onconnect = function(connectEvent) {\n const port = connectEvent.ports[0];\n\n port.onmessage = function(event) {\n const data = event.data;\n const messageType = data.type;\n const message = data.message;\n const endpoint = data.endpoint;\n const headers = data.headers;\n\n if (data.portId && !(data.portId in ports)) {\n // This could happen when a user tries to close a tab which has a pop up alert to confirm closing,\n // and the user decides to cancel closing\n // This triggers before unload event while the tab or window is not closed actually\n ports[data.portId] = port;\n }\n\n const {METRIC, WORKFLOW_EVENT, CUSTOM, CONFIG, SET_AUTH, SET_CONFIG, CLOSE} = csm.EVENT_TYPE;\n switch (messageType) {\n case METRIC: {\n csm.Util.assertInObject(message, 'message', 'namespace');\n const namespace = message.namespace;\n if (shouldDedupe(message)) break;\n addMetricEventToMap(message);\n if (metricLists[namespace]) {\n metricLists[namespace].push(message);\n } else {\n metricLists[namespace] = [message];\n }\n if (metricLists[namespace].length >= batchSettings.maxMetricsSize) {\n putMetricsForNamespace(namespace);\n }\n break;\n }\n case WORKFLOW_EVENT: {\n workflowEvents.workflowEventList.push(message);\n if (workflowEvents.length >= batchSettings.maxWorkflowEventsSize) {\n putWorkflowEvents();\n }\n break;\n }\n case CUSTOM: {\n putCustom(endpoint, headers, message);\n break;\n }\n case CONFIG: {\n const portId = Object.keys(ports).length + 1; // portId starts from 1\n ports[portId] = port;\n for (const setting of Object.keys(message)) {\n if (!csm.Util.isEmpty(message[setting])) {\n configuration[setting] = message[setting];\n }\n }\n\n // set optional batch settings\n if (configuration.batchSettings) {\n for (const setting of Object.keys(configuration.batchSettings)) {\n batchSettings[setting] = configuration.batchSettings[setting];\n }\n }\n // send metrics and workflow events at set intervals\n putMetrics();\n putWorkflowEvents();\n global.setInterval(putMetrics, batchSettings.putMetricsIntervalMs);\n global.setInterval(putWorkflowEvents, batchSettings.putWorkflowEventsIntervalMs);\n\n port.postMessage(\n {\n type: csm.EVENT_TYPE.CONFIG,\n portId: portId,\n },\n );\n break;\n }\n case SET_AUTH: {\n configuration.authParams = message;\n authenticate();\n break;\n }\n case SET_CONFIG: {\n configuration[message.key] = message.value;\n break;\n }\n case CLOSE: {\n delete ports[data.portId];\n if (Object.keys(ports).length === 0) {\n putMetrics();\n putWorkflowEvents();\n }\n break;\n }\n default:\n break;\n }\n };\n };\n\n const shouldDedupe = function(metric) {\n try {\n const pastMetric = getPastMetricEvent(metric);\n return pastMetric && metric.dedupeOptions &&\n (metric.timestamp - pastMetric.timestamp < metric.dedupeOptions.dedupeIntervalMs);\n } catch (err) {\n console.error('Error in shouldDedupe', err);\n return false;\n }\n };\n\n const getPastMetricEvent = function(metric) {\n try {\n return metricMap[getMetricEventKey(metric)];\n } catch (err) {\n // ignore err - no previous metrics found\n return null;\n }\n };\n\n const addMetricEventToMap = function(metric) {\n try {\n metricMap[getMetricEventKey(metric)] = metric;\n } catch (err) {\n console.error('Failed to add event to metricMap', err);\n }\n csm.metricMap = metricMap;\n };\n\n const getMetricEventKey = function(metric) {\n const {namespace, metricName, unit, dedupeOptions} = metric;\n let context = 'global';\n if (dedupeOptions && dedupeOptions.context) {\n context = dedupeOptions.context;\n }\n return `${namespace}-${metricName}-${unit}-${context}`;\n };\n\n const authenticate = function() {\n postRequest(configuration.endpointUrl + '/auth', {authParams: configuration.authParams},\n {\n success: function(response) {\n if (response && response.jwtToken) {\n configuration.authParams.jwtToken = response.jwtToken;\n }\n },\n failure: function(response) {\n broadcastMessage('[ERROR] csm auth failed!');\n broadcastMessage('Response : ' + response);\n },\n }, {'x-api-key': 'auth-method-level-key'});\n };\n\n /**\n * Put metrics to service when:\n * a) metricList size is at maxMetricsSize\n * b) every putMetricsIntervalMs time if the metricList is not empty\n * c) worker is closed\n *\n * Timer is reset, and metricList emptied after each putMetrics call\n */\n const putMetrics = function() {\n for (const namespace of Object.keys(metricLists)) {\n putMetricsForNamespace(namespace);\n }\n };\n\n const putMetricsForNamespace = function(namespace) {\n csm.Util.assertInObject(metricLists, 'metricLists', namespace);\n const metricList = metricLists[namespace];\n\n if (metricList.length > 0 && !configuration.dryRunMode && configuration.endpointUrl) {\n postRequest(configuration.endpointUrl + '/put-metrics', {\n metricNamespace: namespace,\n metricList: metricList,\n authParams: configuration.authParams,\n accountId: configuration.accountId,\n organizationId: configuration.organizationId,\n agentResourceId: configuration.userId,\n }, {\n success: function(response) {\n if (response) {\n broadcastMessage('PutMetrics response : ' + response);\n if (response.unsetToken) {\n delete configuration.authParams.jwtToken;\n authenticate();\n }\n }\n },\n failure: function(response) {\n broadcastMessage('[ERROR] Put metrics to service failed! ');\n },\n });\n }\n metricLists[namespace] = [];\n };\n\n /**\n * Put metrics to service every two seconds if there are events to be put.\n */\n const putWorkflowEvents = function() {\n if (workflowEvents.workflowEventList.length > 0 && !configuration.dryRunMode && configuration.endpointUrl) {\n workflowEvents.authParams = configuration.authParams;\n postRequest(configuration.endpointUrl + '/put-workflow-events', workflowEvents,\n {\n success: function(response) {\n if (response) {\n if (response.workflowEventList && response.workflowEventList.length > 0) {\n broadcastMessage('[WARN] There are ' + response.length + ' workflow events that failed to publish');\n broadcastMessage('Response : ' + response);\n }\n if (response.unsetToken) {\n delete configuration.authParams.jwtToken;\n authenticate();\n }\n }\n },\n failure: function(response) {\n broadcastMessage('[ERROR] Put workflow events to service failed! ');\n },\n });\n }\n\n workflowEvents = {workflowEventList: []};\n };\n\n /**\n * Put data to custom endpoint on demand\n * @param {string} endpoint\n * @param {object} headers\n * @param {object} data to send to endpoint\n */\n const putCustom = function(endpoint, headers, data) {\n if (!configuration.dryRunMode && endpoint && data) {\n postRequest(endpoint, data, {\n success: function(response) {\n if (response) {\n broadcastMessage('Response : ' + response);\n }\n },\n failure: function(response) {\n broadcastMessage('[ERROR] Failed to put custom data! ');\n },\n }, headers);\n }\n };\n\n /**\n * Broadcast message to all tabs\n * @param {string} message to post to all the tabs\n */\n const broadcastMessage = function(message) {\n for (const portId in ports) {\n if (Object.prototype.hasOwnProperty.call(ports, portId)) {\n ports[portId].postMessage(message);\n }\n }\n };\n\n const postRequest = function(url, data, callbacks, headers) {\n csm.Util.assertExist(url, 'url');\n csm.Util.assertExist(data, 'data');\n\n callbacks = callbacks || {};\n callbacks.success = callbacks.success || function() {};\n callbacks.failure = callbacks.failure || function() {};\n\n const request = new XMLHttpRequest(); // new HttpRequest instance\n request.onreadystatechange = function() {\n const errorList = request.response ? JSON.parse(request.response): [];\n if (request.readyState === XHR_DONE_READY_STATE) { // request finished and response is ready\n if (request.status === 200) {\n callbacks.success(errorList);\n } else {\n broadcastMessage('AJAX request failed with status: ' + request.status);\n callbacks.failure(errorList);\n }\n }\n };\n\n request.open('POST', url);\n if (headers && typeof headers === 'object') {\n Object.keys(headers).forEach((header) => request.setRequestHeader(header, headers[header]));\n } else {\n request.setRequestHeader('Content-Type', 'application/json');\n }\n request.send(JSON.stringify(data));\n };\n})()".replace(/\\/g,""),i=URL.createObjectURL(new Blob([n],{type:"text/javascript"})),r=function(e){return"https://ieluqbvv.telemetry.connect.".concat(e,".amazonaws.com/prod")}(e),a={endpoint:r,namespace:"chat-widget",sharedWorkerUrl:i};csm.initCSM(a),this.logger.info("CSMService is initialized in ".concat(e," cell-").concat(t)),this.csmInitialized=!0,this.metricsToBePublished&&(this.metricsToBePublished.forEach((function(e){csm.API.addMetric(e)})),this.metricsToBePublished=null)}catch(e){this.logger.error("Failed to initialize csm: ",e)}}},{key:"updateCsmConfig",value:function(e){this.widgetType="object"!=typeof e||null===e||Array.isArray(e)?this.widgetType:e.widgetType}},{key:"_hasCSMFailedToImport",value:function(){return"undefined"==typeof csm}},{key:"getDefaultDimensions",value:function(){return[{name:"WidgetType",value:this.widgetType}]}},{key:"addMetric",value:function(e){if(!this._hasCSMFailedToImport())if(this.csmInitialized)try{csm.API.addMetric(e)}catch(e){this.logger.error("Failed to addMetric csm: ",e)}else this.metricsToBePublished&&(this.metricsToBePublished.push(e),this.logger.info("CSMService is not initialized yet. Adding metrics to queue to be published once CSMService is initialized"))}},{key:"setDimensions",value:function(e,t){t.forEach((function(t){e.addDimension(t.name,t.value)}))}},{key:"addLatencyMetric",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];if(!this._hasCSMFailedToImport())try{var r=new csm.Metric(e,csm.UNIT.MILLISECONDS,t),a=[].concat(d(this.getDefaultDimensions()),[{name:"Metric",value:"Latency"},{name:ce,value:n}],d(i));this.setDimensions(r,a),this.addMetric(r),this.logger.debug("Successfully published latency API metrics for method ".concat(e))}catch(e){this.logger.error("Failed to addLatencyMetric csm: ",e)}}},{key:"addLatencyMetricWithStartTime",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],r=(new Date).getTime()-t;this.addLatencyMetric(e,r,n,i),this.logger.debug("Successfully published latency API metrics for method ".concat(e))}},{key:"addCountAndErrorMetric",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];if(!this._hasCSMFailedToImport())try{var r=[].concat(d(this.getDefaultDimensions()),[{name:ce,value:t}],d(i)),a=new csm.Metric(e,csm.UNIT.COUNT,1);this.setDimensions(a,[].concat(d(r),[{name:"Metric",value:"Count"}]));var o=n?1:0,s=new csm.Metric(e,csm.UNIT.COUNT,o);this.setDimensions(s,[].concat(d(r),[{name:"Metric",value:"Error"}])),this.addMetric(a),this.addMetric(s),this.logger.debug("Successfully published count and error metrics for method ".concat(e))}catch(e){this.logger.error("Failed to addCountAndErrorMetric csm: ",e)}}},{key:"addCountMetric",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(!this._hasCSMFailedToImport())try{var i=[].concat(d(this.getDefaultDimensions()),[{name:ce,value:t},{name:"Metric",value:"Count"}],d(n)),r=new csm.Metric(e,csm.UNIT.COUNT,1);this.setDimensions(r,i),this.addMetric(r),this.logger.debug("Successfully published count metrics for method ".concat(e))}catch(e){this.logger.error("Failed to addCountMetric csm: ",e)}}},{key:"addAgentCountMetric",value:function(e,t){var n=this;if(!this._hasCSMFailedToImport())try{var i=this;csm&&csm.API.addCount&&e?(csm.API.addCount(e,t),i.MAX_RETRY=5):(e&&this.agentMetricToBePublished.push({metricName:e,count:t}),setTimeout((function(){csm&&csm.API.addCount?(n.agentMetricToBePublished.forEach((function(e){csm.API.addCount(e.metricName,e.count)})),n.agentMetricToBePublished=[]):i.MAX_RETRY>0&&(i.MAX_RETRY-=1,i.addAgentCountMetric())}),3e3))}catch(e){this.logger.error("Failed to addAgentCountMetric csm: ",e)}}}]),e}());function fe(e,t,n,i,r,a,o){try{var s=e[a](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(i,r)}var de=function(){function e(t,n,i){h(this,e);var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;this.chatClient=n,this.participantToken=t||null,this.connectionDetails=null,this.connectionToken=null,this.connectionTokenExpiry=null,this.sessionType=i,this.getConnectionToken=r}return p(e,[{key:"getFetchedConnectionToken",value:function(){return this.connectionToken}},{key:"getConnectionTokenExpiry",value:function(){return this.connectionTokenExpiry}},{key:"getConnectionDetails",value:function(){return this.connectionDetails}},{key:"fetchConnectionDetails",value:function(){return this._fetchConnectionDetails().then((function(e){return e}))}},{key:"_handleCreateParticipantConnectionResponse",value:function(e,t){return this.connectionDetails={url:e.Websocket.Url,expiry:e.Websocket.ConnectionExpiry,transportLifeTimeInSeconds:C,connectionAcknowledged:t,connectionToken:e.ConnectionCredentials.ConnectionToken,connectionTokenExpiry:e.ConnectionCredentials.Expiry},this.connectionToken=e.ConnectionCredentials.ConnectionToken,this.connectionTokenExpiry=e.ConnectionCredentials.Expiry,this.connectionDetails}},{key:"_handleGetConnectionTokenResponse",value:function(e){return this.connectionDetails={url:null,expiry:null,connectionToken:e.participantToken,connectionTokenExpiry:e.expiry,transportLifeTimeInSeconds:C,connectionAcknowledged:!1},this.connectionToken=e.participantToken,this.connectionTokenExpiry=e.expiry,Promise.resolve(this.connectionDetails)}},{key:"callCreateParticipantConnection",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.Type,i=void 0===n||n,r=t.ConnectParticipant,a=void 0!==r&&r,o=(new Date).getTime();return this.chatClient.createParticipantConnection(this.participantToken,i?["WEBSOCKET","CONNECTION_CREDENTIALS"]:null,a||null).then((function(t){if(i)return e._addParticipantConnectionMetric(o),e._handleCreateParticipantConnectionResponse(t.data,a)})).catch((function(t){return i&&e._addParticipantConnectionMetric(o,!0),Promise.reject({reason:"Failed to fetch connectionDetails with createParticipantConnection",_debug:t})}))}},{key:"_addParticipantConnectionMetric",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];ue.addLatencyMetricWithStartTime(y.CREATE_PARTICIPANT_CONNECTION,e,b),ue.addCountAndErrorMetric(y.CREATE_PARTICIPANT_CONNECTION,b,t)}},{key:"_fetchConnectionDetails",value:function(){var e,t=this;return(e=m().mark((function e(){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.sessionType===_.CUSTOMER?t.callCreateParticipantConnection():t.sessionType===_.AGENT?t.getConnectionToken().then((function(e){return t._handleGetConnectionTokenResponse(e.chatTokenTransport)})).catch((function(){return t.callCreateParticipantConnection({Type:!0,ConnectParticipant:!0}).catch((function(e){throw new Error({type:"CONN_ACK_FAILED",errorMessage:e})}))})):Promise.reject({reason:"Failed to fetch connectionDetails.",_debug:new a("Failed to fetch connectionDetails.")}));case 1:case"end":return e.stop()}}),e)})),function(){var t=this,n=arguments;return new Promise((function(i,r){var a=e.apply(t,n);function o(e){fe(a,i,r,o,s,"next",e)}function s(e){fe(a,i,r,o,s,"throw",e)}o(void 0)}))})()}}]),e}(),he=void 0!==he?he:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};he.connect=he.connect||{};var pe=connect.WebSocketManager;!function(){var e={975:function(e,t,n){var i;!function(){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 a(e){return function(e,t){var n,i,o,s,l,c,u,f,d,h=1,p=e.length,g="";for(i=0;i=0),s.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,s.width?parseInt(s.width):0);break;case"e":n=s.precision?parseFloat(n).toExponential(s.precision):parseFloat(n).toExponential();break;case"f":n=s.precision?parseFloat(n).toFixed(s.precision):parseFloat(n);break;case"g":n=s.precision?String(Number(n.toPrecision(s.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=s.precision?n.substring(0,s.precision):n;break;case"t":n=String(!!n),n=s.precision?n.substring(0,s.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=s.precision?n.substring(0,s.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=s.precision?n.substring(0,s.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(s.type)?g+=n:(!r.number.test(s.type)||f&&!s.sign?d="":(d=f?"+":"-",n=n.toString().replace(r.sign,"")),c=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",u=s.width-(d+n).length,l=s.width&&u>0?c.repeat(u):"",g+=s.align?d+n+l:"0"===c?d+l+n:l+d+n)}return g}(function(e){if(s[e])return s[e];for(var t,n=e,i=[],a=0;n;){if(null!==(t=r.text.exec(n)))i.push(t[0]);else if(null!==(t=r.modulo.exec(n)))i.push("%");else{if(null===(t=r.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){a|=1;var o=[],l=t[2],c=[];if(null===(c=r.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(o.push(c[1]);""!==(l=l.substring(c[0].length));)if(null!==(c=r.key_access.exec(l)))o.push(c[1]);else{if(null===(c=r.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");o.push(c[1])}t[2]=o}else a|=2;if(3===a)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.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]=i}(e),arguments)}function o(e,t){return a.apply(null,[e].concat(t||[]))}var s=Object.create(null);t.sprintf=a,t.vsprintf=o,"undefined"!=typeof window&&(window.sprintf=a,window.vsprintf=o,void 0===(i=function(){return{sprintf:a,vsprintf:o}}.call(t,n,t,e))||(e.exports=i))}()}},t={};function n(i){var r=t[i];if(void 0!==r)return r.exports;var a=t[i]={exports:{}};return e[i](a,a.exports,n),a.exports}!function(){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)}var t=n(975),i="AMZ_WEB_SOCKET_MANAGER:",r="aws/subscribe",a="aws/heartbeat",o="aws/ping",s="disconnected",l={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(n,i){return l.assertTrue(null!==n&&void 0!==e(n),(0,t.sprintf)("%s must be provided",i||"A value")),n},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(t){return!("object"!==e(t)||null===t)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},c=new RegExp("^(wss://)\\w*"),u=new RegExp("^(ws://127.0.0.1:)");l.validWSUrl=function(e){return c.test(e)||u.test(e)},l.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},l.assertIsObject=function(e,t){if(!l.isObject(e))throw new Error(t+" is not an object!")},l.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)},l.isNetworkOnline=function(){return navigator.onLine},l.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var f=l;function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function p(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:"";if(this.hasClientLogger()){var n="string"==typeof t?t:JSON.stringify(t,T()),i="string"==typeof this.logMetaData?this.logMetaData:JSON.stringify(this.logMetaData,T()),r="".concat(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)," ").concat(n);switch(i&&(r+=" ".concat(i)),e){case k.DEBUG:return this._clientLogger.debug(r)||r;case k.INFO:return this._clientLogger.info(r)||r;case k.WARN:return this._clientLogger.warn(r)||r;case k.ERROR:return this._clientLogger.error(r)||r;case k.ADVANCED_LOG:return this._advancedLogWriter?this._clientLogger[this._advancedLogWriter](r)||r:""}}}},{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||v;return e.logMetaData&&this.setLogMetaData(e.logMetaData),new C(this,function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:2e3;g(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}return m(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}(),S=null,A=function(){var e=S.getLogger({prefix:i,excludeTimestamp:!0}),t=f.isNetworkOnline(),n={primary:null,secondary:null},l={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},c={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},u={pendingResponse:!1,intervalHandle:null},d={pendingResponse:!1,intervalHandle:null},h={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},p={connConfig:null,promiseHandle:null,promiseCompleted:!0},g={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},_={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},m=new D((function(){z().catch((function(){}))})),F=new Set([r,"aws/unsubscribe",a,o]),b=setInterval((function(){if(t!==f.isNetworkOnline()){if(!(t=f.isNetworkOnline()))return void W(e.advancedLog("Network offline"));var n=T();t&&(!n||E(n,WebSocket.CLOSING)||E(n,WebSocket.CLOSED))&&(W(e.advancedLog("Network online, connecting to WebSocket server")),z().catch((function(){})))}}),250),y=function(t,n){t.forEach((function(t){try{t(n)}catch(t){W(e.error("Error executing callback",t))}}))},v=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"}},k=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";W(e.debug("["+t+"] Primary WebSocket: "+v(n.primary)+" | Secondary WebSocket: "+v(n.secondary)))},E=function(e,t){return e&&e.readyState===t},w=function(e){return E(e,WebSocket.OPEN)},C=function(e){return null===e||void 0===e.readyState||E(e,WebSocket.CLOSED)},T=function(){return null!==n.secondary?n.secondary:n.primary},x=function(){return w(T())},A=function(){if(d.pendingResponse&&(W(e.debug("aws/ping deep heartbeat response not received")),y(h.deepHeartbeatFailure,{timestamp:Date.now(),error:"aws/ping response is not received"}),clearInterval(d.intervalHandle),d.pendingResponse=!1),u.pendingResponse)return W(e.warn("Heartbeat response not received")),clearInterval(u.intervalHandle),u.intervalHandle=null,u.pendingResponse=!1,void z().catch((function(){}));x()?(W(e.debug("Sending aws/ping deep heartbeat")),T().send(H(o)),d.pendingResponse=!0,W(e.debug("Sending heartbeat")),T().send(H(a)),u.pendingResponse=!0):(W(e.debug("Failed to send aws/ping deep heartbeat since WebSocket is not open")),y(h.deepHeartbeatFailure,{timestamp:Date.now(),error:"Unable to send message to aws/ping because websocket connection is not established."}),W(e.warn("Failed to send heartbeat since WebSocket is not open")),k("sendHeartBeat"),z().catch((function(){})))},O=function(){W(e.advancedLog("Reset Websocket state")),l.exponentialBackOffTime=1e3,u.pendingResponse=!1,d.pendingResponse=!1,l.reconnectWebSocket=!0,clearTimeout(l.lifeTimeTimeoutHandle),clearInterval(u.intervalHandle),clearInterval(d.intervalHandle),clearTimeout(l.exponentialTimeoutHandle),clearTimeout(l.webSocketInitCheckerTimeoutId),u.intervalHandle=null},I=function(){_.consecutiveFailedSubscribeAttempts=0,_.consecutiveNoResponseRequest=0,clearInterval(_.responseCheckIntervalId),clearInterval(_.reSubscribeIntervalId)},M=function(){c.connectWebSocketRetryCount=0,c.connectionAttemptStartTime=null,c.noOpenConnectionsTimestamp=null},P=function(){m.connected();try{W(e.advancedLog("WebSocket connection established!")),k("webSocketOnOpen"),null!==l.connState&&l.connState!==s||y(h.connectionGain),l.connState="connected";var t=Date.now();y(h.connectionOpen,{connectWebSocketRetryCount:c.connectWebSocketRetryCount,connectionAttemptStartTime:c.connectionAttemptStartTime,noOpenConnectionsTimestamp:c.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-c.connectionAttemptStartTime,timeWithoutConnection:c.noOpenConnectionsTimestamp?t-c.noOpenConnectionsTimestamp:null}),M(),O(),T().openTimestamp=Date.now(),0===g.subscribed.size&&w(n.secondary)&&B(n.primary,"[Primary WebSocket] Closing WebSocket"),(g.subscribed.size>0||g.pending.size>0)&&(w(n.secondary)&&W(e.info("Subscribing secondary websocket to topics of primary websocket")),g.subscribed.forEach((function(e){g.subscriptionHistory.add(e),g.pending.add(e)})),g.subscribed.clear(),j()),A(),null!==u.intervalHandle&&clearInterval(u.intervalHandle),u.intervalHandle=setInterval(A,1e4);var i=1e3*p.connConfig.webSocketTransport.transportLifeTimeInSeconds;W(e.debug("Scheduling WebSocket manager reconnection, after delay "+i+" ms")),l.lifeTimeTimeoutHandle=setTimeout((function(){W(e.debug("Starting scheduled WebSocket manager reconnection")),z().catch((function(){}))}),i)}catch(t){W(e.error("Error after establishing WebSocket connection",t))}},N=function(t){k("webSocketOnError"),W(e.advancedLog("WebSocketManager Error, error_event: ",JSON.stringify(t))),m.getIsConnected()?z().catch((function(){})):m.retry()},R=function(t){if(void 0!==t.data&&""!==t.data){var i=JSON.parse(t.data);switch(i.topic){case r:if(W(e.debug("Subscription Message received from webSocket server")),_.requestCompleted=!0,_.consecutiveNoResponseRequest=0,"success"===i.content.status)_.consecutiveFailedSubscribeAttempts=0,i.content.topics.forEach((function(e){g.subscriptionHistory.delete(e),g.pending.delete(e),g.subscribed.add(e)})),0===g.subscriptionHistory.size?w(n.secondary)&&(W(e.debug("Successfully subscribed secondary websocket to all topics of primary websocket")),B(n.primary,"[Primary WebSocket] Closing WebSocket")):j(),y(h.subscriptionUpdate,i);else{if(clearInterval(_.reSubscribeIntervalId),++_.consecutiveFailedSubscribeAttempts,5===_.consecutiveFailedSubscribeAttempts)return y(h.subscriptionFailure,i),void(_.consecutiveFailedSubscribeAttempts=0);_.reSubscribeIntervalId=setInterval((function(){j()}),500)}break;case a:W(e.debug("Heartbeat response received")),u.pendingResponse=!1,null===u.intervalHandle&&(u.intervalHandle=setInterval(A,1e4));break;case o:W(e.debug("aws/ping deep heartbeat received")),d.pendingResponse=!1,200===i.statusCode?y(h.deepHeartbeatSuccess,{timestamp:Date.now()}):y(h.deepHeartbeatFailure,{timestamp:Date.now(),statusCode:i.statusCode,statusContent:i.statusContent});break;default:if(i.topic){if(W(e.advancedLog("Message received for topic ",i.topic)),w(n.primary)&&w(n.secondary)&&0===g.subscriptionHistory.size&&this===n.primary)return void W(e.warn("Ignoring Message for Topic "+i.topic+", to avoid duplicates"));if(0===h.allMessage.size&&0===h.topic.size)return void W(e.warn("No registered callback listener for Topic",i.topic));W(e.advancedLog("WebsocketManager invoke callbacks for topic success ",i.topic)),y(h.allMessage,i),h.topic.has(i.topic)&&y(h.topic.get(i.topic),i)}else i.message?(W(e.advancedLog("WebSocketManager Message Error",i)),y(h.topicFailure,{timestamp:Date.now(),errorMessage:i.message,connectionId:i.connectionId,requestId:i.requestId})):W(e.advancedLog("Invalid incoming message",i))}}else W(e.warn("An empty message has been received on Websocket. Ignoring"))},j=function t(){if(_.consecutiveNoResponseRequest>3)return W(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void y(h.subscriptionFailure,f.getSubscriptionResponse(r,!1,Array.from(g.pending)));x()?0!==Array.from(g.pending).length&&(clearInterval(_.responseCheckIntervalId),T().send(H(r,{topics:Array.from(g.pending)})),_.requestCompleted=!1,_.responseCheckIntervalId=setInterval((function(){_.requestCompleted||(++_.consecutiveNoResponseRequest,t())}),1e3)):W(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},B=function(t,n){E(t,WebSocket.CONNECTING)||E(t,WebSocket.OPEN)?t.close(1e3,n):W(e.warn("Ignoring WebSocket Close request, WebSocket State: "+v(t)))},L=function(e){B(n.primary,"[Primary] WebSocket "+e),B(n.secondary,"[Secondary] WebSocket "+e)},q=function(t){O(),I(),W(e.advancedLog("WebSocket Initialization failed - Terminating and cleaning subscriptions",t)),l.websocketInitFailed=!0,L("Terminating WebSocket Manager"),clearInterval(b),y(h.initFailure,{connectWebSocketRetryCount:c.connectWebSocketRetryCount,connectionAttemptStartTime:c.connectionAttemptStartTime,reason:t}),M()},H=function(e,t){return JSON.stringify({topic:e,content:t})},U=function(t){return!!(f.isObject(t)&&f.isObject(t.webSocketTransport)&&f.isNonEmptyString(t.webSocketTransport.url)&&f.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(W(e.error("Invalid WebSocket Connection Configuration",t)),!1)},z=function(){return f.isNetworkOnline()?l.websocketInitFailed?(W(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request")),Promise.resolve({webSocketConnectionFailed:!0})):p.promiseCompleted?(O(),W(e.advancedLog("Fetching new WebSocket connection configuration")),c.connectionAttemptStartTime=c.connectionAttemptStartTime||Date.now(),p.promiseCompleted=!1,p.promiseHandle=h.getWebSocketTransport(),p.promiseHandle.then((function(t){return p.promiseCompleted=!0,W(e.advancedLog("Successfully fetched webSocket connection configuration")),U(t)?(p.connConfig=t,p.connConfig.urlConnValidTime=Date.now()+85e3,K()):(q("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return p.promiseCompleted=!0,W(e.advancedLog("Failed to fetch webSocket connection configuration",t)),f.isNetworkFailure(t)?(W(e.advancedLog("Retrying fetching new WebSocket connection configuration",t)),m.retry()):q("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}))):(W(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")),Promise.resolve({webSocketConnectionFailed:!0})):(W(e.advancedLog("Network offline, ignoring this getWebSocketConnConfig request")),Promise.resolve({webSocketConnectionFailed:!0}))},K=function t(){if(l.websocketInitFailed)return W(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!f.isNetworkOnline())return W(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};W(e.advancedLog("Initializing Websocket Manager")),k("initWebSocket");try{if(U(p.connConfig)){var i=null;return w(n.primary)?(W(e.debug("Primary Socket connection is already open")),E(n.secondary,WebSocket.CONNECTING)||(W(e.debug("Establishing a secondary web-socket connection")),m.numAttempts=0,n.secondary=G()),i=n.secondary):(E(n.primary,WebSocket.CONNECTING)||(W(e.debug("Establishing a primary web-socket connection")),n.primary=G()),i=n.primary),l.webSocketInitCheckerTimeoutId=setTimeout((function(){w(i)||function(){c.connectWebSocketRetryCount++;var n=f.addJitter(l.exponentialBackOffTime,.3);Date.now()+n<=p.connConfig.urlConnValidTime?(W(e.advancedLog("Scheduling WebSocket reinitialization, after delay "+n+" ms")),l.exponentialTimeoutHandle=setTimeout((function(){return t()}),n),l.exponentialBackOffTime*=2):(W(e.advancedLog("WebSocket URL cannot be used to establish connection")),z().catch((function(){})))}()}),1e3),{webSocketConnectionFailed:!1}}}catch(i){return W(e.error("Error Initializing web-socket-manager",i)),q("Failed to initialize new WebSocket: "+i.message),{webSocketConnectionFailed:!0}}},G=function(){var t=new WebSocket(p.connConfig.webSocketTransport.url);return t.addEventListener("open",P),t.addEventListener("message",R),t.addEventListener("error",N),t.addEventListener("close",(function(i){return function(t,i){var r={openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason,wasClean:t.wasClean},a="Close Code: ".concat(r.code," - Reason: ").concat(r.reason," - WasClean: ").concat(r.wasClean),o="OpenTimestamp: ".concat(r.openTimestamp," - CloseTimestamp: ").concat(r.closeTimestamp," - ConnectionDuration: ").concat(r.connectionDuration);W(e.advancedLog("WebSocket connection is closed. ",a)),W(e.advancedLog("Closed WebSocket connection duration: ",o)),k("webSocketOnClose before-cleanup"),y(h.connectionClose,r),C(n.primary)&&(n.primary=null),C(n.secondary)&&(n.secondary=null),l.reconnectWebSocket&&(w(n.primary)||w(n.secondary)?C(n.primary)&&w(n.secondary)&&(W(e.debug("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(W(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),l.connState===s?W(e.info("Ignoring connectionLost callback invocation")):(y(h.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),c.noOpenConnectionsTimestamp=Date.now()),l.connState=s,z().catch((function(){}))),k("webSocketOnClose after-cleanup"))}(i,t)})),t},W=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(f.assertTrue(f.isFunction(t),"transportHandle must be a function"),null===h.getWebSocketTransport)return h.getWebSocketTransport=t,z();W(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(t){return W(e.advancedLog("Initializing Websocket Manager Failure callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.initFailure.add(t),l.websocketInitFailed&&t(),function(){return h.initFailure.delete(t)}},this.onConnectionOpen=function(t){return W(e.advancedLog("Websocket connection open callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.connectionOpen.add(t),function(){return h.connectionOpen.delete(t)}},this.onConnectionClose=function(t){return W(e.advancedLog("Websocket connection close callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.connectionClose.add(t),function(){return h.connectionClose.delete(t)}},this.onConnectionGain=function(t){return W(e.advancedLog("Websocket connection gain callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.connectionGain.add(t),x()&&t(),function(){return h.connectionGain.delete(t)}},this.onConnectionLost=function(t){return W(e.advancedLog("Websocket connection lost callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.connectionLost.add(t),l.connState===s&&t(),function(){return h.connectionLost.delete(t)}},this.onSubscriptionUpdate=function(e){return f.assertTrue(f.isFunction(e),"cb must be a function"),h.subscriptionUpdate.add(e),function(){return h.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(t){return W(e.advancedLog("Websocket subscription failure callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.subscriptionFailure.add(t),function(){return h.subscriptionFailure.delete(t)}},this.onMessage=function(e,t){return f.assertNotNull(e,"topicName"),f.assertTrue(f.isFunction(t),"cb must be a function"),h.topic.has(e)?h.topic.get(e).add(t):h.topic.set(e,new Set([t])),function(){return h.topic.get(e).delete(t)}},this.onAllMessage=function(e){return f.assertTrue(f.isFunction(e),"cb must be a function"),h.allMessage.add(e),function(){return h.allMessage.delete(e)}},this.subscribeTopics=function(e){f.assertNotNull(e,"topics"),f.assertIsList(e),e.forEach((function(e){g.subscribed.has(e)||g.pending.add(e)})),_.consecutiveNoResponseRequest=0,j()},this.sendMessage=function(t){if(f.assertIsObject(t,"payload"),void 0===t.topic||F.has(t.topic))W(e.warn("Cannot send message, Invalid topic: "+t.topic));else{try{t=JSON.stringify(t)}catch(n){return void W(e.warn("Error stringify message",t))}x()?T().send(t):W(e.warn("Cannot send message, web socket connection is not open"))}},this.onDeepHeartbeatSuccess=function(t){return W(e.advancedLog("Websocket deep heartbeat success callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.deepHeartbeatSuccess.add(t),function(){return h.deepHeartbeatSuccess.delete(t)}},this.onDeepHeartbeatFailure=function(t){return W(e.advancedLog("Websocket deep heartbeat failure callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.deepHeartbeatFailure.add(t),function(){return h.deepHeartbeatFailure.delete(t)}},this.onTopicFailure=function(t){return W(e.advancedLog("Websocket topic failure callback registered")),f.assertTrue(f.isFunction(t),"cb must be a function"),h.topicFailure.add(t),function(){return h.topicFailure.delete(t)}},this.closeWebSocket=function(){O(),I(),l.reconnectWebSocket=!1,clearInterval(b),L("User request to close WebSocket")},this.terminateWebSocketManager=q},O={create:function(e){return S||(S=new E(e)),S.hasLogMetaData()||S.setLogMetaData(e),new A},setGlobalConfig:function(e){var t=e&&e.loggerConfig;S||(S=new E),S.updateLoggerConfig(t);var n=e&&e.webSocketManagerConfig,i=n&&n.isNetworkOnline;i&&"function"==typeof i&&(f.isNetworkOnline=i)},LogLevel:k,Logger:y};he.connect=he.connect||{},connect.WebSocketManager=O}()}();var ge=connect.WebSocketManager;connect.WebSocketManager=pe||ge;var _e=ge,me=function(e){function t(e,n,i,a,o,c){var u;return h(this,t),(u=s(this,l(t).call(this,i,o))).customerConnection=!a,u.customerConnection?(t.customerBaseInstances[e]||(t.customerBaseInstances[e]=new Fe(i,void 0,o,c)),u.baseInstance=t.customerBaseInstances[e]):(t.agentBaseInstance&&t.agentBaseInstance.getWebsocketManager()!==a&&(t.agentBaseInstance.end(),t.agentBaseInstance=null),t.agentBaseInstance||(t.agentBaseInstance=new Fe(void 0,a,o)),u.baseInstance=t.agentBaseInstance),u.contactId=e,u.initialContactId=n,u.status=null,u.eventBus=new le,u.subscriptions=[u.baseInstance.onEnded(u.handleEnded.bind(r(u))),u.baseInstance.onConnectionGain(u.handleConnectionGain.bind(r(u))),u.baseInstance.onConnectionLost(u.handleConnectionLost.bind(r(u))),u.baseInstance.onMessage(u.handleMessage.bind(r(u))),u.baseInstance.onDeepHeartbeatSuccess(u.handleDeepHeartbeatSuccess.bind(r(u))),u.baseInstance.onDeepHeartbeatFailure(u.handleDeepHeartbeatFailure.bind(r(u)))],u}return c(t,e),p(t,[{key:"start",value:function(){return i(l(t.prototype),"start",this).call(this),this.baseInstance.start()}},{key:"end",value:function(){i(l(t.prototype),"end",this).call(this),this.eventBus.unsubscribeAll(),this.subscriptions.forEach((function(e){return e()})),this.status=X,this.tryCleanup()}},{key:"tryCleanup",value:function(){this.customerConnection&&!this.baseInstance.hasMessageSubscribers()&&(this.baseInstance.end(),delete t.customerBaseInstances[this.contactId])}},{key:"getStatus",value:function(){return this.status||this.baseInstance.getStatus()}},{key:"onEnded",value:function(e){return this.eventBus.subscribe(ee,e)}},{key:"handleEnded",value:function(){this.eventBus.trigger(ee,{})}},{key:"onConnectionGain",value:function(e){return this.eventBus.subscribe(Z,e)}},{key:"handleConnectionGain",value:function(){this.eventBus.trigger(Z,{})}},{key:"onConnectionLost",value:function(e){return this.eventBus.subscribe(Q,e)}},{key:"handleConnectionLost",value:function(){this.eventBus.trigger(Q,{})}},{key:"onDeepHeartbeatSuccess",value:function(e){return this.eventBus.subscribe(ne,e)}},{key:"handleDeepHeartbeatSuccess",value:function(){this.eventBus.trigger(ne,{})}},{key:"onDeepHeartbeatFailure",value:function(e){return this.eventBus.subscribe(ie,e)}},{key:"handleDeepHeartbeatFailure",value:function(){this.eventBus.trigger(ie,{})}},{key:"onMessage",value:function(e){return this.eventBus.subscribe(te,e)}},{key:"handleMessage",value:function(e){e.InitialContactId!==this.initialContactId&&e.ContactId!==this.contactId&&e.Type!==k.MESSAGE_METADATA||this.eventBus.trigger(te,e)}}]),t}(re);me.customerBaseInstances={},me.agentBaseInstance=null;var Fe=function(){function e(t,n,i,r){h(this,e),this.status=G,this.eventBus=new le,this.logger=A.getLogger({prefix:"ChatJS-LPCConnectionHelperBase",logMetaData:i}),this.initialConnectionDetails=r,this.initWebsocketManager(n,t,i)}return p(e,[{key:"initWebsocketManager",value:function(e,t,n){var i,r,a,o,s=this;if(this.websocketManager=e||_e.create(n),this.websocketManager.subscribeTopics(["aws/chat"]),this.subscriptions=[this.websocketManager.onMessage("aws/chat",this.handleMessage.bind(this)),this.websocketManager.onConnectionGain(this.handleConnectionGain.bind(this)),this.websocketManager.onConnectionLost(this.handleConnectionLost.bind(this)),this.websocketManager.onInitFailure(this.handleEnded.bind(this)),null===(i=(r=this.websocketManager).onDeepHeartbeatSuccess)||void 0===i?void 0:i.call(r,this.handleDeepHeartbeatSuccess.bind(this)),null===(a=(o=this.websocketManager).onDeepHeartbeatFailure)||void 0===a?void 0:a.call(o,this.handleDeepHeartbeatFailure.bind(this))],this.logger.info("Initializing websocket manager."),!e){var l=(new Date).getTime();this.websocketManager.init((function(){return s._getConnectionDetails(t,s.initialConnectionDetails,l).then((function(e){return s.initialConnectionDetails=null,e}))}))}}},{key:"_getConnectionDetails",value:function(e,t,n){var i=this;if(null!==t&&"object"==typeof t&&t.expiry&&t.connectionTokenExpiry){var r={expiry:t.expiry,transportLifeTimeInSeconds:C};return this.logger.debug("Websocket manager initialized. Connection details:",r),Promise.resolve({webSocketTransport:{url:t.url,expiry:t.expiry,transportLifeTimeInSeconds:C}})}return e.fetchConnectionDetails().then((function(e){var t={webSocketTransport:{url:e.url,expiry:e.expiry,transportLifeTimeInSeconds:C}},r={expiry:e.expiry,transportLifeTimeInSeconds:C};return i.logger.debug("Websocket manager initialized. Connection details:",r),i._addWebsocketInitCSMMetric(n),t})).catch((function(e){throw i.logger.error("Initializing Websocket Manager failed:",e),i._addWebsocketInitCSMMetric(n,!0),e}))}},{key:"_addWebsocketInitCSMMetric",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];ue.addLatencyMetric(v,e,b),ue.addCountAndErrorMetric(v,b,t)}},{key:"end",value:function(){this.websocketManager.closeWebSocket&&this.websocketManager.closeWebSocket(),this.eventBus.unsubscribeAll(),this.subscriptions.forEach((function(e){return e()})),this.logger.info("Websocket closed. All event subscriptions are cleared.")}},{key:"start",value:function(){return this.status===G&&(this.status=W),Promise.resolve({websocketStatus:this.status})}},{key:"onEnded",value:function(e){return this.eventBus.subscribe(ee,e)}},{key:"handleEnded",value:function(){this.status=X,this.eventBus.trigger(ee,{}),ue.addCountMetric("WebsocketEnded",b),this.logger.info("Websocket connection ended.")}},{key:"onConnectionGain",value:function(e){return this.eventBus.subscribe(Z,e)}},{key:"handleConnectionGain",value:function(){this.status=V,this.eventBus.trigger(Z,{}),ue.addCountMetric("WebsocketConnectionGained",b),this.logger.info("Websocket connection gained.")}},{key:"onConnectionLost",value:function(e){return this.eventBus.subscribe(Q,e)}},{key:"handleConnectionLost",value:function(){this.status=Y,this.eventBus.trigger(Q,{}),ue.addCountMetric("WebsocketConnectionLost",b),this.logger.info("Websocket connection lost.")}},{key:"onMessage",value:function(e){return this.eventBus.subscribe(te,e)}},{key:"handleMessage",value:function(e){var t;try{t=JSON.parse(e.content),this.eventBus.trigger(te,t),ue.addCountMetric("WebsocketIncomingMessage",b),this.logger.info("this.eventBus trigger Websocket incoming message",te,t)}catch(e){this._sendInternalLogToServer(this.logger.error("Wrong message format"))}}},{key:"getStatus",value:function(){return this.status}},{key:"getWebsocketManager",value:function(){return this.websocketManager}},{key:"hasMessageSubscribers",value:function(){return this.eventBus.getSubscriptions(te).length>0}},{key:"_sendInternalLogToServer",value:function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e}},{key:"onDeepHeartbeatSuccess",value:function(e){return this.eventBus.subscribe(ne,e)}},{key:"handleDeepHeartbeatSuccess",value:function(){this.status=$,this.eventBus.trigger(ne,{}),ue.addCountMetric("WebsocketDeepHeartbeatSuccess",b),this.logger.info("Websocket deep heartbeat success.")}},{key:"onDeepHeartbeatFailure",value:function(e){return this.eventBus.subscribe(ie,e)}},{key:"handleDeepHeartbeatFailure",value:function(){this.status=J,this.eventBus.trigger(ie,{}),ue.addCountMetric("WebsocketDeepHeartbeatFailure",b),this.logger.info("Websocket deep heartbeat failure.")}}]),e}(),be=me;function ye(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}var ve=function(){function e(t){h(this,e),this.logger=A.getLogger({prefix:"ChatJS-MessageReceiptUtil",logMetaData:t}),this.timeout=null,this.timeoutId=null,this.readSet=new Set,this.deliveredSet=new Set,this.readPromiseMap=new Map,this.deliveredPromiseMap=new Map,this.lastReadArgs=null,this.throttleInitialEventsToPrioritizeRead=null,this.throttleSendEventApiCall=null}return p(e,[{key:"isMessageReceipt",value:function(e,t){return-1!==[k.INCOMING_READ_RECEIPT,k.INCOMING_DELIVERED_RECEIPT].indexOf(e)||t.Type===k.MESSAGE_METADATA}},{key:"getEventTypeFromMessageMetaData",value:function(e){return Array.isArray(e.Receipts)&&e.Receipts[0]&&e.Receipts[0].ReadTimestamp?k.INCOMING_READ_RECEIPT:e.Receipts[0].DeliveredTimestamp?k.INCOMING_DELIVERED_RECEIPT:null}},{key:"shouldShowMessageReceiptForCurrentParticipantId",value:function(e,t){return e!==(t.MessageMetadata&&Array.isArray(t.MessageMetadata.Receipts)&&t.MessageMetadata.Receipts[0]&&t.MessageMetadata.Receipts[0].RecipientParticipantId)}},{key:"prioritizeAndSendMessageReceipt",value:function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r2?n-2:0),r=2;r1&&a.resolveReadPromises(c,e[1].value||e[1].reason,"rejected"===e[1].status)}))}}catch(e){a.logger.error("send message receipt failed",e),a.resolveReadPromises(l,e,!0),a.resolveDeliveredPromises(l,e,!0)}},a.timeoutId||(a.timeoutId=setTimeout((function(){a.timeoutId=null,a.throttleSendEventApiCall()}),o))}},{key:"resolveDeliveredPromises",value:function(e,t,n){return this.resolvePromises(this.deliveredPromiseMap,e,t,n)}},{key:"resolveReadPromises",value:function(e,t,n){return this.resolvePromises(this.readPromiseMap,e,t,n)}},{key:"resolvePromises",value:function(e,t,n,i){var r=Array.from(e.keys()),a=r.indexOf(t);if(-1!==a)for(var o=0;o<=a;o++){var s,l=null===(s=e.get(r[o]))||void 0===s?void 0:s[i?1:0];"function"==typeof l&&(e.delete(r[o]),l(n))}else this.logger.debug("Promise for messageId: ".concat(t," already resolved"))}},{key:"rehydrateReceiptMappers",value:function(e,t){var n=this,i=this;return function(r){if(i.logger.debug("rehydrate chat",null==r?void 0:r.data),t){var a=((null==r?void 0:r.data)||{}).Transcript;(void 0===a?[]:a).forEach((function(e){if((null==e?void 0:e.Type)===k.MESSAGE_METADATA){var t,i,r=null==e||null===(t=e.MessageMetadata)||void 0===t||null===(t=t.Receipts)||void 0===t?void 0:t[0],a=null==e||null===(i=e.MessageMetadata)||void 0===i?void 0:i.MessageId;null!=r&&r.ReadTimestamp&&n.readSet.add(a),null!=r&&r.DeliveredTimestamp&&n.deliveredSet.add(a)}}))}return e(r)}}}]),e}();function ke(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}var Ee="Broken",we=function(){function e(t){h(this,e),this.argsValidator=new K,this.pubsub=new le,this.sessionType=t.sessionType,this.getConnectionToken=t.chatDetails.getConnectionToken,this.connectionDetails=t.chatDetails.connectionDetails,this.initialContactId=t.chatDetails.initialContactId,this.contactId=t.chatDetails.contactId,this.participantId=t.chatDetails.participantId,this.chatClient=t.chatClient,this.participantToken=t.chatDetails.participantToken,this.websocketManager=t.websocketManager,this._participantDisconnected=!1,this.sessionMetadata={},this.connectionDetailsProvider=null,this.logger=A.getLogger({prefix:"ChatJS-ChatController",logMetaData:t.logMetaData}),this.logMetaData=t.logMetaData,this.messageReceiptUtil=new ve(t.logMetaData),this.hasChatEnded=!1,this.logger.info("Browser info:",window.navigator.userAgent)}return p(e,[{key:"subscribe",value:function(e,t){this.pubsub.subscribe(e,t),this._sendInternalLogToServer(this.logger.info("Subscribed successfully to event:",e))}},{key:"handleRequestSuccess",value:function(e,t,n,i){return function(r){var a=i?[{name:"ContentType",value:i}]:[];return ue.addLatencyMetricWithStartTime(t,n,b,a),ue.addCountAndErrorMetric(t,b,!1,a),r.metadata=e,r}}},{key:"handleRequestFailure",value:function(e,t,n,i){return function(r){var a=i?[{name:"ContentType",value:i}]:[];return ue.addLatencyMetricWithStartTime(t,n,b,a),ue.addCountAndErrorMetric(t,b,!0,a),r.metadata=e,Promise.reject(r)}}},{key:"sendMessage",value:function(e){if(!this._validateConnectionStatus("sendMessage"))return Promise.reject("Failed to call sendMessage, No active connection");var t=(new Date).getTime(),n=e.metadata||null;this.argsValidator.validateSendMessage(e);var i=this.connectionHelper.getConnectionToken();return this.chatClient.sendMessage(i,e.message,e.contentType).then(this.handleRequestSuccess(n,y.SEND_MESSAGE,t,e.contentType)).catch(this.handleRequestFailure(n,y.SEND_MESSAGE,t,e.contentType))}},{key:"sendAttachment",value:function(e){if(!this._validateConnectionStatus("sendAttachment"))return Promise.reject("Failed to call sendAttachment, No active connection");var t=(new Date).getTime(),n=e.metadata||null,i=this.connectionHelper.getConnectionToken();return this.chatClient.sendAttachment(i,e.attachment,e.metadata).then(this.handleRequestSuccess(n,y.SEND_ATTACHMENT,t,e.attachment.type)).catch(this.handleRequestFailure(n,y.SEND_ATTACHMENT,t,e.attachment.type))}},{key:"downloadAttachment",value:function(e){if(!this._validateConnectionStatus("downloadAttachment"))return Promise.reject("Failed to call downloadAttachment, No active connection");var t=(new Date).getTime(),n=e.metadata||null,i=this.connectionHelper.getConnectionToken();return this.chatClient.downloadAttachment(i,e.attachmentId).then(this.handleRequestSuccess(n,y.DOWNLOAD_ATTACHMENT,t)).catch(this.handleRequestFailure(n,y.DOWNLOAD_ATTACHMENT,t))}},{key:"sendEventIfChatHasNotEnded",value:function(){for(var e,t,n=arguments.length,i=new Array(n),r=0;r0&&void 0!==arguments[0]?arguments[0]:{};if(!this._validateConnectionStatus("getTranscript"))return Promise.reject("Failed to call getTranscript, No active connection");var t=(new Date).getTime(),n=e.metadata||null,i={startPosition:e.startPosition||{},scanDirection:e.scanDirection||"BACKWARD",sortOrder:e.sortOrder||"ASCENDING",maxResults:e.maxResults||15};e.nextToken&&(i.nextToken=e.nextToken),e.contactId&&(i.contactId=e.contactId);var r=this.connectionHelper.getConnectionToken();return this.chatClient.getTranscript(r,i).then(this.messageReceiptUtil.rehydrateReceiptMappers(this.handleRequestSuccess(n,y.GET_TRANSCRIPT,t),N.isFeatureEnabled(g))).catch(this.handleRequestFailure(n,y.GET_TRANSCRIPT,t))}},{key:"connect",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.sessionMetadata=t.metadata||null,this.argsValidator.validateConnectChat(t),!this.connectionDetailsProvider)return this.connectionDetailsProvider=this._getConnectionDetailsProvider(),this.connectionDetailsProvider.fetchConnectionDetails().then((function(t){return e._initConnectionHelper(e.connectionDetailsProvider,t)})).then((function(t){return e._onConnectSuccess(t,e.connectionDetailsProvider)})).catch((function(t){return e._onConnectFailure(t)}));this.logger.warn("Ignoring duplicate call to connect. Method can only be invoked once",t)}},{key:"_initConnectionHelper",value:function(e,t){return this.connectionHelper=new be(this.contactId,this.initialContactId,e,this.websocketManager,this.logMetaData,t),this.connectionDetails=t,this.connectionHelper.onEnded(this._handleEndedConnection.bind(this)),this.connectionHelper.onConnectionLost(this._handleLostConnection.bind(this)),this.connectionHelper.onConnectionGain(this._handleGainedConnection.bind(this)),this.connectionHelper.onMessage(this._handleIncomingMessage.bind(this)),this.connectionHelper.onDeepHeartbeatSuccess(this._handleDeepHeartbeatSuccess.bind(this)),this.connectionHelper.onDeepHeartbeatFailure(this._handleDeepHeartbeatFailure.bind(this)),this.connectionHelper.start()}},{key:"_getConnectionDetailsProvider",value:function(){return new de(this.participantToken,this.chatClient,this.sessionType,this.getConnectionToken)}},{key:"_handleEndedConnection",value:function(e){this._forwardChatEvent(k.CONNECTION_BROKEN,{data:e,chatDetails:this.getChatDetails()}),this.breakConnection()}},{key:"_handleLostConnection",value:function(e){this._forwardChatEvent(k.CONNECTION_LOST,{data:e,chatDetails:this.getChatDetails()})}},{key:"_handleGainedConnection",value:function(e){this.hasChatEnded=!1,this._forwardChatEvent(k.CONNECTION_ESTABLISHED,{data:e,chatDetails:this.getChatDetails()})}},{key:"_handleDeepHeartbeatSuccess",value:function(e){this._forwardChatEvent(k.DEEP_HEARTBEAT_SUCCESS,{data:e,chatDetails:this.getChatDetails()})}},{key:"_handleDeepHeartbeatFailure",value:function(e){this._forwardChatEvent(k.DEEP_HEARTBEAT_FAILURE,{data:e,chatDetails:this.getChatDetails()})}},{key:"_handleIncomingMessage",value:function(e){try{var t=Ce(null==e?void 0:e.ContentType);if(this.messageReceiptUtil.isMessageReceipt(t,e)&&(!(t=this.messageReceiptUtil.getEventTypeFromMessageMetaData(null==e?void 0:e.MessageMetadata))||!this.messageReceiptUtil.shouldShowMessageReceiptForCurrentParticipantId(this.participantId,e)))return;this._forwardChatEvent(t,{data:e,chatDetails:this.getChatDetails()}),e.ContentType===E.chatEnded&&(this.hasChatEnded=!0,this._forwardChatEvent(k.CHAT_ENDED,{data:null,chatDetails:this.getChatDetails()}),this.breakConnection()),e.ContentType===E.transferSucceeded&&this.sessionType!==_.CUSTOMER&&this.breakConnection()}catch(t){this._sendInternalLogToServer(this.logger.error("Error occured while handling message from Connection. eventData:",e," Causing exception:",t))}}},{key:"_forwardChatEvent",value:function(e,t){this.pubsub.triggerAsync(e,t)}},{key:"_onConnectSuccess",value:function(e,t){var n,i=this;this._sendInternalLogToServer(this.logger.info("Connect successful!")),this.logger.warn("onConnectionSuccess response",e);var r={_debug:e,connectSuccess:!0,connectCalled:!0,metadata:this.sessionMetadata},a=Object.assign({chatDetails:this.getChatDetails()},r);this.pubsub.triggerAsync(k.CONNECTION_ESTABLISHED,a);var o=null===(n=t.getConnectionDetails())||void 0===n?void 0:n.connectionAcknowledged;return this._shouldAcknowledgeContact()&&!o&&(ue.addAgentCountMetric("CREATE_PARTICIPANT_CONACK_CALL_COUNT",1),t.callCreateParticipantConnection({Type:!1,ConnectParticipant:!0}).catch((function(e){i.logger.warn("ConnectParticipant failed to acknowledge Agent connection in CreateParticipantConnection: ",e),ue.addAgentCountMetric("CREATE_PARTICIPANT_CONACK_FAILURE",1)}))),this.logger.warn("onConnectionSuccess responseObject",r),r}},{key:"_onConnectFailure",value:function(e){var t={_debug:e,connectSuccess:!1,connectCalled:!0,metadata:this.sessionMetadata};return this._sendInternalLogToServer(this.logger.error("Connect Failed. Error: ",t)),Promise.reject(t)}},{key:"_shouldAcknowledgeContact",value:function(){return this.sessionType===_.AGENT}},{key:"breakConnection",value:function(){return this.connectionHelper?this.connectionHelper.end():Promise.resolve()}},{key:"cleanUpOnParticipantDisconnect",value:function(){this.pubsub.unsubscribeAll()}},{key:"disconnectParticipant",value:function(){var e=this;if(!this._validateConnectionStatus("disconnectParticipant"))return Promise.reject("Failed to call disconnectParticipant, No active connection");var t=(new Date).getTime(),n=this.connectionHelper.getConnectionToken();return this.chatClient.disconnectParticipant(n).then((function(n){return e._sendInternalLogToServer(e.logger.info("Disconnect participant successfully")),e._participantDisconnected=!0,e.cleanUpOnParticipantDisconnect(),e.breakConnection(),ue.addLatencyMetricWithStartTime(y.DISCONNECT_PARTICIPANT,t,b),ue.addCountAndErrorMetric(y.DISCONNECT_PARTICIPANT,b,!1),n=function(e){for(var t=1;t-1)throw new Error("`"+t+"` cannot be a path: did not expect `"+i.sep+"`")}function u(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function f(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}l.prototype.toString=function(e){return(this.contents||"").toString(e)},Object.defineProperty(l.prototype,"path",{get:function(){return this.history[this.history.length-1]},set:function(e){u(e,"path"),this.path!==e&&this.history.push(e)}}),Object.defineProperty(l.prototype,"dirname",{get:function(){return"string"===typeof this.path?i.dirname(this.path):void 0},set:function(e){f(this.path,"dirname"),this.path=i.join(e||"",this.basename)}}),Object.defineProperty(l.prototype,"basename",{get:function(){return"string"===typeof this.path?i.basename(this.path):void 0},set:function(e){u(e,"basename"),c(e,"basename"),this.path=i.join(this.dirname||"",e)}}),Object.defineProperty(l.prototype,"extname",{get:function(){return"string"===typeof this.path?i.extname(this.path):void 0},set:function(e){if(c(e,"extname"),f(this.path,"extname"),e){if(46!==e.charCodeAt(0))throw new Error("`extname` must start with `.`");if(e.indexOf(".",1)>-1)throw new Error("`extname` cannot contain multiple dots")}this.path=i.join(this.dirname,this.stem+(e||""))}}),Object.defineProperty(l.prototype,"stem",{get:function(){return"string"===typeof this.path?i.basename(this.path,this.extname):void 0},set:function(e){u(e,"stem"),c(e,"stem"),this.path=i.join(this.dirname||"",e+(this.extname||""))}})},function(e,t,n){"use strict";function i(e){if("string"!==typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}t.basename=function(e,t){var n,r,a,o,s=0,l=-1;if(void 0!==t&&"string"!==typeof t)throw new TypeError('"ext" argument must be a string');if(i(e),n=e.length,void 0===t||!t.length||t.length>e.length){for(;n--;)if(47===e.charCodeAt(n)){if(a){s=n+1;break}}else l<0&&(a=!0,l=n+1);return l<0?"":e.slice(s,l)}if(t===e)return"";r=-1,o=t.length-1;for(;n--;)if(47===e.charCodeAt(n)){if(a){s=n+1;break}}else r<0&&(a=!0,r=n+1),o>-1&&(e.charCodeAt(n)===t.charCodeAt(o--)?o<0&&(l=n):(o=-1,l=r));s===l?l=r:l<0&&(l=e.length);return e.slice(s,l)},t.dirname=function(e){var t,n,r;if(i(e),!e.length)return".";t=-1,r=e.length;for(;--r;)if(47===e.charCodeAt(r)){if(n){t=r;break}}else n||(n=!0);return t<0?47===e.charCodeAt(0)?"/":".":1===t&&47===e.charCodeAt(0)?"//":e.slice(0,t)},t.extname=function(e){var t,n,r,a=-1,o=0,s=-1,l=0;i(e),r=e.length;for(;r--;)if(47!==(n=e.charCodeAt(r)))s<0&&(t=!0,s=r+1),46===n?a<0?a=r:1!==l&&(l=1):a>-1&&(l=-1);else if(t){o=r+1;break}if(a<0||s<0||0===l||1===l&&a===s-1&&a===o+1)return"";return e.slice(a,s)},t.join=function(){var e,t=-1;for(;++t2){if((i=r.lastIndexOf("/"))!==r.length-1){i<0?(r="",a=0):a=(r=r.slice(0,i)).length-1-r.lastIndexOf("/"),o=l,s=0;continue}}else if(r.length){r="",a=0,o=l,s=0;continue}t&&(r=r.length?r+"/..":"..",a=2)}else r.length?r+="/"+e.slice(o+1,l):r=e.slice(o+1,l),a=l-o-1;o=l,s=0}else 46===n&&s>-1?s++:s=-1}return r}(e,!t),n.length||t||(n=".");n.length&&47===e.charCodeAt(e.length-1)&&(n+="/");return t?"/"+n:n}(e)},t.sep="/"},function(e,t,n){"use strict";t.cwd=function(){return"/"}},function(e,t,n){"use strict";var i=n(645),r=n(279),a=n(646),o=n(647),s=n(648),l=n(277);e.exports=function e(){var t,n=[],r=s(),F={},b=-1;return y.data=function(e,n){if("string"===typeof e)return 2===arguments.length?(g("data",t),F[e]=n,y):u.call(F,e)&&F[e]||null;if(e)return g("data",t),F=e,y;return F},y.freeze=v,y.attachers=n,y.use=function(e){var i;if(g("use",t),null===e||void 0===e);else if("function"===typeof e)u.apply(null,arguments);else{if("object"!==typeof e)throw new Error("Expected usable value, not `"+e+"`");"length"in e?l(e):r(e)}i&&(F.settings=a(F.settings||{},i));return y;function r(e){l(e.plugins),e.settings&&(i=a(i||{},e.settings))}function s(e){if("function"===typeof e)u(e);else{if("object"!==typeof e)throw new Error("Expected usable value, not `"+e+"`");"length"in e?u.apply(null,e):r(e)}}function l(e){var t=-1;if(null===e||void 0===e);else{if("object"!==typeof e||!("length"in e))throw new Error("Expected a list of plugins, not `"+e+"`");for(;++to.length;s&&o.push(r);try{t=e.apply(null,o)}catch(l){if(s&&n)throw l;return r(l)}s||(t&&"function"===typeof t.then?t.then(a,r):t instanceof Error?r(t):a(t))};function r(){n||(n=!0,t.apply(null,arguments))}function a(e){r(null,e)}}},function(e,t,n){"use strict";e.exports=function(e){var t=this;this.Parser=function(n){return i(n,Object.assign({},t.data("settings"),e,{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}};var i=n(651)},function(e,t,n){"use strict";e.exports=n(652)},function(e,t,n){"use strict";e.exports=function(e,t,n){"string"!==typeof t&&(n=t,t=void 0);return function(e){var t=e||{},n=function(e,t){var n=-1;for(;++n-1&&(j.call(this,e),B.call(this,e))}function q(){p("atHardBreak",!0)}function H(){var e=this.resume();this.stack[this.stack.length-1].value=e}function U(){var e=this.resume();this.stack[this.stack.length-1].value=e}function z(){var e=this.resume();this.stack[this.stack.length-1].value=e}function K(){var e=this.stack[this.stack.length-1];g("inReference")?(e.type+="Reference",e.referenceType=g("referenceType")||"shortcut",delete e.url,delete e.title):(delete e.identifier,delete e.label,delete e.referenceType),p("referenceType")}function G(){var e=this.stack[this.stack.length-1];g("inReference")?(e.type+="Reference",e.referenceType=g("referenceType")||"shortcut",delete e.url,delete e.title):(delete e.identifier,delete e.label,delete e.referenceType),p("referenceType")}function W(e){this.stack[this.stack.length-2].identifier=o(this.sliceSerialize(e)).toLowerCase()}function V(){var e=this.stack[this.stack.length-1],t=this.resume();this.stack[this.stack.length-1].label=t,p("inReference",!0),"link"===this.stack[this.stack.length-1].type?this.stack[this.stack.length-1].children=e.children:this.stack[this.stack.length-1].alt=t}function Y(){var e=this.resume();this.stack[this.stack.length-1].url=e}function X(){var e=this.resume();this.stack[this.stack.length-1].title=e}function $(){p("inReference")}function J(){p("referenceType","collapsed")}function Q(e){var t=this.resume();this.stack[this.stack.length-1].label=t,this.stack[this.stack.length-1].identifier=o(this.sliceSerialize(e)).toLowerCase(),p("referenceType","full")}function Z(e){p("characterReferenceType",e.type)}function ee(e){var t,n,i=this.sliceSerialize(e),r=g("characterReferenceType");r?(t=s(i,"characterReferenceMarkerNumeric"===r?10:16),p("characterReferenceType")):t=f(i),(n=this.stack.pop()).value+=t,n.position.end=_(e.end)}function te(e){B.call(this,e),this.stack[this.stack.length-1].url=this.sliceSerialize(e)}function ne(e){B.call(this,e),this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)}function ie(){return{type:"blockquote",children:[]}}function re(){return{type:"code",lang:null,meta:null,value:""}}function ae(){return{type:"inlineCode",value:""}}function oe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function se(){return{type:"emphasis",children:[]}}function le(){return{type:"heading",depth:void 0,children:[]}}function ce(){return{type:"break"}}function ue(){return{type:"html",value:""}}function fe(){return{type:"image",title:null,url:"",alt:null}}function de(){return{type:"link",title:null,url:"",children:[]}}function he(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}function pe(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}function ge(){return{type:"paragraph",children:[]}}function _e(){return{type:"strong",children:[]}}function me(){return{type:"text",value:""}}function Fe(){return{type:"thematicBreak"}}}(n)(u(l(n).document().write(c()(e,t,!0))))};var i=n(653),r=n(110),a=n(280),o=n(189),s=n(654),l=n(655),c=n(694),u=n(695),f=n(285),d=n(278);function h(e,t){var n,i;for(n in t)i=a.call(e,n)?e[n]:e[n]={},"canContainEols"===n||"transforms"===n?e[n]=[].concat(i,t[n]):Object.assign(i,t[n])}},function(e,t,n){"use strict";function i(e){return e&&(e.value||e.alt||e.title||"children"in e&&r(e.children)||"length"in e&&r(e))||""}function r(e){for(var t=[],n=-1;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||65535===(65535&n)||65534===(65535&n)||n>1114111?"\ufffd":i(n)}},function(e,t,n){"use strict";var i=n(656),r=n(657),a=n(658),o=n(283),s=n(661),l=n(662),c=n(190),u=n(665);e.exports=function(e){var t={defined:[],constructs:s([u].concat(c((e||{}).extensions))),content:n(i),document:n(r),flow:n(a),string:n(o.string),text:n(o.text)};return t;function n(e){return function(n){return l(t,e,n)}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(22),r=n(23),a=function(e){var t,n=e.attempt(this.parser.constructs.contentInitial,(function(t){if(null===t)return void e.consume(t);return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r(e,n,"linePrefix")}),(function(t){return e.enter("paragraph"),a(t)}));return n;function a(n){var i=e.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=i),t=i,o(n)}function o(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):i(t)?(e.consume(t),e.exit("chunkText"),a):(e.consume(t),o)}};t.tokenize=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(22),r=n(23),a=n(137),o=function(e){var t,n,r,o=this,c=[],u=0,f={tokenize:function(e,i){var r=0;return t={},u;function u(i){return rt;)o.containerState=c[a][1],c[a][0].exit.call(o,e);c.length=t}},s={tokenize:function(e,t,n){return r(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.indexOf("codeIndented")>-1?void 0:4)}},l={tokenize:function(e,t,n){return r(e,e.lazy(this.parser.constructs.flow,t,n),"linePrefix",this.parser.constructs.disable.null.indexOf("codeIndented")>-1?void 0:4)}};t.tokenize=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(659),r=n(23),a=n(137),o=function(e){var t=this,n=e.attempt(a,(function(i){if(null===i)return void e.consume(i);return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}),e.attempt(this.parser.constructs.flowInitial,o,r(e,e.attempt(this.parser.constructs.flow,o,e.attempt(i,o)),"linePrefix")));return n;function o(i){if(null!==i)return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(i)}};t.tokenize=o},function(e,t,n){"use strict";var i=n(22),r=n(138),a=n(282),o=n(23),s={tokenize:function(e,t){var n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(t)};function r(t){return null===t?a(t):i(t)?e.check(l,o,a)(t):(e.consume(t),r)}function a(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function o(t){return e.consume(t),e.exit("chunkContent"),n=n.next=e.enter("chunkContent",{contentType:"content",previous:n}),r}},resolve:function(e){return a(e),e},interruptible:!0,lazy:!0},l={tokenize:function(e,t,n){var a=this;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o(e,s,"linePrefix")};function s(o){return null===o||i(o)?n(o):a.parser.constructs.disable.null.indexOf("codeIndented")>-1||r(a.events,"linePrefix")<4?e.interrupt(a.parser.constructs.flow,n,t)(o):t(o)}},partial:!0};e.exports=s},function(e,t,n){"use strict";var i=[].splice;e.exports=i},function(e,t,n){"use strict";var i=n(280),r=n(70),a=n(190);function o(e,t){var n,r,o,l;for(n in t)for(l in r=i.call(e,n)?e[n]:e[n]={},o=t[n])r[l]=s(a(o[l]),i.call(r,l)?r[l]:[])}function s(e,t){for(var n=-1,i=[];++n-1)return g();return e.tokenize.call(t?i({},F,t):F,m,p,g)(n)}}function p(t){return e(c,u),r}function g(e){return u.restore(),++l-1&&(n[0]=n[0].slice(r)),o>0&&n.push(e[a].slice(0,o))),n}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(283),r=n(666),a=n(672),o=n(674),s=n(675),l=n(677),c=n(679),u=n(680),f=n(681),d=n(682),h=n(683),p=n(684),g=n(685),_=n(688),m=n(194),F=n(689),b=n(690),y=n(691),v=n(692),k=n(693),E=n(291),w={42:v,43:v,45:v,48:v,49:v,50:v,51:v,52:v,53:v,54:v,55:v,56:v,57:v,62:o},C={91:d},T={"-2":u,"-1":u,32:u},x={35:p,42:E,45:[k,E],60:g,61:k,95:E,96:c,126:c},D={38:l,92:s},S={"-5":y,"-4":y,"-3":y,33:F,38:l,42:r,60:[a,_],91:b,92:[h,s],93:m,95:r,96:f},A={null:[r,i.resolver]};t.contentInitial=C,t.disable={null:[]},t.document=w,t.flow=x,t.flowInitial=T,t.insideSpan=A,t.string=D,t.text=S},function(e,t,n){"use strict";var i=n(191),r=n(70),a=n(667),o=n(671),s=n(192),l=n(96),c={name:"attention",tokenize:function(e,t){var n,i=a(this.previous);return function(t){return e.enter("attentionSequence"),n=t,r(t)};function r(o){var s,l,c,u;return o===n?(e.consume(o),r):(s=e.exit("attentionSequence"),c=!(l=a(o))||2===l&&i,u=!i||2===i&&l,s._open=42===n?c:c&&(i||!u),s._close=42===n?u:u&&(l||!c),t(o))}},resolveAll:function(e,t){var n,a,c,u,f,d,h,p,g=-1;for(;++g1&&e[g][1].end.offset-e[g][1].start.offset>1?2:1)>1?"strongSequence":"emphasisSequence",start:o(l(e[n][1].end),-d),end:l(e[n][1].end)},f={type:d>1?"strongSequence":"emphasisSequence",start:l(e[g][1].start),end:o(l(e[g][1].start),d)},c={type:d>1?"strongText":"emphasisText",start:l(e[n][1].end),end:l(e[g][1].start)},a={type:d>1?"strong":"emphasis",start:l(u.start),end:l(f.end)},e[n][1].end=l(u.start),e[g][1].start=l(f.end),h=[],e[n][1].end.offset-e[n][1].start.offset&&(h=i(h,[["enter",e[n][1],t],["exit",e[n][1],t]])),h=i(h,[["enter",a,t],["enter",u,t],["exit",u,t],["enter",c,t]]),h=i(h,s(t.parser.constructs.insideSpan.null,e.slice(n+1,g),t)),h=i(h,[["exit",c,t],["enter",f,t],["exit",f,t],["exit",a,t]]),e[g][1].end.offset-e[g][1].start.offset?(p=2,h=i(h,[["enter",e[g][1],t],["exit",e[g][1],t]])):p=0,r(e,n-1,g-n+3,h),g=n+h.length-p-2;break}g=-1;for(;++g-1?void 0:4)}},exit:function(e){e.exit("blockQuote")}};e.exports=a},function(e,t,n){"use strict";var i=n(676),r={name:"characterEscape",tokenize:function(e,t,n){return function(t){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(t),e.exit("escapeMarker"),r};function r(r){return i(r)?(e.enter("characterEscapeValue"),e.consume(r),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(r)}}};e.exports=r},function(e,t,n){"use strict";var i=n(72)(/[!-/:-@[-`{-~]/);e.exports=i},function(e,t,n){"use strict";var i=n(285),r=n(139),a=n(286),o=n(678);function s(e){return e&&"object"===typeof e&&"default"in e?e:{default:e}}var l=s(i),c={name:"characterReference",tokenize:function(e,t,n){var i,s,c=this,u=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),f};function f(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),i=31,s=r,h(t))}function d(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=o,h):(e.enter("characterReferenceValue"),i=7,s=a,h(t))}function h(a){var o;return 59===a&&u?(o=e.exit("characterReferenceValue"),s!==r||l.default(c.sliceSerialize(o))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)):s(a)&&u++-1?void 0:4);function a(t){return e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),l(t)}function l(t){return t===s?(e.consume(t),r++,l):ra&&"whitespace"===e[r][1].type&&(r-=2);"atxHeadingSequence"===e[r][1].type&&(a===r-1||r-4>a&&"whitespace"===e[r-2][1].type)&&(r-=a+1===r?2:4);r>a&&(n={type:"atxHeadingText",start:e[a][1].start,end:e[r][1].end},i={type:"chunkText",start:e[a][1].start,end:e[r][1].end,contentType:"text"},o(e,a,r-a+1,[["enter",n,t],["enter",i,t],["exit",i,t],["exit",n,t]]));return e}};e.exports=l},function(e,t,n){"use strict";var i=n(193),r=n(139),a=n(22),o=n(71),s=n(62),l=n(136),c=n(686),u=n(687),f=n(137),d={name:"htmlFlow",tokenize:function(e,t,n){var f,d,p,g,_,m=this;return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),F};function F(r){return 33===r?(e.consume(r),b):47===r?(e.consume(r),k):63===r?(e.consume(r),f=3,m.interrupt?t:U):i(r)?(e.consume(r),p=l(r),d=!0,E):n(r)}function b(r){return 45===r?(e.consume(r),f=2,y):91===r?(e.consume(r),f=5,p="CDATA[",g=0,v):i(r)?(e.consume(r),f=4,m.interrupt?t:U):n(r)}function y(i){return 45===i?(e.consume(i),m.interrupt?t:U):n(i)}function v(i){return i===p.charCodeAt(g++)?(e.consume(i),g===p.length?m.interrupt?t:N:v):n(i)}function k(t){return i(t)?(e.consume(t),p=l(t),E):n(t)}function E(i){return null===i||47===i||62===i||o(i)?47!==i&&d&&u.indexOf(p.toLowerCase())>-1?(f=1,m.interrupt?t(i):N(i)):c.indexOf(p.toLowerCase())>-1?(f=6,47===i?(e.consume(i),w):m.interrupt?t(i):N(i)):(f=7,m.interrupt?n(i):d?T(i):C(i)):45===i||r(i)?(e.consume(i),p+=l(i),E):n(i)}function w(i){return 62===i?(e.consume(i),m.interrupt?t:N):n(i)}function C(t){return s(t)?(e.consume(t),C):M(t)}function T(t){return 47===t?(e.consume(t),M):58===t||95===t||i(t)?(e.consume(t),x):s(t)?(e.consume(t),T):M(t)}function x(t){return 45===t||46===t||58===t||95===t||r(t)?(e.consume(t),x):D(t)}function D(t){return 61===t?(e.consume(t),S):s(t)?(e.consume(t),D):T(t)}function S(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),_=t,A):s(t)?(e.consume(t),S):(_=void 0,O(t))}function A(t){return t===_?(e.consume(t),I):null===t||a(t)?n(t):(e.consume(t),A)}function O(t){return null===t||34===t||39===t||60===t||61===t||62===t||96===t||o(t)?D(t):(e.consume(t),O)}function I(e){return 47===e||62===e||s(e)?T(e):n(e)}function M(t){return 62===t?(e.consume(t),P):n(t)}function P(t){return s(t)?(e.consume(t),P):null===t||a(t)?N(t):n(t)}function N(t){return 45===t&&2===f?(e.consume(t),B):60===t&&1===f?(e.consume(t),L):62===t&&4===f?(e.consume(t),z):63===t&&3===f?(e.consume(t),U):93===t&&5===f?(e.consume(t),H):!a(t)||6!==f&&7!==f?null===t||a(t)?R(t):(e.consume(t),N):e.check(h,z,R)(t)}function R(t){return e.exit("htmlFlowData"),j(t)}function j(t){return null===t?K(t):a(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),j):(e.enter("htmlFlowData"),N(t))}function B(t){return 45===t?(e.consume(t),U):N(t)}function L(t){return 47===t?(e.consume(t),p="",q):N(t)}function q(t){return 62===t&&u.indexOf(p.toLowerCase())>-1?(e.consume(t),z):i(t)&&p.length<8?(e.consume(t),p+=l(t),q):N(t)}function H(t){return 93===t?(e.consume(t),U):N(t)}function U(t){return 62===t?(e.consume(t),z):N(t)}function z(t){return null===t||a(t)?(e.exit("htmlFlowData"),K(t)):(e.consume(t),z)}function K(n){return e.exit("htmlFlow"),t(n)}},resolveTo:function(e){var t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2));return e},concrete:!0},h={tokenize:function(e,t,n){return function(i){return e.exit("htmlFlowData"),e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),e.attempt(f,t,n)}},partial:!0};e.exports=d},function(e,t,n){"use strict";e.exports=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","section","source","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"]},function(e,t,n){"use strict";e.exports=["pre","script","style","textarea"]},function(e,t,n){"use strict";var i=n(193),r=n(139),a=n(22),o=n(71),s=n(62),l=n(23),c={name:"htmlText",tokenize:function(e,t,n){var c,u,f,d,h=this;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),p};function p(t){return 33===t?(e.consume(t),g):47===t?(e.consume(t),D):63===t?(e.consume(t),T):i(t)?(e.consume(t),O):n(t)}function g(t){return 45===t?(e.consume(t),_):91===t?(e.consume(t),u="CDATA[",f=0,v):i(t)?(e.consume(t),C):n(t)}function _(t){return 45===t?(e.consume(t),m):n(t)}function m(t){return null===t||62===t?n(t):45===t?(e.consume(t),F):b(t)}function F(e){return null===e||62===e?n(e):b(e)}function b(t){return null===t?n(t):45===t?(e.consume(t),y):a(t)?(d=b,L(t)):(e.consume(t),b)}function y(t){return 45===t?(e.consume(t),H):b(t)}function v(t){return t===u.charCodeAt(f++)?(e.consume(t),f===u.length?k:v):n(t)}function k(t){return null===t?n(t):93===t?(e.consume(t),E):a(t)?(d=k,L(t)):(e.consume(t),k)}function E(t){return 93===t?(e.consume(t),w):k(t)}function w(t){return 62===t?H(t):93===t?(e.consume(t),w):k(t)}function C(t){return null===t||62===t?H(t):a(t)?(d=C,L(t)):(e.consume(t),C)}function T(t){return null===t?n(t):63===t?(e.consume(t),x):a(t)?(d=T,L(t)):(e.consume(t),T)}function x(e){return 62===e?H(e):T(e)}function D(t){return i(t)?(e.consume(t),S):n(t)}function S(t){return 45===t||r(t)?(e.consume(t),S):A(t)}function A(t){return a(t)?(d=A,L(t)):s(t)?(e.consume(t),A):H(t)}function O(t){return 45===t||r(t)?(e.consume(t),O):47===t||62===t||o(t)?I(t):n(t)}function I(t){return 47===t?(e.consume(t),H):58===t||95===t||i(t)?(e.consume(t),M):a(t)?(d=I,L(t)):s(t)?(e.consume(t),I):H(t)}function M(t){return 45===t||46===t||58===t||95===t||r(t)?(e.consume(t),M):P(t)}function P(t){return 61===t?(e.consume(t),N):a(t)?(d=P,L(t)):s(t)?(e.consume(t),P):I(t)}function N(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,R):a(t)?(d=N,L(t)):s(t)?(e.consume(t),N):(e.consume(t),c=void 0,B)}function R(t){return t===c?(e.consume(t),j):null===t?n(t):a(t)?(d=R,L(t)):(e.consume(t),R)}function j(e){return 62===e||47===e||o(e)?I(e):n(e)}function B(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):62===t||o(t)?I(t):(e.consume(t),B)}function L(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),l(e,q,"linePrefix",h.parser.constructs.disable.null.indexOf("codeIndented")>-1?void 0:4)}function q(t){return e.enter("htmlTextData"),d(t)}function H(i){return 62===i?(e.consume(i),e.exit("htmlTextData"),e.exit("htmlText"),t):n(i)}}};e.exports=c},function(e,t,n){"use strict";var i={name:"labelStartImage",tokenize:function(e,t,n){var i=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),r};function r(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),a):n(t)}function a(e){return 94===e&&"_hiddenFootnoteSupport"in i.parser.constructs?n(e):t(e)}},resolveAll:n(194).resolveAll};e.exports=i},function(e,t,n){"use strict";var i={name:"labelStartLink",tokenize:function(e,t,n){var i=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),r};function r(e){return 94===e&&"_hiddenFootnoteSupport"in i.parser.constructs?n(e):t(e)}},resolveAll:n(194).resolveAll};e.exports=i},function(e,t,n){"use strict";var i=n(23),r={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),i(e,t,"linePrefix")}}};e.exports=r},function(e,t,n){"use strict";var i=n(286),r=n(62),a=n(138),o=n(281),s=n(23),l=n(137),c=n(291),u={name:"list",tokenize:function(e,t,n){var s=this,u=a(s.events,"linePrefix"),d=0;return function(t){var r=s.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===r?!s.containerState.marker||t===s.containerState.marker:i(t)){if(s.containerState.type||(s.containerState.type=r,e.enter(r,{_container:!0})),"listUnordered"===r)return e.enter("listItemPrefix"),42===t||45===t?e.check(c,n,p)(t):p(t);if(!s.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),h(t)}return n(t)};function h(t){return i(t)&&++d<10?(e.consume(t),h):(!s.interrupt||d<2)&&(s.containerState.marker?t===s.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),p(t)):n(t)}function p(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||t,e.check(l,s.interrupt?n:g,e.attempt(f,m,_))}function g(e){return s.containerState.initialBlankLine=!0,u++,m(e)}function _(t){return r(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),m):n(t)}function m(n){return s.containerState.size=u+o(s.sliceStream(e.exit("listItemPrefix"))),t(n)}},continuation:{tokenize:function(e,t,n){var i=this;return i.containerState._closeFlow=void 0,e.check(l,(function(n){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,s(e,t,"listItemIndent",i.containerState.size+1)(n)}),(function(n){if(i.containerState.furtherBlankLines||!r(n))return i.containerState.furtherBlankLines=i.containerState.initialBlankLine=void 0,a(n);return i.containerState.furtherBlankLines=i.containerState.initialBlankLine=void 0,e.attempt(d,t,a)(n)}));function a(r){return i.containerState._closeFlow=!0,i.interrupt=void 0,s(e,e.attempt(u,t,n),"linePrefix",i.parser.constructs.disable.null.indexOf("codeIndented")>-1?void 0:4)(r)}}},exit:function(e){e.exit(this.containerState.type)}},f={tokenize:function(e,t,n){var i=this;return s(e,(function(e){return r(e)||!a(i.events,"listItemPrefixWhitespace")?n(e):t(e)}),"listItemPrefixWhitespace",i.parser.constructs.disable.null.indexOf("codeIndented")>-1?void 0:5)},partial:!0},d={tokenize:function(e,t,n){var i=this;return s(e,(function(e){return a(i.events,"listItemIndent")===i.containerState.size?t(e):n(e)}),"listItemIndent",i.containerState.size+1)},partial:!0};e.exports=u},function(e,t,n){"use strict";var i=n(22),r=n(96),a=n(23),o={name:"setextUnderline",tokenize:function(e,t,n){var r,o,s=this,l=s.events.length;for(;l--;)if("lineEnding"!==s.events[l][1].type&&"linePrefix"!==s.events[l][1].type&&"content"!==s.events[l][1].type){o="paragraph"===s.events[l][1].type;break}return function(t){if(!s.lazy&&(s.interrupt||o))return e.enter("setextHeadingLine"),e.enter("setextHeadingLineSequence"),r=t,c(t);return n(t)};function c(t){return t===r?(e.consume(t),c):(e.exit("setextHeadingLineSequence"),a(e,u,"lineSuffix")(t))}function u(r){return null===r||i(r)?(e.exit("setextHeadingLine"),t(r)):n(r)}},resolveTo:function(e,t){var n,i,a,o,s=e.length;for(;s--;)if("enter"===e[s][0]){if("content"===e[s][1].type){n=s;break}"paragraph"===e[s][1].type&&(i=s)}else"content"===e[s][1].type&&e.splice(s,1),a||"definition"!==e[s][1].type||(a=s);o={type:"setextHeading",start:r(e[i][1].start),end:r(e[e.length-1][1].end)},e[i][1].type="setextHeadingText",a?(e.splice(i,0,["enter",o,t]),e.splice(a+1,0,["exit",e[n][1],t]),e[n][1].end=r(e[a][1].end)):e[n][1]=o;return e.push(["exit",o,t]),e}};e.exports=o},function(e,t,n){"use strict";var i=/[\0\t\n\r]/g;e.exports=function(){var e,t=!0,n=1,r="";return function(a,o,s){var l,c,u,f,d,h=[];a=r+a.toString(o),u=0,r="",t&&(65279===a.charCodeAt(0)&&u++,t=void 0);for(;u":""))+")");return g;function g(){var r,h,p=d.concat(i),g=[];if((!t||u(i,f,d[d.length-1]||null))&&(g=function(e){if(null!==e&&"object"===typeof e&&"length"in e)return e;if("number"===typeof e)return[a,e];return[e]}(n(i,d)),g[0]===s))return g;if(i.children&&g[0]!==o)for(h=(l?i.children.length:-1)+c;h>-1&&h0&&u.children.unshift(i("text"," ")),u.children.unshift(e(null,"input",{type:"checkbox",checked:t.checked,disabled:!0})),d.className=["task-list-item"]);o=c.length,s=-1;for(;++s1:t}},function(e,t,n){"use strict";e.exports=function(e,t){return e(t,"p",i(e,t))};var i=n(29)},function(e,t,n){"use strict";e.exports=function(e,t){return e.augment(t,i("root",r(a(e,t))))};var i=n(42),r=n(111),a=n(29)},function(e,t,n){"use strict";e.exports=function(e,t){return e(t,"strong",i(e,t))};var i=n(29)},function(e,t,n){"use strict";e.exports=function(e,t){var n,o,s,l,c,u=t.children,f=u.length,d=t.align||[],h=d.length,p=[];for(;f--;){for(o=u[f].children,l=0===f?"th":"td",n=h||o.length,s=[];n--;)c=o[n],s[n]=e(c,l,{align:d[n]},c?a(e,c):[]);p[f]=e(u[f],"tr",r(s,!0))}return e(t,"table",r([e(p[0].position,"thead",r([p[0]],!0))].concat(p[1]?e({start:i.start(p[1]),end:i.end(p[p.length-1])},"tbody",r(p.slice(1),!0)):[]),!0))};var i=n(292),r=n(111),a=n(29)},function(e,t,n){"use strict";e.exports=function(e,t){return e.augment(t,i("text",String(t.value).replace(/[ \t]*(\r?\n|\r)[ \t]*/g,"$1")))};var i=n(42)},function(e,t,n){"use strict";var i=n(298),r=n(300),a=n(304),o=n(305),s=n(308),l=n(727);e.exports=i([a,r,o,s,l])},function(e,t){e.exports=function(){for(var e={},t=0;t