amazon-connect-streams
Version:
Amazon Connect Streams Library
1 lines • 627 kB
JavaScript
(()=>{var e={781:(e,t,n)=>{"use strict";let r;function o(e){if(!r)throw new Error(null!=e?e:"Attempted to get Global AmazonConnectProvider that has not been set.");return r}function i(){return"randomUUID"in crypto?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>{const t=parseInt(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}))}n.r(t),n.d(t,{AmazonConnectStreamsSite:()=>_});class a{constructor(){this.idsByHandler=new Map,this.handlersById=new Map}add(e){const t=this.idsByHandler.get(e);if(t)return{handlerId:t};const n=i();return this.idsByHandler.set(e,n),this.handlersById.set(n,e),{handlerId:n}}getIdByHandler(e){var t;return null!==(t=this.idsByHandler.get(e))&&void 0!==t?t:null}getHandlerById(e){var t;return null!==(t=this.handlersById.get(e))&&void 0!==t?t:null}get(){return[...this.idsByHandler.entries()].map((([e,t])=>({handler:e,handlerId:t})))}delete(e){const t=this.idsByHandler.get(e);return t&&this.handlersById.delete(t),this.idsByHandler.delete(e),{isEmpty:this.idsByHandler.size<1}}size(){return this.idsByHandler.size}}class s{constructor(){this.simpleSubscriptions=new Map,this.paramSubscriptions=new Map}add({namespace:e,key:t,parameter:n},r){var o,i,a,s,c;if(n){if(!this.paramSubscriptions.has(e))return void this.paramSubscriptions.set(e,new Map([[t,new Map([[n,r]])]]));if(!(null===(o=this.paramSubscriptions.get(e))||void 0===o?void 0:o.has(t)))return void(null===(i=this.paramSubscriptions.get(e))||void 0===i||i.set(t,new Map([[n,r]])));null===(s=null===(a=this.paramSubscriptions.get(e))||void 0===a?void 0:a.get(t))||void 0===s||s.set(n,r)}else{if(!this.simpleSubscriptions.has(e))return void this.simpleSubscriptions.set(e,new Map([[t,r]]));null===(c=this.simpleSubscriptions.get(e))||void 0===c||c.set(t,r)}}delete({namespace:e,key:t,parameter:n}){var r,o,i,a;n?(null===(o=null===(r=this.paramSubscriptions.get(e))||void 0===r?void 0:r.get(t))||void 0===o?void 0:o.delete(n))&&this.paramSubscriptions.get(e).get(t).size<1&&(null===(i=this.paramSubscriptions.get(e))||void 0===i||i.delete(t),this.paramSubscriptions.get(e).size<1&&this.paramSubscriptions.delete(e)):(null===(a=this.simpleSubscriptions.get(e))||void 0===a?void 0:a.delete(t))&&this.simpleSubscriptions.get(e).size<1&&this.simpleSubscriptions.delete(e)}get({namespace:e,key:t,parameter:n}){var r,o,i;return n?null===(i=null===(o=this.paramSubscriptions.get(e))||void 0===o?void 0:o.get(t))||void 0===i?void 0:i.get(n):null===(r=this.simpleSubscriptions.get(e))||void 0===r?void 0:r.get(t)}getOrAdd(e,t){let n=this.get(e);return n||(n=t(),this.add(e,n)),n}addOrUpdate(e,t,n){let r=this.get(e);return r=r?n(r):t(),this.add(e,r),r}getAllSubscriptions(){return[...Array.from(this.simpleSubscriptions.keys()).flatMap((e=>Array.from(this.simpleSubscriptions.get(e).keys()).flatMap((t=>({namespace:e,key:t}))))),...Array.from(this.paramSubscriptions.keys()).flatMap((e=>Array.from(this.paramSubscriptions.get(e).keys()).flatMap((t=>Array.from(this.paramSubscriptions.get(e).get(t).keys()).flatMap((n=>({namespace:e,key:t,parameter:n})))))))]}}class c{constructor(){this.subscriptions=new s}add(e,t){return this.subscriptions.getOrAdd(e,(()=>new a)).add(t)}get(e){var t,n;return null!==(n=null===(t=this.subscriptions.get(e))||void 0===t?void 0:t.get())&&void 0!==n?n:[]}getById(e,t){var n,r;return null!==(r=null===(n=this.subscriptions.get(e))||void 0===n?void 0:n.getHandlerById(t))&&void 0!==r?r:null}delete(e,t){var n,r;null!==(r=null===(n=this.subscriptions.get(e))||void 0===n?void 0:n.delete(t).isEmpty)&&void 0!==r&&r&&this.subscriptions.delete(e)}size(e){var t,n;return null!==(n=null===(t=this.subscriptions.get(e))||void 0===t?void 0:t.size())&&void 0!==n?n:0}isEmpty(e){return 0===this.size(e)}getAllSubscriptions(){return this.subscriptions.getAllSubscriptions()}getAllSubscriptionHandlerIds(){return this.subscriptions.getAllSubscriptions().reduce(((e,t)=>e.concat(this.get(t).map((({handlerId:e})=>({topic:t,handlerId:e}))))),[])}}class u extends Error{constructor({reason:e,namespace:t,errorKey:n,details:r}){super(`ConnectError with error key "${n}"`),this.errorType=u.ErrorType,this.namespace=t,this.errorKey=n,this.reason=e,this.details=null!=r?r:{}}}u.ErrorType="ConnectError";const l="clientTimeout";function p(e,t,n,r){const o=Math.max(1,null!=r?r:3e4);return new Promise(((r,i)=>{let a=!1;const s=setTimeout((()=>{n({timeoutMs:o,request:e}),i(function(e,t){const{namespace:n,command:r,data:o}=e;return{namespace:n,reason:"Client Timeout",details:{command:r,requestData:o,timeoutMs:t},errorKey:l}}(e,o)),a=!0}),o);t((e=>{clearTimeout(s),a||(e.isError?i(new u(e)):r(e.data))}))}))}class d{constructor(e){this.requestMap=new Map,this.logger=new T({provider:e,source:"core.requestManager"})}processRequest(e){const{requestId:t}=e;return p(e,(e=>this.requestMap.set(t,e)),(({request:e,timeoutMs:t})=>this.handleTimeout(e,t)))}processResponse(e){const{requestId:t}=e,n=this.requestMap.get(t);n?(n(e),this.requestMap.delete(t)):this.logger.error("Returned a response message with no handler",{message:e})}handleTimeout(e,t){const{requestId:n,namespace:r,command:o}=e;this.requestMap.delete(n),this.logger.error("Client request timeout",{requestId:n,namespace:r,command:o,timeoutMs:t})}}var f=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};function h(e){try{switch(e.type){case"acknowledge":case"error":case"childConnectionClose":default:return e;case"childDownstreamMessage":return Object.assign(Object.assign({},e),{message:h(e.message)});case"publish":{const{data:t}=e,n=f(e,["data"]);return Object.assign({},n)}case"response":if(e.isError)return Object.assign(Object.assign({},e),{details:{command:e.details.command}});{const{data:t}=e,n=f(e,["data"]);return Object.assign({},n)}}}catch(t){return{messageDetails:"error when sanitizing downstream message",message:e,error:t}}}class g{constructor(e,t){this.provider=e,this.relayChildUpstreamMessage=t,this.messagePorts=new Map,this.logger=new T({provider:e,source:"childConnectionManager"})}addChannel({connectionId:e,port:t,providerId:n}){if(this.messagePorts.has(e))return void this.logger.error("Attempted to add child connection that already exists. No action",{connectionId:e});const r=this.createMessageHandler(e,n);t.addEventListener("message",r),t.start(),this.messagePorts.set(e,{port:t,handler:r,providerId:n}),this.relayChildUpstreamMessage({type:"childUpstream",connectionId:e,sourceProviderId:n,parentProviderId:this.provider.id,message:{type:"childConnectionReady"}}),this.logger.debug("Child port added",{connectionId:e})}handleDownstreamMessage({connectionId:e,message:t,targetProviderId:n}){const r=this.messagePorts.get(e);if(!r)return void this.logger.warn("Attempted to route downstream message to child message port that does not exist",{connectionId:e,message:h(t)});const{port:o,providerId:i}=r;i&&i!==n?this.logger.error("Downstream target message did not match target provider id. Not sending message.",{connectionId:e,targetProviderId:n,actualProviderId:i,message:h(t)}):o.postMessage(t)}handleCloseMessage({connectionId:e}){const t=this.messagePorts.get(e);if(!t)return void this.logger.warn("Attempted to close child message port that was not found",{connectionId:e});const{port:n,handler:r}=t;n.removeEventListener("message",r),n.close(),this.messagePorts.delete(e),this.logger.debug("Removed child message channel",{connectionId:e})}createMessageHandler(e,t){return n=>this.relayChildUpstreamMessage({type:"childUpstream",sourceProviderId:t,parentProviderId:this.provider.id,connectionId:e,message:n.data})}}class m{constructor(e){this.errorHandlers=new Set,this.logger=new T({provider:e,source:"core.proxy.error"})}invoke(e){const{message:t,key:n,details:r,isFatal:o,connectionStatus:i}=e;this.logger.error(t,{key:n,details:r,isFatal:o,connectionStatus:i},{duplicateMessageToConsole:!0,remoteIgnore:!0}),[...this.errorHandlers].forEach((t=>{try{t(e)}catch(t){this.logger.error("An error occurred within a AmazonConnectErrorHandler",{handlerError:t,originalError:e})}}))}onError(e){this.errorHandlers.add(e)}offError(e){this.errorHandlers.delete(e)}}class v{constructor(e){this.status="notConnected",this.changeHandlers=new Set,this.logger=new T({source:"core.proxy.connection-status-manager",provider:e,mixin:()=>({status:this.status})})}getStatus(){return this.status}update(e){this.status=e.status,this.logger.trace("Proxy Connection Status Changed",{status:e.status}),[...this.changeHandlers].forEach((t=>{try{t(e)}catch(e){this.logger.error("An error occurred within a ProxyConnectionChangedHandler",{error:e})}}))}onChange(e){this.changeHandlers.add(e)}offChange(e){this.changeHandlers.delete(e)}}var y,b=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))},E=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};class S{constructor(e){this.provider=e,this.logger=new T({source:"core.proxy",provider:e,mixin:()=>({proxyType:this.proxyType,connectionId:this.connectionId})}),this.requestManager=new d(e),this.status=new v(e),this.errorService=new m(e),this.upstreamMessageQueue=[],this.connectionEstablished=!1,this.isInitialized=!1,this.subscriptions=new c,this.connectionId=null,this.channelManager=new g(e,this.sendOrQueueMessageToSubject.bind(this))}init(){if(this.isInitialized)throw new Error("Proxy already initialized");this.isInitialized=!0,this.initProxy()}request(e,t,n,r){const o=function(e,t,n,r){return{type:"request",namespace:e,command:t,requestId:i(),data:n,messageOrigin:r}}(e,t,n,null!=r?r:this.getUpstreamMessageOrigin()),a=this.requestManager.processRequest(o);return this.sendOrQueueMessageToSubject(o),a}subscribe(e,t,n){const{handlerId:r}=this.subscriptions.add(e,t),o={type:"subscribe",topic:e,messageOrigin:null!=n?n:this.getUpstreamMessageOrigin(),handlerId:r};this.sendOrQueueMessageToSubject(o)}unsubscribe(e,t,n){if(this.subscriptions.delete(e,t),this.subscriptions.isEmpty(e)){const t={type:"unsubscribe",topic:e,messageOrigin:null!=n?n:this.getUpstreamMessageOrigin()};this.sendOrQueueMessageToSubject(t)}}log(e){const t=function({level:e,source:t,message:n,loggerId:r,data:o},i,a){const s=o?JSON.parse(JSON.stringify(o)):void 0;return{type:"log",level:e,time:new Date,source:t,message:n,loggerId:r,data:s,context:i,messageOrigin:a}}(e,this.addContextToLogger(),this.getUpstreamMessageOrigin());this.sendOrQueueMessageToSubject(t)}sendLogMessage(e){"log"===e.type?(e.context=Object.assign(Object.assign({},e.context),this.addContextToLogger()),this.sendOrQueueMessageToSubject(e)):this.logger.error("Attempted to send invalid log message",{message:e})}sendMetric({metricData:e,time:t,namespace:n}){const r=function({metricData:e,time:t,namespace:n},r){var o,i;return{type:"metric",namespace:n,metricName:e.metricName,unit:e.unit,value:e.value,time:t,dimensions:null!==(o=e.dimensions)&&void 0!==o?o:{},optionalDimensions:null!==(i=e.optionalDimensions)&&void 0!==i?i:{},messageOrigin:r}}({metricData:e,time:t,namespace:n},this.getUpstreamMessageOrigin());this.sendOrQueueMessageToSubject(r)}sendMetricMessage(e){"metric"===e.type?this.sendOrQueueMessageToSubject(e):this.logger.error("Attempted to send invalid metric message",{metricMessage:e})}sendOrQueueMessageToSubject(e){this.connectionEstablished?this.sendMessageToSubject(e):this.upstreamMessageQueue.push(e)}consumerMessageHandler(e){if(!this.isInitialized)return void this.logger.error("Attempted to process message from subject prior to proxy being initializing. Message not processed",{originalMessageEventData:e.data});const{data:t}=e;if(!("type"in t))return void this.logger.warn("Unknown inbound message",{originalMessageEventData:t});const n=t;this.handleMessageFromSubject(n)}handleMessageFromSubject(e){this.handleDefaultMessageFromSubject(e)}handleDefaultMessageFromSubject(e){switch(e.type){case"acknowledge":this.handleConnectionAcknowledge(e);break;case"response":this.handleResponse(e);break;case"publish":this.handlePublish(e);break;case"error":this.handleError(e);break;case"childDownstreamMessage":this.channelManager.handleDownstreamMessage(e);break;case"childConnectionClose":this.channelManager.handleCloseMessage(e);break;default:return void this.logger.error("Unknown inbound message",{originalMessageEventData:e})}}handleConnectionAcknowledge(e){for(this.connectionId=e.connectionId,this.status.update({status:"ready",connectionId:e.connectionId}),this.connectionEstablished=!0;this.upstreamMessageQueue.length;){const e=this.upstreamMessageQueue.shift();this.sendMessageToSubject(e)}}handleResponse(e){this.requestManager.processResponse(e)}handlePublish(e){const{handlerId:t,topic:n}=e;if(t){const r=this.subscriptions.getById(n,t);r&&this.handleAsyncSubscriptionHandlerInvoke({handler:r,handlerId:t},e)}else this.subscriptions.get(n).map((t=>{this.handleAsyncSubscriptionHandlerInvoke(t,e)}))}handleError(e){if(e.isFatal){const{message:t,type:n}=e,r=E(e,["message","type"]);this.status.update({status:"error",reason:t,details:r})}this.publishError({message:e.message,key:e.key,details:e.details,isFatal:e.isFatal,proxyStatus:e.status})}publishError(e){const t=Object.assign(Object.assign({},e),{connectionStatus:this.connectionStatus});this.errorService.invoke(t)}handleAsyncSubscriptionHandlerInvoke(e,t){return b(this,arguments,void 0,(function*({handler:e,handlerId:t},{topic:n,data:r}){try{yield e(r)}catch(e){this.logger.error("An error occurred when handling subscription",{topic:n,error:e,handlerId:t})}}))}get connectionStatus(){return this.status.getStatus()}onError(e){this.errorService.onError(e)}offError(e){this.errorService.offError(e)}onConnectionStatusChange(e){this.status.onChange(e)}offConnectionStatusChange(e){this.status.offChange(e)}addChildChannel(e){this.channelManager.addChannel(e)}resetConnection(e){var t;this.connectionEstablished=!1,this.status.update({status:"reset",reason:e});const n=this.subscriptions.getAllSubscriptionHandlerIds();this.logger.info("Resetting proxy",{reason:e,subscriptionHandlerCount:null!==(t=null==n?void 0:n.length)&&void 0!==t?t:-1}),null==n||n.map((({topic:e,handlerId:t})=>({type:"subscribe",topic:e,messageOrigin:this.getUpstreamMessageOrigin(),handlerId:t}))).forEach((e=>this.sendOrQueueMessageToSubject(e)))}}class C{constructor({config:e,proxyFactory:t}){if(this._id=i(),!t)throw new Error("Attempted to get Proxy before setting up factory");if(!e)throw new Error("Failed to include config");this.proxyFactory=t,this._config=e}get id(){return this._id}getProxy(){return this.proxy||(this.proxy=this.proxyFactory(this),this.proxy.init()),this.proxy}get config(){return Object.assign({},this._config)}onError(e){this.getProxy().onError(e)}offError(e){this.getProxy().offError(e)}static initializeProvider(e){const t=new T({source:"core.amazonConnect.init",provider:e});if(this.isInitialized){const e="Error: Attempted to initialize provider more than one time.";throw t.error(e),new Error(e)}return function(e){if(r)throw new Error("Global Provider is already set");r=e}(e),this.isInitialized=!0,e.getProxy(),e}}C.isInitialized=!1,function(e){e[e.trace=1]="trace",e[e.debug=2]="debug",e[e.info=3]="info",e[e.warn=4]="warn",e[e.error=5]="error"}(y||(y={}));class I{constructor(e){this.mixin=e}getTransformedData(e,t){return this.mixin?Object.assign(Object.assign({},null!=t?t:{}),this.mixin(null!=t?t:{},e)):t}}class T{constructor(e){this._proxy=null,this._logToConsoleLevel=null,this.loggerId=function(e){const t=new Uint8Array(Math.ceil(e/2));return crypto.getRandomValues(t),Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("").substring(0,e)}(8),"string"==typeof e?(this.source=e,this.dataTransformer=new I(void 0)):(this.source=e.source,e.provider&&"function"==typeof e.provider?this.providerFactory=e.provider:this.provider=e.provider,this.dataTransformer=new I(e.mixin),this.logOptions=e.options)}trace(e,t,n){this.log(y.trace,e,t,n)}debug(e,t,n){this.log(y.debug,e,t,n)}info(e,t,n){this.log(y.info,e,t,n)}warn(e,t,n){this.log(y.warn,e,t,n)}error(e,t,n){this.log(y.error,e,t,n)}log(e,t,n,r){const o=this.dataTransformer.getTransformedData(e,n);this.ignoreRemote(r)||this.getProxy().log({level:e,source:this.source,loggerId:this.loggerId,message:t,data:o}),this.applyDuplicateMessageToConsole(e,r)&&function(e,t,n){if(n)switch(e){case y.error:console.error(t,n);break;case y.warn:console.warn(t,n);break;case y.info:console.info(t,n);break;case y.debug:console.debug(t,n);break;case y.trace:console.trace(t,n);break;default:console.log(t,n)}else switch(e){case y.error:console.error(t);break;case y.warn:console.warn(t);break;case y.info:console.info(t);break;case y.debug:console.debug(t);break;case y.trace:console.trace(t);break;default:console.log(t)}}(e,t,o)}getProvider(){return this.provider||(this.provider=this.providerFactory?this.providerFactory():o()),this.provider}getProxy(){return this._proxy||(this._proxy=this.getProvider().getProxy()),this._proxy}applyDuplicateMessageToConsole(e,t){return(null==t?void 0:t.duplicateMessageToConsole)||this.getLogConsoleLevel()<=e}getLogConsoleLevel(){var e,t,n,r;return this._logToConsoleLevel||(this._logToConsoleLevel=(null===(e=this.logOptions)||void 0===e?void 0:e.minLogToConsoleLevelOverride)?this.logOptions.minLogToConsoleLevelOverride:null!==(r=null===(n=null===(t=this.getProvider().config)||void 0===t?void 0:t.logging)||void 0===n?void 0:n.minLogToConsoleLevel)&&void 0!==r?r:y.error),this._logToConsoleLevel}ignoreRemote(e){var t,n,r;return null!==(n=null===(t=this.logOptions)||void 0===t?void 0:t.remoteIgnore)&&void 0!==n&&n||null!==(r=null==e?void 0:e.remoteIgnore)&&void 0!==r&&r}}class w extends S{constructor(e){super(e),this.postMessageHandler=this.listenForInitialMessage.bind(this),this.proxyLogger=new T({source:"siteProxy",provider:e})}initProxy(){this.status.update({status:"connecting"}),window.addEventListener("message",this.postMessageHandler)}resetConnection(e){super.resetConnection(e),this.messagePort=void 0,this.status.update({status:"connecting"})}sendMessageToSubject(e){this.messagePort?this.messagePort.postMessage(e):this.proxyLogger.error("Failed to send UpstreamMessage. MessagePort not set",{messageType:e.type})}addContextToLogger(){return{}}listenForInitialMessage(e){if(this.verifyEventSource(e)){if(!this.verifyOrigin(e))return;if("cross-domain-adapter-init"!==e.data.type)return void this.invalidInitMessageHandler(e.data);if(this.messagePort&&(this.resetConnection("Subsequent Message Port Detected"),this.proxyLogger.info("Subsequent message port received. Resetting connection")),this.messagePort=e.ports[0],!this.messagePort)throw new Error("message port not provided by iframe");this.messagePort.onmessage=this.consumerMessageHandler.bind(this),this.status.update({status:"initializing"}),this.messagePort.postMessage({type:"cross-domain-site-ready",providerId:this.provider.id}),this.proxyLogger.debug("CDA Post message handler removed")}}verifyOrigin(e){const t=e.origin;if(!t)return this.proxyLogger.warn("No origin provided in event. Ignoring event."),!1;let n;try{n=new URL(this.provider.config.instanceUrl).origin}catch(e){return this.proxyLogger.error("Unable to parse expected origin from config. Cannot match",{error:e,eventOrigin:t,configInstanceUrl:this.provider.config.instanceUrl},{duplicateMessageToConsole:!0}),!1}return t===n||("cross-domain-adapter-init"===e.data.type&&this.proxyLogger.warn("Origin of message with type 'cross-domain-adapter-init' did not expected instance value. Ignoring",{expectedOrigin:n,eventOrigin:t},{duplicateMessageToConsole:!0}),!1)}}class A extends w{constructor(e){super(e),this.ccpIFrame=null}get proxyType(){return"streams-site"}setCCPIframe(e){const t=Boolean(this.ccpIFrame);this.ccpIFrame=e,t&&this.resetConnection("CCP IFrame Updated")}getUpstreamMessageOrigin(){return Object.assign({_type:"streams-site",providerId:this.provider.id},{origin:null!==(t=null===(e=null===document||void 0===document?void 0:document.location)||void 0===e?void 0:e.origin)&&void 0!==t?t:"unknown",path:null!==(r=null===(n=null===document||void 0===document?void 0:document.location)||void 0===n?void 0:n.pathname)&&void 0!==r?r:"unknown"});var e,t,n,r}verifyEventSource(e){const t=this.ccpIFrame;if(!t)return this.proxyLogger.error("CCP Iframe not provided to proxy. Unable to verify event to Connect to CCP.",{origin:e.origin}),!1;const n=e.source===t.contentWindow;return n||this.proxyLogger.warn("Message came from unexpected iframe. Not a valid CCP. Will not connect",{origin:e.origin}),n}invalidInitMessageHandler(){}}class _ extends C{constructor(e){super({config:e,proxyFactory:e=>new A(e)})}static init(e){const t=new _(e);return _.initializeProvider(t),{provider:t}}static get default(){return o("AmazonConnectStreamsSite has not been initialized")}setCCPIframe(e){this.getProxy().setCCPIframe(e)}}},825:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t,e.lily=t,t.agentApp={};var n={CCP:"ccp",GUIDES:"customviews"};t.agentApp.initCCP=t.core.initCCP,t.agentApp.isInitialized=function(e){},t.agentApp.initAppCommunication=function(e,n){var r=document.getElementById(e),o=new t.IFrameConduit(n,window,r),i=[t.AgentEvents.UPDATE,t.ContactEvents.VIEW,t.EventType.ACKNOWLEDGE,t.EventType.TERMINATED,t.TaskEvents.CREATED,t.EmailEvents.CREATED];r.addEventListener("load",(function(e){i.forEach((function(e){t.core.getUpstream().onUpstream(e,(function(t){o.sendUpstream(e,t)}))}))}))};var r=function(e){var t=e.indexOf("ccp-v2");return e.slice(0,t-1)},o=function(e){if("string"==typeof e)return e;try{return e.getContactId()}catch(t){return void console.error("[CustomViews]: Invalid Contact Provided: ",e)}};t.agentApp.initApp=function(e,i,a,s){s=s||{};var c,u=a.endsWith("/")||/[?&]?[^=?&]+=[^=?&]+/g.test(a)?a:a+"/",l=s.onLoad?s.onLoad:null,p={endpoint:u,style:s.style,onLoad:l};if(e===n.CCP_DR)c=n.CCP;else if(e===n.GUIDES&&s.customViewsParams){var d=s.customViewsParams.iframeSuffix;if(c=d?"".concat(n.GUIDES).concat(d):"".concat(n.GUIDES),void 0!==t.agentApp.AppRegistry.get(c))throw new Error("[CustomViews]: Custom views application with the same name already exists. Please provide a different iframeSuffix for the custom views application.")}else c=e;var f="string"==typeof i?document.getElementById(i):i;t.agentApp.AppRegistry.register(c,p,f),t.agentApp.AppRegistry.start(c,(function(i){var a=i.endpoint,u=i.containerDOM;return{init:function(){switch(e){case n.CCP:return s.ccpParams=s.ccpParams?s.ccpParams:{},s.style&&(s.ccpParams.style=s.style),function(e,n,o){var i={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:r(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1,allowFramedVideoCall:!0,allowFramedScreenSharing:!0,allowFramedScreenSharingPopUp:!1}},a=t.merge(i,o.ccpParams);t.core.initCCP(n,a)}(a,u,s);case n.GUIDES:return void 0!==s.customViewsParams?(t.agentApp.initAppCommunication(c,a,u),function(e,r,i){var a,s,c=i.customViewsParams,u=c.contact,l=c.disableAutoDestroy,p=c.iframeSuffix,d=c.terminateCustomViewOptions,f=void 0===d?{}:d,h=i.customViewsParams.contactFlowId;void 0!==u&&((a=o(u))&&!0!==l&&"string"!=typeof u&&u.onDestroy((function(n){t.core.terminateCustomView(e,p,{timeout:f.timeout||5e3,hideIframe:void 0===f.hideIframe||f.hideIframe,resolveIframe:void 0===f.resolveIframe||f.resolveIframe})})),h||console.warn("[CustomViews]: Need to provide a contactFlowId when defining contact parameter for initalizing customviews application")),s=p?"".concat(n.GUIDES).concat(p):"".concat(n.GUIDES);var g="iframe[id='".concat(s,"']"),m=(null==r?void 0:r.querySelector(g))||document.getElementById(s)||window.top.document.getElementById(s);if(!m)throw new Error("[CustomViews]: No iframe found for the app: ",s);var v=AWS.util.uuid.v4();a?m.src="".concat(e,"?contactFlowId=").concat(h,"¤tContactId=").concat(a,"&agentAppTabId=").concat(v,"-tab"):h&&(m.src="".concat(e,"?contactFlowId=").concat(h,"&agentAppTabId=").concat(v,"-tab"))}(a,u,s)):t.agentApp.initAppCommunication(c,a,u);default:return t.agentApp.initAppCommunication(c,a,u)}},destroy:function(){switch(e){case n.CCP:return i=r(a)+"/logout",t.fetch(i,{credentials:"include"}).then((function(){return t.core.getEventBus().trigger(t.EventType.TERMINATE),!0})).catch((function(e){return t.getLog().error("An error occured on logout."+e).withException(e),window.location.href=i,!1}));case n.GUIDES:return void 0!==s.customViewsParams?(o=c,void t.agentApp.AppRegistry.delete(o)):null;default:return null}var o,i}}}))},t.agentApp.stopApp=function(e){return t.agentApp.AppRegistry.stop(e)}}()},961:()=>{!function(){var e=this||globalThis,t=e.connect||{};e.connect=t;var n,r="ccp";e.connect.agentApp.AppRegistry=(n={},{register:function(e,t,r){n[e]={containerDOM:r,endpoint:t.endpoint,style:t.style,instance:void 0,onLoad:t.onLoad}},start:function(e,t){if(n[e]){var o=n[e].containerDOM,i=n[e].endpoint,a=n[e].style,s=n[e].onLoad;if(e!==r){var c=function(e,t,n,r){var o=document.createElement("iframe");return o.src=t,o.style=n||"width: 100%; height:100%;",o.id=e,o["aria-label"]=e,o.onload=r,o.allow="clipboard-read; clipboard-write",o.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),o}(e,i,a,s);o.appendChild(c)}return n[e].instance=t(n[e]),n[e].instance.init()}},get:function(e){return n[e]},delete:function(e){delete n[e]},stop:function(e){if(n[e]){var t,r=n[e],o=r.containerDOM.querySelector("iframe");if(e.includes("customviews")){var i="iframe[id='".concat(e,"']");o=r.containerDOM.querySelector(i)}return r.containerDOM.removeChild(o),r.instance&&(t=r.instance.destroy(),delete r.instance),t}}})}()},610:()=>{function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{};n%2?e(Object(r),!0).forEach((function(e){p(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,i,a,s=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){u=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw o}}return s}}(e,t)||s(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return r="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},r(e)}function o(){"use strict";o=function(){return t};var e,t={},n=Object.prototype,i=n.hasOwnProperty,a=Object.defineProperty||function(e,t,n){e[t]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function p(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{p({},"")}catch(e){p=function(e,t,n){return e[t]=n}}function d(e,t,n,r){var o=t&&t.prototype instanceof b?t:b,i=Object.create(o.prototype),s=new N(r||[]);return a(i,"_invoke",{value:R(e,n,s)}),i}function f(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var h="suspendedStart",g="suspendedYield",m="executing",v="completed",y={};function b(){}function E(){}function S(){}var C={};p(C,c,(function(){return this}));var I=Object.getPrototypeOf,T=I&&I(I(P([])));T&&T!==n&&i.call(T,c)&&(C=T);var w=S.prototype=b.prototype=Object.create(C);function A(e){["next","throw","return"].forEach((function(t){p(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function n(o,a,s,c){var u=f(e[o],e,a);if("throw"!==u.type){var l=u.arg,p=l.value;return p&&"object"==r(p)&&i.call(p,"__await")?t.resolve(p.__await).then((function(e){n("next",e,s,c)}),(function(e){n("throw",e,s,c)})):t.resolve(p).then((function(e){l.value=e,s(l)}),(function(e){return n("throw",e,s,c)}))}c(u.arg)}var o;a(this,"_invoke",{value:function(e,r){function i(){return new t((function(t,o){n(e,r,t,o)}))}return o=o?o.then(i,i):i()}})}function R(t,n,r){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var c=O(s,r);if(c){if(c===y)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===h)throw o=v,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=m;var u=f(t,n,r);if("normal"===u.type){if(o=r.done?v:g,u.arg===y)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(o=v,r.method="throw",r.arg=u.arg)}}}function O(t,n){var r=n.method,o=t.iterator[r];if(o===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,O(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=f(o,t.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,y;var a=i.arg;return a?a.done?(n[t.resultName]=a.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,y):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,y)}function L(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function N(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(L,this),this.reset(!0)}function P(t){if(t||""===t){var n=t[c];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,a=function n(){for(;++o<t.length;)if(i.call(t,o))return n.value=t[o],n.done=!1,n;return n.value=e,n.done=!0,n};return a.next=a}}throw new TypeError(r(t)+" is not iterable")}return E.prototype=S,a(w,"constructor",{value:S,configurable:!0}),a(S,"constructor",{value:E,configurable:!0}),E.displayName=p(S,l,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===E||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,S):(e.__proto__=S,p(e,l,"GeneratorFunction")),e.prototype=Object.create(w),e},t.awrap=function(e){return{__await:e}},A(_.prototype),p(_.prototype,u,(function(){return this})),t.AsyncIterator=_,t.async=function(e,n,r,o,i){void 0===i&&(i=Promise);var a=new _(d(e,n,r,o),i);return t.isGeneratorFunction(n)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},A(w),p(w,l,"Generator"),p(w,c,(function(){return this})),p(w,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=P,N.prototype={constructor:N,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(k),!t)for(var n in this)"t"===n.charAt(0)&&i.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function r(r,o){return s.type="throw",s.arg=t,n.next=r,o&&(n.method="next",n.arg=e),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var c=i.call(a,"catchLoc"),u=i.call(a,"finallyLoc");if(c&&u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=e,a.arg=t,o?(this.method="next",this.next=o.finallyLoc,y):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),y},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),k(n),y}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;k(n)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:P(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),y}},t}function i(e,t,n,r,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,o)}function a(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function s(e){i(a,r,o,s,c,"next",e)}function c(e){i(a,r,o,s,c,"throw",e)}s(void 0)}))}}function s(e,t){if(e){if("string"==typeof e)return c(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(e,t):void 0}}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,d(r.key),r)}}function l(e,t,n){return t&&u(e.prototype,t),n&&u(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function p(e,t,n){return(t=d(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(e){var t=function(e,t){if("object"!=r(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=r(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==r(t)?t:t+""}!function(){var e=this||globalThis,i=e.connect||{};e.connect=i,e.lily=i,i.AgentStateType=i.makeEnum(["init","routable","not_routable","offline","system","error"]),i.AgentStatusType=i.AgentStateType,i.AgentAvailStates=i.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),i.AgentErrorStates=i.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),i.EndpointType=i.makeEnum(["phone_number","agent","queue"]),i.AddressType=i.EndpointType,i.ConnectionType=i.makeEnum(["agent","inbound","outbound","monitoring"]),i.ConnectionStateType=i.makeEnum(["init","connecting","connected","hold","disconnected","silent_monitor","barge"]),i.ConnectionStatusType=i.ConnectionStateType,i.CONNECTION_ACTIVE_STATES=i.set([i.ConnectionStateType.CONNECTING,i.ConnectionStateType.CONNECTED,i.ConnectionStateType.HOLD,i.ConnectionStateType.SILENT_MONITOR,i.ConnectionStateType.BARGE]),i.CONNECTION_CONNECTED_STATES=i.set([i.ConnectionStateType.CONNECTED,i.ConnectionStateType.SILENT_MONITOR,i.ConnectionStateType.BARGE]),i.ContactStateType=i.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended","rejected","paused"]),i.ContactStatusType=i.ContactStateType,i.CONTACT_ACTIVE_STATES=i.makeEnum(["paused","incoming","pending","connecting","connected"]),i.ContactType=i.makeEnum(["voice","queue_callback","chat","task","email"]),i.ContactInitiationMethod=i.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect","webrtc_api","agent_reply"]),i.MonitoringMode=i.makeEnum(["SILENT_MONITOR","BARGE"]),i.MonitoringErrorTypes=i.makeEnum(["invalid_target_state"]),i.ChannelType=i.makeEnum(["VOICE","CHAT","TASK"]),i.MediaType=i.makeEnum(["softphone","chat","task","email"]),i.SoftphoneCallType=i.makeEnum(["audio_video","video_only","audio_only","none"]),i.SoftphoneErrorTypes=i.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","vdi_strategy_not_supported","vdi_redir_not_supported","other"]),i.ClickType=i.makeEnum(["Accept","Reject","Hangup"]),i.VoiceIdErrorTypes=i.makeEnum(["no_speaker_id_found","speaker_id_not_enrolled","get_speaker_id_failed","get_speaker_status_failed","opt_out_speaker_failed","opt_out_speaker_in_lcms_failed","delete_speaker_failed","start_session_failed","evaluate_speaker_failed","session_not_exists","describe_session_failed","enroll_speaker_failed","update_speaker_id_failed","update_speaker_id_in_lcms_failed","not_supported_on_conference_calls","enroll_speaker_timeout","evaluate_speaker_timeout","get_domain_id_failed","no_domain_id_found"]),i.CTIExceptions=i.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),i.VoiceIdStreamingStatus=i.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),i.VoiceIdAuthenticationDecision=i.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),i.VoiceIdFraudDetectionDecision=i.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),i.ContactFlowAuthenticationDecision=i.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),i.ContactFlowFraudDetectionDecision=i.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),i.CustomerAuthenticationStatus=i.makeEnum(["AUTHENTICATED","FAILED","TIMEOUT"]),i.VideoCapability=i.makeEnum(["SEND"]),i.ScreenShareCapability=i.makeEnum(["SEND"]),i.VoiceIdEnrollmentRequestStatus=i.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),i.VoiceIdSpeakerStatus=i.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),i.VoiceIdConstants={EVALUATE_SESSION_DELAY:1e4,EVALUATION_MAX_POLL_TIMES:24,EVALUATION_POLLING_INTERVAL:5e3,ENROLLMENT_MAX_POLL_TIMES:120,ENROLLMENT_POLLING_INTERVAL:5e3,START_SESSION_DELAY:8e3},i.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId"};var c=l((function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}));p(c,"isEnabled",(function(){var e=i.isCRM()?i.core.getClient():i.core.getApiProxyClient();return new Promise((function(t,n){e.call(i.ApiProxyClientMethods.QR_INTEGRATION_EXISTS,null,{success:function(e){i.getLog().info("Quick Responses isEnabled succeeded").withObject(e).sendInternalLogToServer(),t(e)},failure:function(e){i.getLog().error("Quick Responses isEnabled failed").withException(e).sendInternalLogToServer(),n(e)}})}))})),p(c,"searchQuickResponses",(function(e){var n=i.isCRM()?i.core.getClient():i.core.getApiProxyClient(),r=null!=e&&e.contactId?new f(e.contactId).getAttributes():void 0;return new Promise((function(o,a){n.call(i.ApiProxyClientMethods.QR_SEARCH_QUICK_RESPONSES,t(t({},e),{},{attributes:r}),{success:function(e){i.getLog().info("searchQuickResponses succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){i.getLog().error("searchQuickResponses failed").withException(e).sendInternalLogToServer(),a(e)}})}))}));var u=function(){if(!i.agent.initialized)throw new i.StateError("The agent is not yet initialized!")};u.prototype._getData=function(){return i.core.getAgentDataProvider().getAgentData()},u.prototype._createContactAPI=function(e){return new i.Contact(e.contactId)},u.prototype.onRefresh=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.REFRESH,e)},u.prototype.onRoutable=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.ROUTABLE,e)},u.prototype.onNotRoutable=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.NOT_ROUTABLE,e)},u.prototype.onOffline=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.OFFLINE,e)},u.prototype.onError=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.ERROR,e)},u.prototype.onSoftphoneError=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.SOFTPHONE_ERROR,e)},u.prototype.onWebSocketConnectionLost=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},u.prototype.onWebSocketConnectionGained=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},u.prototype.onAfterCallWork=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.ACW,e)},u.prototype.onStateChange=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.STATE_CHANGE,e)},u.prototype.onMuteToggle=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.MUTE_TOGGLE,e)},u.prototype.onLocalMediaStreamCreated=function(e){return i.core.getEventBus().subscribe(i.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},u.prototype.onSpeakerDeviceChanged=function(e){return i.core.getEventBus().subscribe(i.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},u.prototype.onMicrophoneDeviceChanged=function(e){return i.core.getEventBus().subscribe(i.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},u.prototype.onRingerDeviceChanged=function(e){return i.core.getEventBus().subscribe(i.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},u.prototype.onCameraDeviceChanged=function(e){return i.core.getEventBus().subscribe(i.ConfigurationEvents.CAMERA_DEVICE_CHANGED,e)},u.prototype.onBackgroundBlurChanged=function(e){return i.core.getEventBus().subscribe(i.ConfigurationEvents.BACKGROUND_BLUR_CHANGED,e)},u.prototype.mute=function(){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.EventType.MUTE,data:{mute:!0}})},u.prototype.unmute=function(){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.EventType.MUTE,data:{mute:!1}})},u.prototype.setSpeakerDevice=function(e){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},u.prototype.setMicrophoneDevice=function(e){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},u.prototype.setRingerDevice=function(e){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},u.prototype.setCameraDevice=function(e){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.ConfigurationEvents.CAMERA_DEVICE_CHANGED,data:{deviceId:e}})},u.prototype.setBackgroundBlur=function(e){i.core.getUpstream().sendUpstream(i.EventType.BROADCAST,{event:i.ConfigurationEvents.BACKGROUND_BLUR_CHANGED,data:{isBackgroundBlurEnabled:e}})},u.prototype.getState=function(){return this._getData().snapshot.state},u.prototype.getNextState=function(){return this._getData().snapshot.nextState},u.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},u.prototype.getStatus=u.prototype.getState,u.prototype.getStateDuration=function(){return i.now()-this._getData().snapshot.state.startTimestamp.getTime()+i.core.getSkew()},u.prototype.getStatusDuration=u.prototype.getStateDuration,u.prototype.getPermissions=function(){return this.getConfiguration().permissions},u.prototype.getContacts=function(e){var t=this;return this._getData().snapshot.contacts.map((function(e){return t._createContactAPI(e)})).filter((function(t){return!e||t.getType()===e}))},u.prototype.getConfiguration=function(){return this._getData().configuration},u.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},u.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},u.prototype.getChannelConcurrency=function(e){var t=this.getRoutingProfile().channelConcurrencyMap;return t||(t=Object.keys(i.ChannelType).reduce((function(e,t){return"TASK"!==t&&(e[i.ChannelType[t]]=1),e}),{})),e?t[e]||0:t},u.prototype.getName=function(){return this.getConfiguration().name},u.prototype.getAgentARN=function(){return this.getConfiguration().agentARN},u.prototype.getExtension=function(){return this.getConfiguration().extension},u.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},u.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},u.prototype.setConfiguration=function(e,t){var n=i.core.getClient();e&&e.agentPreferences&&e.agentPreferences.LANGUAGE&&!e.agentPreferences.locale&&(e.agentPreferences.locale=e.agentPreferences.LANGUAGE),e&&e.agentPreferences&&!i.isValidLocale(e.agentPreferences.locale)?t&&t.failure&&t.failure(i.AgentErrorStates.INVALID_LOCALE):n.call(i.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:i.assertNotNull(e,"configuration")},{success:function(e){i.core.getUpstream().sendUpstream(i.EventType.RELOAD_AGENT_CONFIGURATION),t.success&&t.success(e)},failure:t&&t.failure})},u.prototype.setState=function(e,t,n){i.core.getClient().call(i.ClientMethods.PUT_AGENT_STATE,{state:i.assertNotNull(e,"state"),enqueueNextState:n&&!!n.enqueueNextState},t)},u.prototype.onEnqueuedNextState=function(e){i.core.getEventBus().subscribe(i.AgentEvents.ENQUEUED_NEXT_STATE,e)},u.prototype.setStatus=u.prototype.setState,u.prototype.connect=function(e,t){var n=i.core.getClient(),r=new i.Endpoint(e);delete r.endpointId;var o={endpoint:i.assertNotNull(r,"endpoint"),queueARN:t&&(t.queueARN||t.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN};t&&t.relatedContactId&&null!==t.relatedContactId&&(o.relatedContactId=t.relatedContactId,t.previousContactId&&delete o.previousContactId),n.call(i.ClientMethods.CREATE_OUTBOUND_CONTACT,o,t&&{success:t.success,failure:t.failure})},u.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map((function(e){return e.queueARN}))},u.prototype.getEndpoints=function(e,t,n){var r=this,o=i.core.getClient();i.assertNotNull(t,"callbacks"),i.assertNotNull(t.success,"callbacks.success");var a=n||{};a.endpoints=a.endpoints||[],a.maxResults=a.maxResults||i.DEFAULT_BATCH_SIZE,i.isArray(e)||(e=[e]),o.call(i.ClientMethods.GET_ENDPOINTS,{queueARNs:e,nextToken:a.nextToken||null,maxResults:a.maxResults},{success:function(n){if(n.nextToken)r.getEndpoints(e,t,{nextToken:n.nextToken,maxResults:a.maxResults,endpoints:a.endpoints.concat(n.endpoints)});else{a.endpoints=a.endpoints.concat(n.endpoints);var o=a.endpoints.map((function(e){return new i.Endpoint(e)}));t.success({endpoints:o,addresses:o})}},failure:t.failure})},u.prototype.getAddresses=u.prototype.getEndpoints,u.prototype._getResourceId=function(){var e,t=this.getAllQueueARNs(),n=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=s(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(t);try{for(n.s();!(e=n.n()).done;){var r=e.value.match(/\/agent\/([^/]+)/);if(r)return r[1]}}catch(e){n.e(e)}finally{n.f()}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",t)},u.prototype.toSnapshot=function(){return new i.AgentSnapshot(this._getData())};var d=function(e){i.Agent.call(this),this.agentData=e};(d.prototype=Object.create(u.prototype)).constructor=d,d.prototype._getData=function(){return this.agentData},d.prototype._createContactAPI=function(e){return new i.ContactSnapshot(e)};var f=function(e){this.contactId=e};f.prototype._getData=function(){return i.core.getAgentDataProvider().getContactData(this.getContactId())},f.prototype._createConnectionAPI=function(e){return this.getType()===i.ContactType.CHAT?new i.ChatConnection(this.contactId,e.connectionId):this.getType()=