From 4000972d7bcca7f782f05f74c44a774f9c07363d Mon Sep 17 00:00:00 2001 From: shishkev <88100722+shishkev@users.noreply.github.com> Date: Wed, 8 Jun 2022 12:47:00 -0400 Subject: [PATCH] Task templates APIs support and other improvements. (#573) * [VoiceId] Invoke a callback when sufficient audio has been collected * [N+ Conferencing] Unlock N+ features for deskphone agents * updated documentation for view contact * rebasing Streams/mainline * add addNamespaceToLogs utility function * Backoff reloads on 401s. Introduce new events relating to the authorize api * fixing iframe metrics * [LongPoll Deprecation] introduce the longPollingOptions object into initSharedWorker's params and the shared worker's ClientEngine class props * pass addNamespaceToLogs param on connect.EventType.CONFIGURE, remove from connect.agentApp.initApp * adding try-catch around err.stack.split * updated to keep array type in all cases * fixed the order of type checks * Emit number of ccp browser tabs metric on tab event * [Task Templates] Streams update * fix agent.setConfiguration's bug that doesn't support a parameter at agentPreferences.LANGUAGE * refactor unit tests * remove setSoftphoneUserMediaStream call from SoftphoneManager to prevent one way audio issue * Fix console error from emitting tab count metric * document shouldAddNamespaceToLogs initCCP param * document scenarios where onViewContact callback is invoked * add note about how onAccepted doesn't fire for auto-accepted contacts * address git comments * Enable styling to be set from initCCP params * Code cleaning --- CHANGELOG.md | 8 + Documentation.md | 94 ++- README.md | 2 + package-lock.json | 612 +++------------ package.json | 2 +- release/connect-streams-min.js | 2 +- release/connect-streams.js | 700 ++++++++++++++++-- src/agent-app/agent-app.js | 6 +- src/api.js | 34 +- src/aws-client.js | 18 +- src/client.js | 109 ++- src/core.js | 220 +++++- src/event.js | 6 +- src/index.d.ts | 30 +- src/lib/amazon-connect-websocket-manager.js | 2 +- .../amazon-connect-websocket-manager.js.map | 2 +- src/log.js | 15 +- src/softphone.js | 1 - src/util.js | 14 + src/worker.js | 96 ++- test/unit/agent-app.spec.js | 36 + test/unit/agent.spec.js | 116 +++ test/unit/connections.spec.js | 15 +- test/unit/core.spec.js | 593 ++++++++++++--- test/unit/softphone.spec.js | 43 -- test/unit/voiceid.spec.js | 26 + test/unit/worker.spec.js | 72 ++ 27 files changed, 2069 insertions(+), 805 deletions(-) create mode 100644 test/unit/agent.spec.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 940ab0a6..490461d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # CHANGELOG.md +## 2.2.0 +Added functions: +* `contact.getChannelContext` method to get the channel context for the contact. See Documentation.md for more details +* `connect.core.onAuthorizationSuccess`. See Documentation.md for more details +* `connect.core.onAuthorizeRetriesExhausted` and `connect.core.onCTIAuthorizeRetriesExhausted` methods, along with some backoff logic to the retries / page reloads for the CTI and authorize apis. Please see these methods' entries in Documentation.md for more information. + +Added support for Task templates APIs. + ## 2.1.0 Added functions: * `contact.isMultiPartyConferenceEnabled` method to determine whether this contact is a softphone call and multiparty conference feature is turned on. See Documentation.md for more details diff --git a/Documentation.md b/Documentation.md index 1506f7c0..76163fbf 100644 --- a/Documentation.md +++ b/Documentation.md @@ -199,6 +199,7 @@ everything set up correctly and that you are able to listen for events. enableAudioDeviceSettings: false, //optional, defaults to 'false' enablePhoneTypeSettings: true //optional, defaults to 'true' }, + shouldAddNamespaceToLogs: false, //optional, defaults to 'false' ccpAckTimeout: 5000, //optional, defaults to 3000 (ms) ccpSynTimeout: 3000, //optional, defaults to 1000 (ms) ccpLoadTimeout: 10000 //optional, defaults to 5000 (ms) @@ -251,6 +252,7 @@ and made available to your JS client code. displayed. * `enablePhoneTypeSettings`: If `true`, or if `pageOptions` is not provided, the settings tab will display a section for configuring the agent's phone type and deskphone number. If `false`, the agent will not be able to change the phone type or deskphone number from the settings tab. +* `shouldAddNamespaceToLogs`: prepends `[CCP]` to all logs logged by the CCP. Important note: there are a few logs made by the CCP before the namespace is prepended. * `ccpAckTimeout`: A timeout in ms that indicates how long streams will wait for the iframed CCP to respond to its `SYNCHRONIZE` event emissions. These happen continuously from the first time `initCCP` is called. They should only appear when there is a problem that requires a refresh or a re-login. * `ccpSynTimeout`: A timeout in ms that indicates how long streams will wait to send a new `SYNCHRONIZE` event to the iframed CCP. These happens continuously from the first time `initCCP` is called. * `ccpLoadTimeout`: A timeout in ms that indicates how long streams will wait for the initial `ACKNOWLEDGE` event from the shared worker while the CCP is still standing itself up. @@ -293,6 +295,30 @@ connect.core.onIframeRetriesExhausted(() => { ``` Subscribes a callback function to be called when the iframe failed to load, after attempting all retries. An Iframe Retry (refresh of the iframe page) is scheduled whenever there is a `connect.EventType.ACK_TIMEOUT`. If a `connect.EventType.ACKNOWLEDGE` event happens before the scheduled retry, the retry is cancelled. We allow for 6 scheduled retries. Once these are exhausted, `connect.EventType.ACK_TIMEOUT` events do not trigger scheduled retries. +### `connect.core.onAuthorizeSuccess()` +```js +connect.core.onAuthorizeSuccess(() => { + console.log("authorization succeeded! Hooray"); +}); +``` +Subscribes a callback function to be called when the agent authorization api succeeds. + +### `connect.core.onCTIAuthorizeRetriesExhausted()` +```js +connect.core.onCTIAuthorizeRetriesExhausted(() => { + console.log("We have failed CTI API authorization multiple times and we are out of retries"); +}); +``` +Subscribes a callback function to be called when multiple authorization-type CTI API failures have happened. After this event occurs, streams will not try to re-authenticate the user when more CTI API authorization-type (401) failures happen. Note that CTI APIs are the agent, contact, and connection apis (specifically, those listed under the `connect.ClientMethods` enum). Therefore, it may be prudent to indicate to the agent that there is a problem related to authorization. + +### `connect.core.onAuthorizeRetriesExhausted()` +```js +connect.core.onAuthorizeRetriesExhausted(() => { + console.log("We have failed the agent authorization api multiple times and we are out of retries"); +}); +``` +Subscribes a callback function to be called when multiple agent authorization api failures have happened. After this event occurs, streams will not try to redirect the user to login when more agent authorization api failures happen. Therefore, it may be prudent to indicate to the agent that there is a problem related to authorization. + ### `connect.core.terminate()` ```js var containerDiv = document.getElementById("containerDiv"); @@ -325,6 +351,21 @@ connect.core.onViewContact(function(event) { Subscribes a callback that starts whenever the currently selected contact on the CCP changes. The callback is called when the contact changes in the UI (i.e. via `click` events) or via `connect.core.viewContact()`. +More precisely, `onViewContact` is called in the below scenarios: + +1. There is a new incoming contact, and there are no other contacts currently open in CCP. This includes both outbound contacts and contacts that are accepted using auto-accept +2. A contact is closed and there is at least one other open contact + 1. CCP will call `onViewContact` with the next contact in the list of contacts +3. A contact has been selected as the active contact in CCP. This can happen in multiple ways + 1. An agent clicks on that contact’s tab in native or embedded CCP + 2. CCP will trigger `onViewContact` when the close contact button is clicked in native or embedded CCP. CCP will call `onViewContact` with the next contact in the list of contacts. Note that this is redundant with scenario 2 and will result in `onViewContact` being called twice. +4. A new contact has been accepted using the accept contact button in native or embedded CCP +5. `connect.core.viewContact` is called in your custom implementation +6. There are some cases when `onViewContact` is called with an empty string. This denotes that the active contact has been unset. That happens in the following scenarios: + 1. The close contact button is clicked and there are no other active contacts + 2. An agent clicks on a new channel in CCP + 1. Note: in this case `onViewContact` will be called with a contact from the newly selected channel shortly after + ### `connect.core.onAuthFail()` ```js connect.core.onAuthFail(function() { /* ... */ }); @@ -806,7 +847,7 @@ Subscribe a method to be invoked when the contact is connecting. This event happ ```js contact.onAccepted(function(contact) { /* ... */ }); ``` -Subscribe a method to be invoked whenever the contact is accepted. +Subscribe a method to be invoked whenever the contact is accepted. Please note that event doesn't fire for contacts that are auto-accepted. ### `contact.onMissed()` ```js @@ -1128,6 +1169,21 @@ Gets references for the contact. A sample reference looks like the following: } ``` +### `contact.getChannelContext()` +```js +var channelContext = contact.getChannelContext(); +``` +Gets the channel context for the contact. For task contacts the channel context contains `scheduledTime`, `taskTemplateId`, `taskTemplateVersion` properties. It might look like the following: + +```js +{ + scheduledTime: 1646609220 + taskTemplateId: "ba6db758-d31e-4c6c-bd51-14d8b4686ece" + taskTemplateVersion: 1 +} +``` + + ## Connection API The Connection API provides action methods (no event subscriptions) which can be called to manipulate the state @@ -1474,12 +1530,24 @@ This enumeration lists all of the contact types supported by Connect Streams. This is a list of some of the special event types which are published into the low-level `EventBus`. -* `EventType.ACKNOWLEDGE`: Event received when the backend API shared worker acknowledges the current tab. +* `EventType.ACKNOWLEDGE`: Event received when the backend API shared worker acknowledges the current tab. More specifically, it is sent to Streams in the following scenarios: + - a consumer port connects to the shared worker + - when Streams sends the `EventType.SYNCHRONIZE` to the shared worker, the shared worker sends the `ACKNOWLEDGE` event back. This happens every few seconds so that Streams and the shared worker are synchronized. * `EventType.ACK_TIMEOUT`: Event which is published if the backend API shared worker fails to respond to an `EventType.SYNCHRONIZE` event in a timely manner, meaning that the tab or window has been disconnected from the shared worker. * `EventType.IFRAME_RETRIES_EXHAUSTED`: Event which is published once the hard limit of 6 CCP retries are all exhausted. These retries are tiggered by the `ACK_TIMEOUT` event above. * `EventType.AUTH_FAIL`: Event published indicating that the most recent API call returned a status header indicating that the current user authentication is no longer valid. This usually requires the user to log in again for the CCP to continue to function. See `connect.core.initCCP()` under **Initialization** for more information about automatic login popups which can be used to give the user the chance to log in again when this happens. * `EventType.LOG`: An event published whenever the CCP or the API shared worker creates a log entry. -* `EventType.TERMINATED`: Event published when the agent logged out from ccp. +* `EventType.TERMINATED`: When the `EventType.TERMINATE` (not `TERMINATED`) event is sent to Streams, it is forwarded to the shared worker, which on successful termination then sends `EventType.TERMINATED` event back to Streams. The `EventType.TERMINATE` event is sent to Streams in the following scenarios: + - The CCP is initialized as an agent app (via `connect.agentApp.initApp`), and `connect.agentApp.stopApp` is invoked + - The user manually logs out of the CCP + +### `AgentEvents` +Event types that affect the agent's state. + +* `AgentEvents.UPDATE`: this event is sent to Streams in the following scenarios: + - a consumer port connects to the shared worker + - when the shared worker or ccp is first initialized, then again repeated every few seconds + - when the `EventType.RELOAD_AGENT_CONFIGURATION` event is sent to the shared worker. This happens in the `Agent.prototype.setConfiguration` method (which is invoked when the ccp settings are saved in the UI) #### Note The `EventBus` is used by the high-level subscription APIs to manage subscriptions @@ -1705,20 +1773,30 @@ voiceConnection.getVoiceIdSpeakerStatus() ``` -### `voiceConnection.enrollSpeakerInVoiceId()` -Enrolls a customer in Voice ID. The enrollment process completes once the backend has collected enough speech data (30 seconds of net customer's audio). If after 10 minutes the process hasn't completed, the method will throw a timeout error. If you call this API for a customer who is already enrolled, it will re-enroll the customer by collecting new speech data and registering a new digital voiceprint. Enrollment can happen only once in a voice contact. +### `voiceConnection.enrollSpeakerInVoiceId(callbackOnAudioCollectionComplete)` +Enrolls a customer in Voice ID. The enrollment process completes once the backend has collected enough speech data (30 seconds of net customer's audio). If after 10 minutes the process hasn't completed, the method will throw a timeout error. If you call this API for a customer who is already enrolled, it will re-enroll the customer by collecting new speech data and registering a new digital voiceprint. Enrollment can happen only once in a voice contact. +You can pass in a callback (optional) that will be invoked when our backend has collected sufficient audio for our backend service to create the new voiceprint. ```js -voiceConnection.enrollSpeakerInVoiceId() +const callbackOnAudioCollectionComplete = (data) => { + console.log( + `Now sufficient audio has been collected and + the customer no longer needs to keep talking. + The backend service is creating the voiceprint with the audio collected` + ); +}; + +voiceConnection.enrollSpeakerInVoiceId(callbackOnAudioCollectionComplete) .then((data) => { - // it returns session data but no additional actions needed + console.log( + `The enrollment process is complete and the customer has been enrolled into Voice ID` + ); }) .catch((err) => { console.error(err); }); ``` - ### `voiceConnection.evaluateSpeakerWithVoiceId(boolean)` Checks the customer's Voice ID verification status. The evaluation process completes once the backend has collected enough speech data (10 seconds of net customer's audio). If after 2 minutes the process hasn't completed, the method will throw a timeout error. If you pass in false, it uses the existing audio stream, which is typically started in the contact flow, and immediately returns the result if enough audio has already been collected. If you pass in true, it starts a new audio stream and returns the result when enough audio has been collected. The default value is false. diff --git a/README.md b/README.md index 30ad1851..bb3b4cb9 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,7 @@ everything setup correctly and that you will be able to listen for events. enableAudioDeviceSettings: false, //optional, defaults to 'false' enablePhoneTypeSettings: true //optional, defaults to 'true' }, + shouldAddNamespaceToLogs: false, //optional, defaults to 'false' ccpAckTimeout: 5000, //optional, defaults to 3000 (ms) ccpSynTimeout: 3000, //optional, defaults to 1000 (ms) ccpLoadTimeout: 10000 //optional, defaults to 5000 (ms) @@ -244,6 +245,7 @@ and made available to your JS client code. displayed. * `enablePhoneTypeSettings`: If `true`, or if `pageOptions` is not provided, the settings tab will display a section for configuring the agent's phone type and deskphone number. If `false`, the agent will not be able to change the phone type or deskphone number from the settings tab. +* `shouldAddNamespaceToLogs`: prepends `[CCP]` to all logs logged by the CCP. Important note: there are a few logs made by the CCP before the namespace is prepended. * `ccpAckTimeout`: A timeout in ms that indicates how long streams will wait for the iframed CCP to respond to its `SYNCHRONIZE` event emissions. These happen continuously from the first time `initCCP` is called. They should only appear when there is a problem that requires a refresh or a re-login. * `ccpSynTimeout`: A timeout in ms that indicates how long streams will wait to send a new `SYNCHRONIZE` event to the iframed CCP. These happens continuously from the first time `initCCP` is called. * `ccpLoadTimeout`: A timeout in ms that indicates how long streams will wait for the initial `ACKNOWLEDGE` event from the shared worker while the CCP is still standing itself up. diff --git a/package-lock.json b/package-lock.json index c5595d39..c3bbc3af 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,11 @@ { "name": "amazon-connect-streams", - "version": "2.1.1", + "version": "2.2.0", "lockfileVersion": 1, "requires": true, "dependencies": { "@ampproject/remapping": { "version": "2.1.2", - "resolved": false, "integrity": "sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg==", "dev": true, "requires": { @@ -15,7 +14,6 @@ }, "@babel/code-frame": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", "dev": true, "requires": { @@ -23,38 +21,35 @@ } }, "@babel/compat-data": { - "version": "7.17.0", - "resolved": false, - "integrity": "sha512-392byTlpGWXMv4FbyWw3sAZ/FrW/DrwqLGXpy0mbyNe9Taqv1mg9yON5/o0cnr8XYCkFTZbC1eV+c+LAROgrng==", + "version": "7.17.7", + "integrity": "sha512-p8pdE6j0a29TNGebNm7NzYZWB3xVZJBZ7XGs42uAKzQo8VQ3F0By/cQCtUEABwIqw5zo6WA4NbmxsfzADzMKnQ==", "dev": true }, "@babel/core": { - "version": "7.17.5", - "resolved": false, - "integrity": "sha512-/BBMw4EvjmyquN5O+t5eh0+YqB3XXJkYD2cjKpYtWOfFy4lQ4UozNSmxAcWT8r2XtZs0ewG+zrfsqeR15i1ajA==", + "version": "7.17.9", + "integrity": "sha512-5ug+SfZCpDAkVp9SFIZAzlW18rlzsOcJGaetCjkySnrXXDUw9AR8cDUm1iByTmdWM6yxX6/zycaV76w3YTF2gw==", "dev": true, "requires": { "@ampproject/remapping": "^2.1.0", "@babel/code-frame": "^7.16.7", - "@babel/generator": "^7.17.3", - "@babel/helper-compilation-targets": "^7.16.7", - "@babel/helper-module-transforms": "^7.16.7", - "@babel/helpers": "^7.17.2", - "@babel/parser": "^7.17.3", + "@babel/generator": "^7.17.9", + "@babel/helper-compilation-targets": "^7.17.7", + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helpers": "^7.17.9", + "@babel/parser": "^7.17.9", "@babel/template": "^7.16.7", - "@babel/traverse": "^7.17.3", + "@babel/traverse": "^7.17.9", "@babel/types": "^7.17.0", "convert-source-map": "^1.7.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", - "json5": "^2.1.2", + "json5": "^2.2.1", "semver": "^6.3.0" } }, "@babel/generator": { - "version": "7.17.3", - "resolved": false, - "integrity": "sha512-+R6Dctil/MgUsZsZAkYgK+ADNSZzJRRy0TvY65T71z/CR854xHQ1EweBYXdfT+HNeN7w0cSJJEzgxZMv40pxsg==", + "version": "7.17.9", + "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", "dev": true, "requires": { "@babel/types": "^7.17.0", @@ -64,19 +59,17 @@ "dependencies": { "source-map": { "version": "0.5.7", - "resolved": false, "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true } } }, "@babel/helper-compilation-targets": { - "version": "7.16.7", - "resolved": false, - "integrity": "sha512-mGojBwIWcwGD6rfqgRXVlVYmPAv7eOpIemUG3dGnDdCY4Pae70ROij3XmfrH6Fa1h1aiDylpglbZyktfzyo/hA==", + "version": "7.17.7", + "integrity": "sha512-UFzlz2jjd8kroj0hmCFV5zr+tQPi1dpC2cRsDV/3IEW8bJfCPrPpmcSN6ZS8RqIq4LXcmpipCQFPddyFA5Yc7w==", "dev": true, "requires": { - "@babel/compat-data": "^7.16.4", + "@babel/compat-data": "^7.17.7", "@babel/helper-validator-option": "^7.16.7", "browserslist": "^4.17.5", "semver": "^6.3.0" @@ -84,7 +77,6 @@ }, "@babel/helper-environment-visitor": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag==", "dev": true, "requires": { @@ -92,28 +84,16 @@ } }, "@babel/helper-function-name": { - "version": "7.16.7", - "resolved": false, - "integrity": "sha512-QfDfEnIUyyBSR3HtrtGECuZ6DAyCkYFp7GHl75vFtTnn6pjKeK0T1DB5lLkFvBea8MdaiUABx3osbgLyInoejA==", + "version": "7.17.9", + "integrity": "sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg==", "dev": true, "requires": { - "@babel/helper-get-function-arity": "^7.16.7", "@babel/template": "^7.16.7", - "@babel/types": "^7.16.7" - } - }, - "@babel/helper-get-function-arity": { - "version": "7.16.7", - "resolved": false, - "integrity": "sha512-flc+RLSOBXzNzVhcLu6ujeHUrD6tANAOU5ojrRx/as+tbzf8+stUCj7+IfRRoAbEZqj/ahXEMsjhOhgeZsrnTw==", - "dev": true, - "requires": { - "@babel/types": "^7.16.7" + "@babel/types": "^7.17.0" } }, "@babel/helper-hoist-variables": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==", "dev": true, "requires": { @@ -122,7 +102,6 @@ }, "@babel/helper-module-imports": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==", "dev": true, "requires": { @@ -130,14 +109,13 @@ } }, "@babel/helper-module-transforms": { - "version": "7.17.6", - "resolved": false, - "integrity": "sha512-2ULmRdqoOMpdvkbT8jONrZML/XALfzxlb052bldftkicAUy8AxSCkD5trDPQcwHNmolcl7wP6ehNqMlyUw6AaA==", + "version": "7.17.7", + "integrity": "sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw==", "dev": true, "requires": { "@babel/helper-environment-visitor": "^7.16.7", "@babel/helper-module-imports": "^7.16.7", - "@babel/helper-simple-access": "^7.16.7", + "@babel/helper-simple-access": "^7.17.7", "@babel/helper-split-export-declaration": "^7.16.7", "@babel/helper-validator-identifier": "^7.16.7", "@babel/template": "^7.16.7", @@ -146,17 +124,15 @@ } }, "@babel/helper-simple-access": { - "version": "7.16.7", - "resolved": false, - "integrity": "sha512-ZIzHVyoeLMvXMN/vok/a4LWRy8G2v205mNP0XOuf9XRLyX5/u9CnVulUtDgUTama3lT+bf/UqucuZjqiGuTS1g==", + "version": "7.17.7", + "integrity": "sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA==", "dev": true, "requires": { - "@babel/types": "^7.16.7" + "@babel/types": "^7.17.0" } }, "@babel/helper-split-export-declaration": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==", "dev": true, "requires": { @@ -165,31 +141,27 @@ }, "@babel/helper-validator-identifier": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", "dev": true }, "@babel/helper-validator-option": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==", "dev": true }, "@babel/helpers": { - "version": "7.17.2", - "resolved": false, - "integrity": "sha512-0Qu7RLR1dILozr/6M0xgj+DFPmi6Bnulgm9M8BVa9ZCWxDqlSnqt3cf8IDPB5m45sVXUZ0kuQAgUrdSFFH79fQ==", + "version": "7.17.9", + "integrity": "sha512-cPCt915ShDWUEzEp3+UNRktO2n6v49l5RSnG9M5pS24hA+2FAc5si+Pn1i4VVbQQ+jh+bIZhPFQOJOzbrOYY1Q==", "dev": true, "requires": { "@babel/template": "^7.16.7", - "@babel/traverse": "^7.17.0", + "@babel/traverse": "^7.17.9", "@babel/types": "^7.17.0" } }, "@babel/highlight": { - "version": "7.16.10", - "resolved": false, - "integrity": "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==", + "version": "7.17.9", + "integrity": "sha512-J9PfEKCbFIv2X5bjTMiZu6Vf341N05QIY+d6FvVKynkG1S7G0j3I0QoRtWIrXhZ+/Nlb5Q0MzqL7TokEJ5BNHg==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.16.7", @@ -199,7 +171,6 @@ "dependencies": { "ansi-styles": { "version": "3.2.1", - "resolved": false, "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "requires": { @@ -208,7 +179,6 @@ }, "chalk": { "version": "2.4.2", - "resolved": false, "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { @@ -219,7 +189,6 @@ }, "color-convert": { "version": "1.9.3", - "resolved": false, "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "requires": { @@ -228,25 +197,21 @@ }, "color-name": { "version": "1.1.3", - "resolved": false, "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, "escape-string-regexp": { "version": "1.0.5", - "resolved": false, "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "has-flag": { "version": "3.0.0", - "resolved": false, "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", "dev": true }, "supports-color": { "version": "5.5.0", - "resolved": false, "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "requires": { @@ -256,14 +221,12 @@ } }, "@babel/parser": { - "version": "7.17.3", - "resolved": false, - "integrity": "sha512-7yJPvPV+ESz2IUTPbOL+YkIGyCqOyNIzdguKQuJGnH7bg1WTIifuM21YqokFt/THWh1AkCRn9IgoykTRCBVpzA==", + "version": "7.17.9", + "integrity": "sha512-vqUSBLP8dQHFPdPi9bc5GK9vRkYHJ49fsZdtoJ8EQ8ibpwk5rPKfvNIwChB0KVXcIjcepEBBd2VHC5r9Gy8ueg==", "dev": true }, "@babel/template": { "version": "7.16.7", - "resolved": false, "integrity": "sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==", "dev": true, "requires": { @@ -273,18 +236,17 @@ } }, "@babel/traverse": { - "version": "7.17.3", - "resolved": false, - "integrity": "sha512-5irClVky7TxRWIRtxlh2WPUUOLhcPN06AGgaQSB8AEwuyEBgJVuJ5imdHm5zxk8w0QS5T+tDfnDxAlhWjpb7cw==", + "version": "7.17.9", + "integrity": "sha512-PQO8sDIJ8SIwipTPiR71kJQCKQYB5NGImbOviK8K+kg5xkNSYXLBupuX9QhatFowrsvo9Hj8WgArg3W7ijNAQw==", "dev": true, "requires": { "@babel/code-frame": "^7.16.7", - "@babel/generator": "^7.17.3", + "@babel/generator": "^7.17.9", "@babel/helper-environment-visitor": "^7.16.7", - "@babel/helper-function-name": "^7.16.7", + "@babel/helper-function-name": "^7.17.9", "@babel/helper-hoist-variables": "^7.16.7", "@babel/helper-split-export-declaration": "^7.16.7", - "@babel/parser": "^7.17.3", + "@babel/parser": "^7.17.9", "@babel/types": "^7.17.0", "debug": "^4.1.0", "globals": "^11.1.0" @@ -292,7 +254,6 @@ }, "@babel/types": { "version": "7.17.0", - "resolved": false, "integrity": "sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw==", "dev": true, "requires": { @@ -301,14 +262,12 @@ } }, "@discoveryjs/json-ext": { - "version": "0.5.6", - "resolved": false, - "integrity": "sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==", + "version": "0.5.7", + "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==", "dev": true }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", - "resolved": false, "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", "dev": true, "requires": { @@ -321,7 +280,6 @@ "dependencies": { "argparse": { "version": "1.0.10", - "resolved": false, "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "requires": { @@ -330,13 +288,11 @@ }, "camelcase": { "version": "5.3.1", - "resolved": false, "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, "find-up": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { @@ -346,7 +302,6 @@ }, "js-yaml": { "version": "3.14.1", - "resolved": false, "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", "dev": true, "requires": { @@ -356,7 +311,6 @@ }, "locate-path": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -365,7 +319,6 @@ }, "p-limit": { "version": "2.3.0", - "resolved": false, "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { @@ -374,7 +327,6 @@ }, "p-locate": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -385,25 +337,21 @@ }, "@istanbuljs/schema": { "version": "0.1.3", - "resolved": false, "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", "dev": true }, "@jridgewell/resolve-uri": { "version": "3.0.5", - "resolved": false, "integrity": "sha512-VPeQ7+wH0itvQxnG+lIzWgkysKIr3L9sslimFW55rHMdGu/qCQ5z5h9zq4gI8uBtqkpHhsF4Z/OwExufUCThew==", "dev": true }, "@jridgewell/sourcemap-codec": { "version": "1.4.11", - "resolved": false, "integrity": "sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg==", "dev": true }, "@jridgewell/trace-mapping": { "version": "0.3.4", - "resolved": false, "integrity": "sha512-vFv9ttIedivx0ux3QSjhgtCVjPZd5l46ZOMDSCwnH1yUO2e964gO8LZGyv2QkqcgR6TnBU1v+1IFqmeoG+0UJQ==", "dev": true, "requires": { @@ -413,7 +361,6 @@ }, "@sinonjs/commons": { "version": "1.8.3", - "resolved": false, "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", "dev": true, "requires": { @@ -422,7 +369,6 @@ }, "@sinonjs/fake-timers": { "version": "6.0.1", - "resolved": false, "integrity": "sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==", "dev": true, "requires": { @@ -431,7 +377,6 @@ }, "@sinonjs/samsam": { "version": "5.3.1", - "resolved": false, "integrity": "sha512-1Hc0b1TtyfBu8ixF/tpfSHTVWKwCBLY4QJbkgnE7HcwyvT2xArDxb4K7dMgqRm3szI+LJbzmW/s4xxEhv6hwDg==", "dev": true, "requires": { @@ -442,13 +387,11 @@ }, "@sinonjs/text-encoding": { "version": "0.7.1", - "resolved": false, "integrity": "sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==", "dev": true }, "@types/eslint": { "version": "8.4.1", - "resolved": false, "integrity": "sha512-GE44+DNEyxxh2Kc6ro/VkIj+9ma0pO0bwv9+uHSyBrikYOHr8zYcdPvnBOp1aw8s+CjRvuSx7CyWqRrNFQ59mA==", "dev": true, "requires": { @@ -458,7 +401,6 @@ }, "@types/eslint-scope": { "version": "3.7.3", - "resolved": false, "integrity": "sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g==", "dev": true, "requires": { @@ -468,31 +410,26 @@ }, "@types/estree": { "version": "0.0.51", - "resolved": false, "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==", "dev": true }, "@types/json-schema": { - "version": "7.0.9", - "resolved": false, - "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", + "version": "7.0.11", + "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", "dev": true }, "@types/node": { - "version": "16.11.26", - "resolved": false, - "integrity": "sha512-GZ7bu5A6+4DtG7q9GsoHXy3ALcgeIHP4NnL0Vv2wu0uUB/yQex26v0tf6/na1mm0+bS9Uw+0DFex7aaKr2qawQ==", + "version": "17.0.24", + "integrity": "sha512-aveCYRQbgTH9Pssp1voEP7HiuWlD2jW2BO56w+bVrJn04i61yh6mRfoKO6hEYQD9vF+W8Chkwc6j1M36uPkx4g==", "dev": true }, "@ungap/promise-all-settled": { "version": "1.1.2", - "resolved": false, "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==", "dev": true }, "@webassemblyjs/ast": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==", "dev": true, "requires": { @@ -502,25 +439,21 @@ }, "@webassemblyjs/floating-point-hex-parser": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==", "dev": true }, "@webassemblyjs/helper-api-error": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==", "dev": true }, "@webassemblyjs/helper-buffer": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==", "dev": true }, "@webassemblyjs/helper-numbers": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==", "dev": true, "requires": { @@ -531,13 +464,11 @@ }, "@webassemblyjs/helper-wasm-bytecode": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==", "dev": true }, "@webassemblyjs/helper-wasm-section": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==", "dev": true, "requires": { @@ -549,7 +480,6 @@ }, "@webassemblyjs/ieee754": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==", "dev": true, "requires": { @@ -558,7 +488,6 @@ }, "@webassemblyjs/leb128": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==", "dev": true, "requires": { @@ -567,13 +496,11 @@ }, "@webassemblyjs/utf8": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==", "dev": true }, "@webassemblyjs/wasm-edit": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==", "dev": true, "requires": { @@ -589,7 +516,6 @@ }, "@webassemblyjs/wasm-gen": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==", "dev": true, "requires": { @@ -602,7 +528,6 @@ }, "@webassemblyjs/wasm-opt": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==", "dev": true, "requires": { @@ -614,7 +539,6 @@ }, "@webassemblyjs/wasm-parser": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==", "dev": true, "requires": { @@ -628,7 +552,6 @@ }, "@webassemblyjs/wast-printer": { "version": "1.11.1", - "resolved": false, "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==", "dev": true, "requires": { @@ -638,13 +561,11 @@ }, "@webpack-cli/configtest": { "version": "1.1.1", - "resolved": false, "integrity": "sha512-1FBc1f9G4P/AxMqIgfZgeOTuRnwZMten8E7zap5zgpPInnCrP8D4Q81+4CWIch8i/Nf7nXjP0v6CjjbHOrXhKg==", "dev": true }, "@webpack-cli/info": { "version": "1.4.1", - "resolved": false, "integrity": "sha512-PKVGmazEq3oAo46Q63tpMr4HipI3OPfP7LiNOEJg963RMgT0rqheag28NCML0o3GIzA3DmxP1ZIAv9oTX1CUIA==", "dev": true, "requires": { @@ -653,37 +574,31 @@ }, "@webpack-cli/serve": { "version": "1.6.1", - "resolved": false, "integrity": "sha512-gNGTiTrjEVQ0OcVnzsRSqTxaBSr+dmTfm+qJsCDluky8uhdLWep7Gcr62QsAKHTMxjCS/8nEITsmFAhfIx+QSw==", "dev": true }, "@xtuc/ieee754": { "version": "1.2.0", - "resolved": false, "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", "dev": true }, "@xtuc/long": { "version": "4.2.2", - "resolved": false, "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true }, "abab": { "version": "2.0.5", - "resolved": false, "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", "dev": true }, "acorn": { "version": "5.7.4", - "resolved": false, "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", "dev": true }, "acorn-globals": { "version": "4.3.4", - "resolved": false, "integrity": "sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A==", "dev": true, "requires": { @@ -693,7 +608,6 @@ "dependencies": { "acorn": { "version": "6.4.2", - "resolved": false, "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", "dev": true } @@ -701,19 +615,16 @@ }, "acorn-import-assertions": { "version": "1.8.0", - "resolved": false, "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==", "dev": true }, "acorn-walk": { "version": "6.2.0", - "resolved": false, "integrity": "sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==", "dev": true }, "aggregate-error": { "version": "3.1.0", - "resolved": false, "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", "dev": true, "requires": { @@ -723,7 +634,6 @@ }, "ajv": { "version": "6.12.6", - "resolved": false, "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "requires": { @@ -735,25 +645,21 @@ }, "ajv-keywords": { "version": "3.5.2", - "resolved": false, "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", "dev": true }, "ansi-colors": { "version": "4.1.1", - "resolved": false, "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true }, "ansi-regex": { "version": "5.0.1", - "resolved": false, "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", - "resolved": false, "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { @@ -762,7 +668,6 @@ }, "anymatch": { "version": "3.1.2", - "resolved": false, "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", "dev": true, "requires": { @@ -772,7 +677,6 @@ }, "append-transform": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", "dev": true, "requires": { @@ -781,25 +685,21 @@ }, "archy": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", "dev": true }, "argparse": { "version": "2.0.1", - "resolved": false, "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, "array-equal": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", "dev": true }, "asn1": { "version": "0.2.6", - "resolved": false, "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", "dev": true, "requires": { @@ -808,49 +708,41 @@ }, "assert-plus": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true }, "assertion-error": { "version": "1.1.0", - "resolved": false, "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", "dev": true }, "async-limiter": { "version": "1.0.1", - "resolved": false, "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==", "dev": true }, "asynckit": { "version": "0.4.0", - "resolved": false, "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "dev": true }, "aws-sign2": { "version": "0.7.0", - "resolved": false, "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", "dev": true }, "aws4": { "version": "1.11.0", - "resolved": false, "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", "dev": true }, "balanced-match": { "version": "1.0.2", - "resolved": false, "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, "bcrypt-pbkdf": { "version": "1.0.2", - "resolved": false, "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", "dev": true, "requires": { @@ -859,13 +751,11 @@ }, "binary-extensions": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", "dev": true }, "brace-expansion": { "version": "1.1.11", - "resolved": false, "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, "requires": { @@ -875,7 +765,6 @@ }, "braces": { "version": "3.0.2", - "resolved": false, "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dev": true, "requires": { @@ -884,24 +773,21 @@ }, "browser-process-hrtime": { "version": "1.0.0", - "resolved": false, "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, "browser-stdout": { "version": "1.3.1", - "resolved": false, "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", "dev": true }, "browserslist": { - "version": "4.19.3", - "resolved": false, - "integrity": "sha512-XK3X4xtKJ+Txj8G5c30B4gsm71s69lqXlkYui4s6EkKxuv49qjYlY6oVd+IFJ73d4YymtM3+djvvt/R/iJwwDg==", + "version": "4.20.2", + "integrity": "sha512-CQOBCqp/9pDvDbx3xfMi+86pr4KXIf2FDkTTdeuYw8OxS9t898LA1Khq57gtufFILXpfgsSx5woNgsBgvGjpsA==", "dev": true, "requires": { - "caniuse-lite": "^1.0.30001312", - "electron-to-chromium": "^1.4.71", + "caniuse-lite": "^1.0.30001317", + "electron-to-chromium": "^1.4.84", "escalade": "^3.1.1", "node-releases": "^2.0.2", "picocolors": "^1.0.0" @@ -909,13 +795,11 @@ }, "buffer-from": { "version": "1.1.2", - "resolved": false, "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, "caching-transform": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", "dev": true, "requires": { @@ -927,25 +811,21 @@ }, "camelcase": { "version": "6.3.0", - "resolved": false, "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", "dev": true }, "caniuse-lite": { - "version": "1.0.30001312", - "resolved": false, - "integrity": "sha512-Wiz1Psk2MEK0pX3rUzWaunLTZzqS2JYZFzNKqAiJGiuxIjRPLgV6+VDPOg6lQOUxmDwhTlh198JsTTi8Hzw6aQ==", + "version": "1.0.30001332", + "integrity": "sha512-10T30NYOEQtN6C11YGg411yebhvpnC6Z102+B95eAsN0oB6KUs01ivE8u+G6FMIRtIrVlYXhL+LUwQ3/hXwDWw==", "dev": true }, "caseless": { "version": "0.12.0", - "resolved": false, "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", "dev": true }, "chai": { "version": "4.3.6", - "resolved": false, "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", "dev": true, "requires": { @@ -960,7 +840,6 @@ }, "chalk": { "version": "4.1.2", - "resolved": false, "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { @@ -970,7 +849,6 @@ "dependencies": { "supports-color": { "version": "7.2.0", - "resolved": false, "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { @@ -981,13 +859,11 @@ }, "check-error": { "version": "1.0.2", - "resolved": false, "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", "dev": true }, "chokidar": { "version": "3.5.3", - "resolved": false, "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, "requires": { @@ -1003,19 +879,16 @@ }, "chrome-trace-event": { "version": "1.0.3", - "resolved": false, "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", "dev": true }, "clean-stack": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", "dev": true }, "cli": { "version": "1.0.1", - "resolved": false, "integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=", "dev": true, "requires": { @@ -1025,7 +898,6 @@ }, "cliui": { "version": "7.0.4", - "resolved": false, "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "requires": { @@ -1036,7 +908,6 @@ }, "clone-deep": { "version": "4.0.1", - "resolved": false, "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", "dev": true, "requires": { @@ -1047,7 +918,6 @@ }, "color-convert": { "version": "2.0.1", - "resolved": false, "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -1056,19 +926,16 @@ }, "color-name": { "version": "1.1.4", - "resolved": false, "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "colorette": { "version": "2.0.16", - "resolved": false, "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", "dev": true }, "combined-stream": { "version": "1.0.8", - "resolved": false, "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, "requires": { @@ -1077,25 +944,21 @@ }, "commander": { "version": "2.20.3", - "resolved": false, "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true }, "commondir": { "version": "1.0.1", - "resolved": false, "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", "dev": true }, "concat-map": { "version": "0.0.1", - "resolved": false, "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, "console-browserify": { "version": "1.1.0", - "resolved": false, "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", "dev": true, "requires": { @@ -1104,7 +967,6 @@ }, "convert-source-map": { "version": "1.8.0", - "resolved": false, "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", "dev": true, "requires": { @@ -1113,7 +975,6 @@ "dependencies": { "safe-buffer": { "version": "5.1.2", - "resolved": false, "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true } @@ -1121,13 +982,11 @@ }, "core-util-is": { "version": "1.0.3", - "resolved": false, "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, "cross-spawn": { "version": "7.0.3", - "resolved": false, "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { @@ -1138,13 +997,11 @@ }, "cssom": { "version": "0.3.8", - "resolved": false, "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true }, "cssstyle": { "version": "1.4.0", - "resolved": false, "integrity": "sha512-GBrLZYZ4X4x6/QEoBnIrqb8B/f5l4+8me2dkom/j1Gtbxy0kBv6OGzKuAsGM75bkGwGAFkt56Iwg28S3XTZgSA==", "dev": true, "requires": { @@ -1153,7 +1010,6 @@ }, "dashdash": { "version": "1.14.1", - "resolved": false, "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", "dev": true, "requires": { @@ -1162,7 +1018,6 @@ }, "data-urls": { "version": "1.1.0", - "resolved": false, "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", "dev": true, "requires": { @@ -1173,7 +1028,6 @@ "dependencies": { "whatwg-url": { "version": "7.1.0", - "resolved": false, "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==", "dev": true, "requires": { @@ -1186,13 +1040,11 @@ }, "date-now": { "version": "0.1.4", - "resolved": false, "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", "dev": true }, "debug": { "version": "4.3.3", - "resolved": false, "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", "dev": true, "requires": { @@ -1201,7 +1053,6 @@ "dependencies": { "ms": { "version": "2.1.2", - "resolved": false, "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true } @@ -1209,13 +1060,11 @@ }, "decamelize": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", "dev": true }, "deep-eql": { "version": "3.0.1", - "resolved": false, "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", "dev": true, "requires": { @@ -1224,13 +1073,11 @@ }, "deep-is": { "version": "0.1.4", - "resolved": false, "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, "default-require-extensions": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==", "dev": true, "requires": { @@ -1239,19 +1086,16 @@ }, "delayed-stream": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", "dev": true }, "diff": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "dev": true }, "dom-serializer": { "version": "0.2.2", - "resolved": false, "integrity": "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g==", "dev": true, "requires": { @@ -1260,14 +1104,12 @@ }, "dependencies": { "domelementtype": { - "version": "2.2.0", - "resolved": false, - "integrity": "sha512-DtBMo82pv1dFtUmHyr48beiuq792Sxohr+8Hm9zoxklYPfa6n0Z3Byjj2IV7bmr2IyqClnqEQhfgHJJ5QF0R5A==", + "version": "2.3.0", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", "dev": true }, "entities": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", "dev": true } @@ -1275,13 +1117,11 @@ }, "domelementtype": { "version": "1.3.1", - "resolved": false, "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", "dev": true }, "domexception": { "version": "1.0.1", - "resolved": false, "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", "dev": true, "requires": { @@ -1290,7 +1130,6 @@ }, "domhandler": { "version": "2.3.0", - "resolved": false, "integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=", "dev": true, "requires": { @@ -1299,7 +1138,6 @@ }, "domutils": { "version": "1.5.1", - "resolved": false, "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", "dev": true, "requires": { @@ -1309,7 +1147,6 @@ }, "ecc-jsbn": { "version": "0.1.2", - "resolved": false, "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", "dev": true, "requires": { @@ -1318,20 +1155,17 @@ } }, "electron-to-chromium": { - "version": "1.4.73", - "resolved": false, - "integrity": "sha512-RlCffXkE/LliqfA5m29+dVDPB2r72y2D2egMMfIy3Le8ODrxjuZNVo4NIC2yPL01N4xb4nZQLwzi6Z5tGIGLnA==", + "version": "1.4.108", + "integrity": "sha512-/36KkMuL6+WTrodVlOjtHhH9Ro7BgRaQrh0bfKckwDtdRSjTBuZCOddeXxzK1PkwphoeTxGUFVT9xnmvQ7xEdw==", "dev": true }, "emoji-regex": { "version": "8.0.0", - "resolved": false, "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "end-of-stream": { "version": "1.4.4", - "resolved": false, "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "dev": true, "requires": { @@ -1339,9 +1173,8 @@ } }, "enhanced-resolve": { - "version": "5.9.1", - "resolved": false, - "integrity": "sha512-jdyZMwCQ5Oj4c5+BTnkxPgDZO/BJzh/ADDmKebayyzNwjVX1AFCeGkOfxNx0mHi2+8BKC5VxUYiw3TIvoT7vhw==", + "version": "5.9.3", + "integrity": "sha512-Bq9VSor+kjvW3f9/MiiR4eE3XYgOl7/rS8lnSxbRbF3kS0B2r+Y9w5krBWxZgDxASVZbdYrn5wT4j/Wb0J9qow==", "dev": true, "requires": { "graceful-fs": "^4.2.4", @@ -1350,43 +1183,36 @@ }, "entities": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=", "dev": true }, "envinfo": { "version": "7.8.1", - "resolved": false, "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==", "dev": true }, "es-module-lexer": { "version": "0.9.3", - "resolved": false, "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==", "dev": true }, "es6-error": { "version": "4.1.1", - "resolved": false, "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", "dev": true }, "escalade": { "version": "3.1.1", - "resolved": false, "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", "dev": true }, "escape-string-regexp": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true }, "escodegen": { "version": "1.14.3", - "resolved": false, "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", "dev": true, "requires": { @@ -1399,7 +1225,6 @@ }, "eslint-scope": { "version": "5.1.1", - "resolved": false, "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "requires": { @@ -1409,13 +1234,11 @@ }, "esprima": { "version": "4.0.1", - "resolved": false, "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, "esrecurse": { "version": "4.3.0", - "resolved": false, "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { @@ -1424,7 +1247,6 @@ "dependencies": { "estraverse": { "version": "5.3.0", - "resolved": false, "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true } @@ -1432,25 +1254,21 @@ }, "estraverse": { "version": "4.3.0", - "resolved": false, "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true }, "esutils": { "version": "2.0.3", - "resolved": false, "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true }, "events": { "version": "3.3.0", - "resolved": false, "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", "dev": true }, "execa": { "version": "5.1.1", - "resolved": false, "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", "dev": true, "requires": { @@ -1467,49 +1285,41 @@ }, "exit": { "version": "0.1.2", - "resolved": false, "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, "extend": { "version": "3.0.2", - "resolved": false, "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, "extsprintf": { "version": "1.3.0", - "resolved": false, "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", "dev": true }, "fast-deep-equal": { "version": "3.1.3", - "resolved": false, "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, "fast-json-stable-stringify": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, "fast-levenshtein": { "version": "2.0.6", - "resolved": false, "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, "fastest-levenshtein": { "version": "1.0.12", - "resolved": false, "integrity": "sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow==", "dev": true }, "fill-range": { "version": "7.0.1", - "resolved": false, "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, "requires": { @@ -1518,7 +1328,6 @@ }, "find-cache-dir": { "version": "3.3.2", - "resolved": false, "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", "dev": true, "requires": { @@ -1529,7 +1338,6 @@ }, "find-up": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "requires": { @@ -1539,13 +1347,11 @@ }, "flat": { "version": "5.0.2", - "resolved": false, "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", "dev": true }, "foreground-child": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "requires": { @@ -1555,13 +1361,11 @@ }, "forever-agent": { "version": "0.6.1", - "resolved": false, "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", "dev": true }, "form-data": { "version": "2.3.3", - "resolved": false, "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", "dev": true, "requires": { @@ -1572,62 +1376,52 @@ }, "fromentries": { "version": "1.3.2", - "resolved": false, "integrity": "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==", "dev": true }, "fs.realpath": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, "fsevents": { "version": "2.3.2", - "resolved": false, "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "optional": true }, "function-bind": { "version": "1.1.1", - "resolved": false, "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, "gensync": { "version": "1.0.0-beta.2", - "resolved": false, "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "dev": true }, "get-caller-file": { "version": "2.0.5", - "resolved": false, "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "get-func-name": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, "get-package-type": { "version": "0.1.0", - "resolved": false, "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", "dev": true }, "get-stream": { "version": "6.0.1", - "resolved": false, "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", "dev": true }, "getpass": { "version": "0.1.7", - "resolved": false, "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", "dev": true, "requires": { @@ -1636,7 +1430,6 @@ }, "glob": { "version": "7.2.0", - "resolved": false, "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", "dev": true, "requires": { @@ -1650,7 +1443,6 @@ }, "glob-parent": { "version": "5.1.2", - "resolved": false, "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "requires": { @@ -1659,37 +1451,31 @@ }, "glob-to-regexp": { "version": "0.4.1", - "resolved": false, "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", "dev": true }, "globals": { "version": "11.12.0", - "resolved": false, "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", "dev": true }, "graceful-fs": { - "version": "4.2.9", - "resolved": false, - "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", + "version": "4.2.10", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", "dev": true }, "growl": { "version": "1.10.5", - "resolved": false, "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", "dev": true }, "har-schema": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", "dev": true }, "har-validator": { "version": "5.1.5", - "resolved": false, "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", "dev": true, "requires": { @@ -1699,7 +1485,6 @@ }, "has": { "version": "1.0.3", - "resolved": false, "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, "requires": { @@ -1708,13 +1493,11 @@ }, "has-flag": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, "hasha": { "version": "5.2.2", - "resolved": false, "integrity": "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==", "dev": true, "requires": { @@ -1724,13 +1507,11 @@ }, "he": { "version": "1.2.0", - "resolved": false, "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true }, "html-encoding-sniffer": { "version": "1.0.2", - "resolved": false, "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", "dev": true, "requires": { @@ -1739,13 +1520,11 @@ }, "html-escaper": { "version": "2.0.2", - "resolved": false, "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, "htmlparser2": { "version": "3.8.3", - "resolved": false, "integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=", "dev": true, "requires": { @@ -1758,7 +1537,6 @@ }, "http-signature": { "version": "1.2.0", - "resolved": false, "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", "dev": true, "requires": { @@ -1769,13 +1547,11 @@ }, "human-signals": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", "dev": true }, "iconv-lite": { "version": "0.4.24", - "resolved": false, "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "requires": { @@ -1784,7 +1560,6 @@ }, "import-local": { "version": "3.1.0", - "resolved": false, "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", "dev": true, "requires": { @@ -1794,19 +1569,16 @@ }, "imurmurhash": { "version": "0.1.4", - "resolved": false, "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, "indent-string": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", "dev": true }, "inflight": { "version": "1.0.6", - "resolved": false, "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { @@ -1816,19 +1588,16 @@ }, "inherits": { "version": "2.0.4", - "resolved": false, "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, "interpret": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", "dev": true }, "is-binary-path": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, "requires": { @@ -1837,7 +1606,6 @@ }, "is-core-module": { "version": "2.8.1", - "resolved": false, "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", "dev": true, "requires": { @@ -1846,19 +1614,16 @@ }, "is-extglob": { "version": "2.1.1", - "resolved": false, "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "is-glob": { "version": "4.0.3", - "resolved": false, "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "requires": { @@ -1867,19 +1632,16 @@ }, "is-number": { "version": "7.0.0", - "resolved": false, "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, "is-plain-obj": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", "dev": true }, "is-plain-object": { "version": "2.0.4", - "resolved": false, "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, "requires": { @@ -1888,61 +1650,51 @@ }, "is-stream": { "version": "2.0.1", - "resolved": false, "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true }, "is-typedarray": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", "dev": true }, "is-unicode-supported": { "version": "0.1.0", - "resolved": false, "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", "dev": true }, "is-windows": { "version": "1.0.2", - "resolved": false, "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", "dev": true }, "isarray": { "version": "0.0.1", - "resolved": false, "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", "dev": true }, "isexe": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, "isobject": { "version": "3.0.1", - "resolved": false, "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", "dev": true }, "isstream": { "version": "0.1.2", - "resolved": false, "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", "dev": true }, "istanbul-lib-coverage": { "version": "3.2.0", - "resolved": false, "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", "dev": true }, "istanbul-lib-hook": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", "dev": true, "requires": { @@ -1951,7 +1703,6 @@ }, "istanbul-lib-instrument": { "version": "4.0.3", - "resolved": false, "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", "dev": true, "requires": { @@ -1963,7 +1714,6 @@ }, "istanbul-lib-processinfo": { "version": "2.0.2", - "resolved": false, "integrity": "sha512-kOwpa7z9hme+IBPZMzQ5vdQj8srYgAtaRqeI48NGmAQ+/5yKiHLV0QbYqQpxsdEF0+w14SoB8YbnHKcXE2KnYw==", "dev": true, "requires": { @@ -1978,7 +1728,6 @@ }, "istanbul-lib-report": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", "dev": true, "requires": { @@ -1989,7 +1738,6 @@ "dependencies": { "supports-color": { "version": "7.2.0", - "resolved": false, "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { @@ -2000,7 +1748,6 @@ }, "istanbul-lib-source-maps": { "version": "4.0.1", - "resolved": false, "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", "dev": true, "requires": { @@ -2011,7 +1758,6 @@ }, "istanbul-reports": { "version": "3.1.4", - "resolved": false, "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", "dev": true, "requires": { @@ -2021,7 +1767,6 @@ }, "jest-worker": { "version": "27.5.1", - "resolved": false, "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", "dev": true, "requires": { @@ -2032,13 +1777,11 @@ }, "js-tokens": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true }, "js-yaml": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "requires": { @@ -2047,13 +1790,11 @@ }, "jsbn": { "version": "0.1.1", - "resolved": false, "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", "dev": true }, "jsdom": { "version": "11.12.0", - "resolved": false, "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", "dev": true, "requires": { @@ -2087,13 +1828,11 @@ }, "jsesc": { "version": "2.5.2", - "resolved": false, "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true }, "jshint": { "version": "2.13.4", - "resolved": false, "integrity": "sha512-HO3bosL84b2qWqI0q+kpT/OpRJwo0R4ivgmxaO848+bo10rc50SkPnrtwSFXttW0ym4np8jbJvLwk5NziB7jIw==", "dev": true, "requires": { @@ -2108,40 +1847,31 @@ }, "json-parse-better-errors": { "version": "1.0.2", - "resolved": false, "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", "dev": true }, "json-schema": { "version": "0.4.0", - "resolved": false, "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", "dev": true }, "json-schema-traverse": { "version": "0.4.1", - "resolved": false, "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, "json-stringify-safe": { "version": "5.0.1", - "resolved": false, "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", "dev": true }, "json5": { - "version": "2.2.0", - "resolved": false, - "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dev": true, - "requires": { - "minimist": "^1.2.5" - } + "version": "2.2.1", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "dev": true }, "jsprim": { "version": "1.4.2", - "resolved": false, "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", "dev": true, "requires": { @@ -2153,25 +1883,21 @@ }, "just-extend": { "version": "4.2.1", - "resolved": false, "integrity": "sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg==", "dev": true }, "kind-of": { "version": "6.0.3", - "resolved": false, "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true }, "left-pad": { "version": "1.3.0", - "resolved": false, "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", "dev": true }, "levn": { "version": "0.3.0", - "resolved": false, "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", "dev": true, "requires": { @@ -2180,14 +1906,12 @@ } }, "loader-runner": { - "version": "4.2.0", - "resolved": false, - "integrity": "sha512-92+huvxMvYlMzMt0iIOukcwYBFpkYJdpl2xsZ7LrlayO7E8SOv+JJUEK17B/dJIHAOLMfh2dZZ/Y18WgmGtYNw==", + "version": "4.3.0", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", "dev": true }, "locate-path": { "version": "6.0.0", - "resolved": false, "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "requires": { @@ -2196,31 +1920,26 @@ }, "lodash": { "version": "4.17.21", - "resolved": false, "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "lodash.flattendeep": { "version": "4.4.0", - "resolved": false, "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=", "dev": true }, "lodash.get": { "version": "4.4.2", - "resolved": false, "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", "dev": true }, "lodash.sortby": { "version": "4.7.0", - "resolved": false, "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", "dev": true }, "log-symbols": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", "dev": true, "requires": { @@ -2230,7 +1949,6 @@ }, "loupe": { "version": "2.3.4", - "resolved": false, "integrity": "sha512-OvKfgCC2Ndby6aSTREl5aCCPTNIzlDfQZvZxNUrBrihDhL3xcrYegTblhmEiCrg2kKQz4XsFIaemE5BF4ybSaQ==", "dev": true, "requires": { @@ -2239,7 +1957,6 @@ }, "make-dir": { "version": "3.1.0", - "resolved": false, "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", "dev": true, "requires": { @@ -2248,50 +1965,38 @@ }, "merge-stream": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, "mime-db": { - "version": "1.51.0", - "resolved": false, - "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "version": "1.52.0", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true }, "mime-types": { - "version": "2.1.34", - "resolved": false, - "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "version": "2.1.35", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "requires": { - "mime-db": "1.51.0" + "mime-db": "1.52.0" } }, "mimic-fn": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "dev": true }, "minimatch": { "version": "3.0.8", - "resolved": false, "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, - "minimist": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", - "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", - "dev": true - }, "mocha": { - "version": "9.2.1", - "resolved": false, - "integrity": "sha512-T7uscqjJVS46Pq1XDXyo9Uvey9gd3huT/DD9cYBb4K2Xc/vbKRPUWK067bxDQRK0yIz6Jxk73IrnimvASzBNAQ==", + "version": "9.2.2", + "integrity": "sha512-L6XC3EdwT6YrIk0yXpavvLkn8h+EU+Y5UcCHKECyMbdUIxyMuZj4bX4U9e1nvnvUUvQVsV2VHQr5zLdcUkhW/g==", "dev": true, "requires": { "@ungap/promise-all-settled": "1.1.2", @@ -2307,9 +2012,9 @@ "he": "1.2.0", "js-yaml": "4.1.0", "log-symbols": "4.1.0", - "minimatch": "3.0.4", + "minimatch": "4.2.1", "ms": "2.1.3", - "nanoid": "3.2.0", + "nanoid": "3.3.1", "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", @@ -2321,9 +2026,8 @@ }, "dependencies": { "minimatch": { - "version": "3.0.4", - "resolved": false, - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "version": "4.2.1", + "integrity": "sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g==", "dev": true, "requires": { "brace-expansion": "^1.1.7" @@ -2331,7 +2035,6 @@ }, "strip-json-comments": { "version": "3.1.1", - "resolved": false, "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true } @@ -2339,7 +2042,6 @@ }, "mocha-jsdom": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-+3D++FPXHXEesbBD7Q/r4dkc3XzVFMPLJVIECaQ685dj9qKQYzliqX8IXyIUbUL4x1QfgD9h8Zao8cn03NKKEA==", "dev": true, "requires": { @@ -2348,25 +2050,21 @@ }, "ms": { "version": "2.1.3", - "resolved": false, "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, "nanoid": { - "version": "3.2.0", - "resolved": false, - "integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==", + "version": "3.3.1", + "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", "dev": true }, "neo-async": { "version": "2.6.2", - "resolved": false, "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, "nise": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-eQMEmGN/8arp0xsvGoQ+B1qvSkR73B1nWSCh7nOt5neMCtwcQVYQGdzQMhcNscktTsWB54xnlSQFzOAPJD8nXA==", "dev": true, "requires": { @@ -2379,7 +2077,6 @@ }, "node-preload": { "version": "0.2.1", - "resolved": false, "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", "dev": true, "requires": { @@ -2387,20 +2084,17 @@ } }, "node-releases": { - "version": "2.0.2", - "resolved": false, - "integrity": "sha512-XxYDdcQ6eKqp/YjI+tb2C5WM2LgjnZrfYg4vgQt49EK268b6gYCHsBLrK2qvJo4FmCtqmKezb0WZFK4fkrZNsg==", + "version": "2.0.3", + "integrity": "sha512-maHFz6OLqYxz+VQyCAtA3PTX4UP/53pa05fyDNc9CwjvJ0yEh6+xBwKsgCxMNhS8taUKBFYxfuiaD9U/55iFaw==", "dev": true }, "normalize-path": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true }, "npm-run-path": { "version": "4.0.1", - "resolved": false, "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", "dev": true, "requires": { @@ -2409,13 +2103,11 @@ }, "nwsapi": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", "dev": true }, "nyc": { "version": "15.1.0", - "resolved": false, "integrity": "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==", "dev": true, "requires": { @@ -2450,13 +2142,11 @@ "dependencies": { "camelcase": { "version": "5.3.1", - "resolved": false, "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, "cliui": { "version": "6.0.0", - "resolved": false, "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "requires": { @@ -2467,13 +2157,11 @@ }, "decamelize": { "version": "1.2.0", - "resolved": false, "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "find-up": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { @@ -2483,7 +2171,6 @@ }, "locate-path": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -2492,7 +2179,6 @@ }, "p-limit": { "version": "2.3.0", - "resolved": false, "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { @@ -2501,7 +2187,6 @@ }, "p-locate": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -2510,7 +2195,6 @@ }, "wrap-ansi": { "version": "6.2.0", - "resolved": false, "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { @@ -2521,13 +2205,11 @@ }, "y18n": { "version": "4.0.3", - "resolved": false, "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "15.4.1", - "resolved": false, "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { @@ -2546,7 +2228,6 @@ }, "yargs-parser": { "version": "18.1.3", - "resolved": false, "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { @@ -2558,13 +2239,11 @@ }, "oauth-sign": { "version": "0.9.0", - "resolved": false, "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", "dev": true }, "once": { "version": "1.4.0", - "resolved": false, "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { @@ -2573,7 +2252,6 @@ }, "onetime": { "version": "5.1.2", - "resolved": false, "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dev": true, "requires": { @@ -2582,7 +2260,6 @@ }, "optionator": { "version": "0.8.3", - "resolved": false, "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, "requires": { @@ -2596,7 +2273,6 @@ }, "p-limit": { "version": "3.1.0", - "resolved": false, "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "requires": { @@ -2605,7 +2281,6 @@ }, "p-locate": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "requires": { @@ -2614,7 +2289,6 @@ }, "p-map": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, "requires": { @@ -2623,13 +2297,11 @@ }, "p-try": { "version": "2.2.0", - "resolved": false, "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, "package-hash": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", "dev": true, "requires": { @@ -2641,37 +2313,31 @@ }, "parse5": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", "dev": true }, "path-exists": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "path-is-absolute": { "version": "1.0.1", - "resolved": false, "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true }, "path-key": { "version": "3.1.1", - "resolved": false, "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true }, "path-parse": { "version": "1.0.7", - "resolved": false, "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, "path-to-regexp": { "version": "1.8.0", - "resolved": false, "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", "dev": true, "requires": { @@ -2680,31 +2346,26 @@ }, "pathval": { "version": "1.1.1", - "resolved": false, "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", "dev": true }, "performance-now": { "version": "2.1.0", - "resolved": false, "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", "dev": true }, "picocolors": { "version": "1.0.0", - "resolved": false, "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", "dev": true }, "picomatch": { "version": "2.3.1", - "resolved": false, "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true }, "pkg-dir": { "version": "4.2.0", - "resolved": false, "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "requires": { @@ -2713,7 +2374,6 @@ "dependencies": { "find-up": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { @@ -2723,7 +2383,6 @@ }, "locate-path": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -2732,7 +2391,6 @@ }, "p-limit": { "version": "2.3.0", - "resolved": false, "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { @@ -2741,7 +2399,6 @@ }, "p-locate": { "version": "4.1.0", - "resolved": false, "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -2752,19 +2409,16 @@ }, "pn": { "version": "1.1.0", - "resolved": false, "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", "dev": true }, "prelude-ls": { "version": "1.1.2", - "resolved": false, "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "dev": true }, "process-on-spawn": { "version": "1.0.0", - "resolved": false, "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", "dev": true, "requires": { @@ -2773,13 +2427,11 @@ }, "psl": { "version": "1.8.0", - "resolved": false, "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", "dev": true }, "pump": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dev": true, "requires": { @@ -2789,19 +2441,16 @@ }, "punycode": { "version": "2.1.1", - "resolved": false, "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, "qs": { "version": "6.5.3", - "resolved": false, "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", "dev": true }, "randombytes": { "version": "2.1.0", - "resolved": false, "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", "dev": true, "requires": { @@ -2810,7 +2459,6 @@ }, "readable-stream": { "version": "1.1.14", - "resolved": false, "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", "dev": true, "requires": { @@ -2822,7 +2470,6 @@ }, "readdirp": { "version": "3.6.0", - "resolved": false, "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "requires": { @@ -2831,7 +2478,6 @@ }, "rechoir": { "version": "0.7.1", - "resolved": false, "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", "dev": true, "requires": { @@ -2840,7 +2486,6 @@ }, "release-zalgo": { "version": "1.0.0", - "resolved": false, "integrity": "sha1-CXALflB0Mpc5Mw5TXFqQ+2eFFzA=", "dev": true, "requires": { @@ -2849,7 +2494,6 @@ }, "request": { "version": "2.88.2", - "resolved": false, "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", "dev": true, "requires": { @@ -2877,7 +2521,6 @@ }, "request-promise-core": { "version": "1.1.4", - "resolved": false, "integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==", "dev": true, "requires": { @@ -2886,7 +2529,6 @@ }, "request-promise-native": { "version": "1.0.9", - "resolved": false, "integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==", "dev": true, "requires": { @@ -2897,19 +2539,16 @@ }, "require-directory": { "version": "2.1.1", - "resolved": false, "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "resolve": { "version": "1.22.0", - "resolved": false, "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", "dev": true, "requires": { @@ -2920,7 +2559,6 @@ }, "resolve-cwd": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", "dev": true, "requires": { @@ -2929,13 +2567,11 @@ }, "resolve-from": { "version": "5.0.0", - "resolved": false, "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true }, "rimraf": { "version": "3.0.2", - "resolved": false, "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { @@ -2944,25 +2580,21 @@ }, "safe-buffer": { "version": "5.2.1", - "resolved": false, "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", "dev": true }, "safer-buffer": { "version": "2.1.2", - "resolved": false, "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, "sax": { "version": "1.2.4", - "resolved": false, "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true }, "schema-utils": { "version": "3.1.1", - "resolved": false, "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", "dev": true, "requires": { @@ -2973,13 +2605,11 @@ }, "semver": { "version": "6.3.0", - "resolved": false, "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true }, "serialize-javascript": { "version": "6.0.0", - "resolved": false, "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", "dev": true, "requires": { @@ -2988,13 +2618,11 @@ }, "set-blocking": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, "shallow-clone": { "version": "3.0.1", - "resolved": false, "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", "dev": true, "requires": { @@ -3003,7 +2631,6 @@ }, "shebang-command": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "requires": { @@ -3012,19 +2639,16 @@ }, "shebang-regex": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, "signal-exit": { "version": "3.0.7", - "resolved": false, "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, "sinon": { "version": "9.2.4", - "resolved": false, "integrity": "sha512-zljcULZQsJxVra28qIAL6ow1Z9tpattkCTEJR4RBP3TGc00FcttsP5pK284Nas5WjMZU5Yzy3kAIp3B3KRf5Yg==", "dev": true, "requires": { @@ -3038,13 +2662,11 @@ "dependencies": { "diff": { "version": "4.0.2", - "resolved": false, "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": false, "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { @@ -3055,13 +2677,11 @@ }, "source-map": { "version": "0.6.1", - "resolved": false, "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, "source-map-support": { "version": "0.5.21", - "resolved": false, "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, "requires": { @@ -3071,7 +2691,6 @@ }, "spawn-wrap": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", "dev": true, "requires": { @@ -3085,13 +2704,11 @@ }, "sprintf-js": { "version": "1.0.3", - "resolved": false, "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, "sshpk": { "version": "1.17.0", - "resolved": false, "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", "dev": true, "requires": { @@ -3108,13 +2725,11 @@ }, "stealthy-require": { "version": "1.1.1", - "resolved": false, "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", "dev": true }, "string-width": { "version": "4.2.3", - "resolved": false, "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { @@ -3125,13 +2740,11 @@ }, "string_decoder": { "version": "0.10.31", - "resolved": false, "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", "dev": true }, "strip-ansi": { "version": "6.0.1", - "resolved": false, "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { @@ -3140,25 +2753,21 @@ }, "strip-bom": { "version": "4.0.0", - "resolved": false, "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true }, "strip-final-newline": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", "dev": true }, "strip-json-comments": { "version": "1.0.4", - "resolved": false, "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=", "dev": true }, "supports-color": { "version": "8.1.1", - "resolved": false, "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, "requires": { @@ -3167,26 +2776,22 @@ }, "supports-preserve-symlinks-flag": { "version": "1.0.0", - "resolved": false, "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true }, "symbol-tree": { "version": "3.2.4", - "resolved": false, "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, "tapable": { "version": "2.2.1", - "resolved": false, "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", "dev": true }, "terser": { - "version": "5.11.0", - "resolved": false, - "integrity": "sha512-uCA9DLanzzWSsN1UirKwylhhRz3aKPInlfmpGfw8VN6jHsAtu8HJtIpeeHHK23rxnE/cDc+yvmq5wqkIC6Kn0A==", + "version": "5.12.1", + "integrity": "sha512-NXbs+7nisos5E+yXwAD+y7zrcTkMqb0dEJxIGtSKPdCBzopf7ni4odPul2aechpV7EXNvOudYOX2bb5tln1jbQ==", "dev": true, "requires": { "acorn": "^8.5.0", @@ -3197,13 +2802,11 @@ "dependencies": { "acorn": { "version": "8.7.0", - "resolved": false, "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", "dev": true }, "source-map": { "version": "0.7.3", - "resolved": false, "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", "dev": true } @@ -3211,7 +2814,6 @@ }, "terser-webpack-plugin": { "version": "5.3.1", - "resolved": false, "integrity": "sha512-GvlZdT6wPQKbDNW/GDQzZFg/j4vKU96yl2q6mcUkzKOgW4gwf1Z8cZToUCrz31XHlPWH8MVb1r2tFtdDtTGJ7g==", "dev": true, "requires": { @@ -3224,7 +2826,6 @@ }, "test-exclude": { "version": "6.0.0", - "resolved": false, "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, "requires": { @@ -3235,13 +2836,11 @@ }, "to-fast-properties": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", "dev": true }, "to-regex-range": { "version": "5.0.1", - "resolved": false, "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, "requires": { @@ -3250,7 +2849,6 @@ }, "tough-cookie": { "version": "2.5.0", - "resolved": false, "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", "dev": true, "requires": { @@ -3260,7 +2858,6 @@ }, "tr46": { "version": "1.0.1", - "resolved": false, "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", "dev": true, "requires": { @@ -3269,7 +2866,6 @@ }, "tunnel-agent": { "version": "0.6.0", - "resolved": false, "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", "dev": true, "requires": { @@ -3278,13 +2874,11 @@ }, "tweetnacl": { "version": "0.14.5", - "resolved": false, "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", "dev": true }, "type-check": { "version": "0.3.2", - "resolved": false, "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", "dev": true, "requires": { @@ -3293,19 +2887,16 @@ }, "type-detect": { "version": "4.0.8", - "resolved": false, "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, "type-fest": { "version": "0.8.1", - "resolved": false, "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true }, "typedarray-to-buffer": { "version": "3.1.5", - "resolved": false, "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "dev": true, "requires": { @@ -3313,14 +2904,12 @@ } }, "typescript": { - "version": "4.5.5", - "resolved": false, - "integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==", + "version": "4.6.3", + "integrity": "sha512-yNIatDa5iaofVozS/uQJEl3JRWLKKGJKh6Yaiv0GLGSuhpFJe7P3SbHZ8/yjAHRQwKRoA6YZqlfjXWmVzoVSMw==", "dev": true }, "uri-js": { "version": "4.4.1", - "resolved": false, "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, "requires": { @@ -3329,13 +2918,11 @@ }, "uuid": { "version": "3.4.0", - "resolved": false, "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "dev": true }, "verror": { "version": "1.10.0", - "resolved": false, "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "dev": true, "requires": { @@ -3346,7 +2933,6 @@ "dependencies": { "core-util-is": { "version": "1.0.2", - "resolved": false, "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true } @@ -3354,7 +2940,6 @@ }, "w3c-hr-time": { "version": "1.0.2", - "resolved": false, "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", "dev": true, "requires": { @@ -3363,7 +2948,6 @@ }, "watchpack": { "version": "2.3.1", - "resolved": false, "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==", "dev": true, "requires": { @@ -3373,14 +2957,12 @@ }, "webidl-conversions": { "version": "4.0.2", - "resolved": false, "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", "dev": true }, "webpack": { - "version": "5.69.1", - "resolved": false, - "integrity": "sha512-+VyvOSJXZMT2V5vLzOnDuMz5GxEqLk7hKWQ56YxPW/PQRUuKimPqmEIJOx8jHYeyo65pKbapbW464mvsKbaj4A==", + "version": "5.72.0", + "integrity": "sha512-qmSmbspI0Qo5ld49htys8GY9XhS9CGqFoHTsOVAnjBdg0Zn79y135R+k4IR4rKK6+eKaabMhJwiVB7xw0SJu5w==", "dev": true, "requires": { "@types/eslint-scope": "^3.7.3", @@ -3392,7 +2974,7 @@ "acorn-import-assertions": "^1.7.6", "browserslist": "^4.14.5", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.8.3", + "enhanced-resolve": "^5.9.2", "es-module-lexer": "^0.9.0", "eslint-scope": "5.1.1", "events": "^3.2.0", @@ -3411,7 +2993,6 @@ "dependencies": { "acorn": { "version": "8.7.0", - "resolved": false, "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", "dev": true } @@ -3419,7 +3000,6 @@ }, "webpack-cli": { "version": "4.9.2", - "resolved": false, "integrity": "sha512-m3/AACnBBzK/kMTcxWHcZFPrw/eQuY4Df1TxvIWfWM2x7mRqBQCqKEd96oCUa9jkapLBaFfRce33eGDb4Pr7YQ==", "dev": true, "requires": { @@ -3439,7 +3019,6 @@ "dependencies": { "commander": { "version": "7.2.0", - "resolved": false, "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", "dev": true } @@ -3447,7 +3026,6 @@ }, "webpack-merge": { "version": "5.8.0", - "resolved": false, "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", "dev": true, "requires": { @@ -3457,19 +3035,16 @@ }, "webpack-plugin-replace": { "version": "1.2.0", - "resolved": false, "integrity": "sha512-1HA3etHpJW55qonJqv84o5w5GY7iqF8fqSHpTWdNwarj1llkkt4jT4QSvYs1hoaU8Lu5akDnq/spHHO5mXwo1w==", "dev": true }, "webpack-sources": { "version": "3.2.3", - "resolved": false, "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", "dev": true }, "whatwg-encoding": { "version": "1.0.5", - "resolved": false, "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", "dev": true, "requires": { @@ -3478,13 +3053,11 @@ }, "whatwg-mimetype": { "version": "2.3.0", - "resolved": false, "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", "dev": true }, "whatwg-url": { "version": "6.5.0", - "resolved": false, "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", "dev": true, "requires": { @@ -3495,7 +3068,6 @@ }, "which": { "version": "2.0.2", - "resolved": false, "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "requires": { @@ -3504,31 +3076,26 @@ }, "which-module": { "version": "2.0.0", - "resolved": false, "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wildcard": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", "dev": true }, "word-wrap": { "version": "1.2.3", - "resolved": false, "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", "dev": true }, "workerpool": { "version": "6.2.0", - "resolved": false, "integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==", "dev": true }, "wrap-ansi": { "version": "7.0.0", - "resolved": false, "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "requires": { @@ -3539,13 +3106,11 @@ }, "wrappy": { "version": "1.0.2", - "resolved": false, "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, "write-file-atomic": { "version": "3.0.3", - "resolved": false, "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", "dev": true, "requires": { @@ -3557,7 +3122,6 @@ }, "ws": { "version": "5.2.3", - "resolved": false, "integrity": "sha512-jZArVERrMsKUatIdnLzqvcfydI85dvd/Fp1u/VOpfdDWQ4c9qWXe+VIeAbQ5FrDwciAkr+lzofXLz3Kuf26AOA==", "dev": true, "requires": { @@ -3566,19 +3130,16 @@ }, "xml-name-validator": { "version": "3.0.0", - "resolved": false, "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", "dev": true }, "y18n": { "version": "5.0.8", - "resolved": false, "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true }, "yargs": { "version": "16.2.0", - "resolved": false, "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "requires": { @@ -3593,13 +3154,11 @@ }, "yargs-parser": { "version": "20.2.4", - "resolved": false, "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", "dev": true }, "yargs-unparser": { "version": "2.0.0", - "resolved": false, "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", "dev": true, "requires": { @@ -3611,7 +3170,6 @@ }, "yocto-queue": { "version": "0.1.0", - "resolved": false, "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true } diff --git a/package.json b/package.json index f2c037f9..8c5b89b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "amazon-connect-streams", - "version": "2.1.1", + "version": "2.2.0", "description": "Amazon Connect Streams Library", "engines": { "node": ">=12.0.0" diff --git a/release/connect-streams-min.js b/release/connect-streams-min.js index 954f16fb..a0122afa 100644 --- a/release/connect-streams-min.js +++ b/release/connect-streams-min.js @@ -1 +1 @@ -(()=>{var e={821:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.agentApp={};var n="ccp";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];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)};t.agentApp.initApp=function(e,o,i,s){s=s||{};var a=i.endsWith("/")?i:i+"/",c=s.onLoad?s.onLoad:null,u={endpoint:a,style:s.style,onLoad:c};t.agentApp.AppRegistry.register(e,u,document.getElementById(o)),t.agentApp.AppRegistry.start(e,(function(o){var i=o.endpoint,a=o.containerDOM;return{init:function(){return e===n?function(e,n,o){var i={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:r(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1}},s=t.merge(i,o.ccpParams);t.core.initCCP(n,s)}(i,a,s):t.agentApp.initAppCommunication(e,i)},destroy:function(){return e===n?(o=r(i)+"/logout",t.fetch(o,{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=o,!1}))):null;var o}}}))},t.agentApp.stopApp=function(e){return t.agentApp.AppRegistry.stop(e)}}()},500:()=>{!function(){var e=this||window,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,s=n[e].style,a=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.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),o}(e,i,s,a);o.appendChild(c)}return n[e].instance=t(n[e]),n[e].instance.init()}},stop:function(e){if(n[e]){var t,r=n[e],o=r.containerDOM.querySelector("iframe");return r.containerDOM.removeChild(o),r.instance&&(t=r.instance.destroy(),delete r.instance),t}}})}()},965:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.AgentStateType=t.makeEnum(["init","routable","not_routable","offline"]),t.AgentStatusType=t.AgentStateType,t.AgentAvailStates=t.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),t.AgentErrorStates=t.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),t.EndpointType=t.makeEnum(["phone_number","agent","queue"]),t.AddressType=t.EndpointType,t.ConnectionType=t.makeEnum(["agent","inbound","outbound","monitoring"]),t.ConnectionStateType=t.makeEnum(["init","connecting","connected","hold","disconnected"]),t.ConnectionStatusType=t.ConnectionStateType,t.CONNECTION_ACTIVE_STATES=t.set([t.ConnectionStateType.CONNECTING,t.ConnectionStateType.CONNECTED,t.ConnectionStateType.HOLD]),t.ContactStateType=t.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended"]),t.ContactStatusType=t.ContactStateType,t.CONTACT_ACTIVE_STATES=t.makeEnum(["incoming","pending","connecting","connected"]),t.ContactType=t.makeEnum(["voice","queue_callback","chat","task"]),t.ContactInitiationMethod=t.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect"]),t.ChannelType=t.makeEnum(["VOICE","CHAT","TASK"]),t.MediaType=t.makeEnum(["softphone","chat","task"]),t.SoftphoneCallType=t.makeEnum(["audio_video","video_only","audio_only","none"]),t.SoftphoneErrorTypes=t.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","other"]),t.VoiceIdErrorTypes=t.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"]),t.CTIExceptions=t.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),t.VoiceIdStreamingStatus=t.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),t.VoiceIdAuthenticationDecision=t.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),t.VoiceIdFraudDetectionDecision=t.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),t.ContactFlowAuthenticationDecision=t.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),t.ContactFlowFraudDetectionDecision=t.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),t.VoiceIdEnrollmentRequestStatus=t.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),t.VoiceIdSpeakerStatus=t.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),t.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},t.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId"};var n=function(){if(!t.agent.initialized)throw new t.StateError("The agent is not yet initialized!")};n.prototype._getData=function(){return t.core.getAgentDataProvider().getAgentData()},n.prototype._createContactAPI=function(e){return new t.Contact(e.contactId)},n.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(t.AgentEvents.REFRESH,e)},n.prototype.onRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ROUTABLE,e)},n.prototype.onNotRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.NOT_ROUTABLE,e)},n.prototype.onOffline=function(e){t.core.getEventBus().subscribe(t.AgentEvents.OFFLINE,e)},n.prototype.onError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ERROR,e)},n.prototype.onSoftphoneError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.SOFTPHONE_ERROR,e)},n.prototype.onWebSocketConnectionLost=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},n.prototype.onWebSocketConnectionGained=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},n.prototype.onAfterCallWork=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ACW,e)},n.prototype.onStateChange=function(e){t.core.getEventBus().subscribe(t.AgentEvents.STATE_CHANGE,e)},n.prototype.onMuteToggle=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.MUTE_TOGGLE,e)},n.prototype.onLocalMediaStreamCreated=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},n.prototype.onSpeakerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},n.prototype.onMicrophoneDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},n.prototype.onRingerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},n.prototype.mute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!0}})},n.prototype.unmute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!1}})},n.prototype.setSpeakerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},n.prototype.setMicrophoneDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},n.prototype.setRingerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},n.prototype.getState=function(){return this._getData().snapshot.state},n.prototype.getNextState=function(){return this._getData().snapshot.nextState},n.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},n.prototype.getStatus=n.prototype.getState,n.prototype.getStateDuration=function(){return t.now()-this._getData().snapshot.state.startTimestamp.getTime()+t.core.getSkew()},n.prototype.getStatusDuration=n.prototype.getStateDuration,n.prototype.getPermissions=function(){return this.getConfiguration().permissions},n.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}))},n.prototype.getConfiguration=function(){return this._getData().configuration},n.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},n.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},n.prototype.getChannelConcurrency=function(e){var n=this.getRoutingProfile().channelConcurrencyMap;return n||(n=Object.keys(t.ChannelType).reduce((function(e,n){return"TASK"!==n&&(e[t.ChannelType[n]]=1),e}),{})),e?n[e]||0:n},n.prototype.getName=function(){return this.getConfiguration().name},n.prototype.getExtension=function(){return this.getConfiguration().extension},n.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},n.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},n.prototype.setConfiguration=function(e,n){var r=t.core.getClient();e&&e.agentPreferences&&!t.isValidLocale(e.agentPreferences.locale)?n&&n.failure&&n.failure(t.AgentErrorStates.INVALID_LOCALE):r.call(t.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:t.assertNotNull(e,"configuration")},{success:function(e){t.core.getUpstream().sendUpstream(t.EventType.RELOAD_AGENT_CONFIGURATION),n.success&&n.success(e)},failure:n&&n.failure})},n.prototype.setState=function(e,n,r){t.core.getClient().call(t.ClientMethods.PUT_AGENT_STATE,{state:t.assertNotNull(e,"state"),enqueueNextState:r&&!!r.enqueueNextState},n)},n.prototype.onEnqueuedNextState=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ENQUEUED_NEXT_STATE,e)},n.prototype.setStatus=n.prototype.setState,n.prototype.connect=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_OUTBOUND_CONTACT,{endpoint:t.assertNotNull(o,"endpoint"),queueARN:n&&(n.queueARN||n.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN},n&&{success:n.success,failure:n.failure})},n.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map((function(e){return e.queueARN}))},n.prototype.getEndpoints=function(e,n,r){var o=this,i=t.core.getClient();t.assertNotNull(n,"callbacks"),t.assertNotNull(n.success,"callbacks.success");var s=r||{};s.endpoints=s.endpoints||[],s.maxResults=s.maxResults||t.DEFAULT_BATCH_SIZE,t.isArray(e)||(e=[e]),i.call(t.ClientMethods.GET_ENDPOINTS,{queueARNs:e,nextToken:s.nextToken||null,maxResults:s.maxResults},{success:function(r){if(r.nextToken)o.getEndpoints(e,n,{nextToken:r.nextToken,maxResults:s.maxResults,endpoints:s.endpoints.concat(r.endpoints)});else{s.endpoints=s.endpoints.concat(r.endpoints);var i=s.endpoints.map((function(e){return new t.Endpoint(e)}));n.success({endpoints:i,addresses:i})}},failure:n.failure})},n.prototype.getAddresses=n.prototype.getEndpoints,n.prototype._getResourceId=function(){var e=this.getAllQueueARNs();for(let t of e){const e=t.match(/\/agent\/([^/]+)/);if(e)return e[1]}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",e)},n.prototype.toSnapshot=function(){return new t.AgentSnapshot(this._getData())};var r=function(e){t.Agent.call(this),this.agentData=e};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._getData=function(){return this.agentData},r.prototype._createContactAPI=function(e){return new t.ContactSnapshot(e)};var o=function(e){this.contactId=e};o.prototype._getData=function(){return t.core.getAgentDataProvider().getContactData(this.getContactId())},o.prototype._createConnectionAPI=function(e){return this.getType()===t.ContactType.CHAT?new t.ChatConnection(this.contactId,e.connectionId):this.getType()===t.ContactType.TASK?new t.TaskConnection(this.contactId,e.connectionId):new t.VoiceConnection(this.contactId,e.connectionId)},o.prototype.getEventName=function(e){return t.core.getContactEventName(e,this.getContactId())},o.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.REFRESH),e)},o.prototype.onIncoming=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.INCOMING),e)},o.prototype.onConnecting=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTING),e)},o.prototype.onPending=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.PENDING),e)},o.prototype.onAccepted=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACCEPTED),e)},o.prototype.onMissed=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.MISSED),e)},o.prototype.onEnded=function(e){var n=t.core.getEventBus();n.subscribe(this.getEventName(t.ContactEvents.ENDED),e),n.subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onDestroy=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onACW=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACW),e)},o.prototype.onConnected=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTED),e)},o.prototype.onError=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ERROR),e)},o.prototype.getContactId=function(){return this.contactId},o.prototype.getOriginalContactId=function(){return this._getData().initialContactId},o.prototype.getInitialContactId=o.prototype.getOriginalContactId,o.prototype.getType=function(){return this._getData().type},o.prototype.getContactDuration=function(){return this._getData().contactDuration},o.prototype.getState=function(){return this._getData().state},o.prototype.getStatus=o.prototype.getState,o.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},o.prototype.getStatusDuration=o.prototype.getStateDuration,o.prototype.getQueue=function(){return this._getData().queue},o.prototype.getQueueTimestamp=function(){return this._getData().queueTimestamp},o.prototype.getConnections=function(){var e=this;return this._getData().connections.map((function(n){return e.getType()===t.ContactType.CHAT?new t.ChatConnection(e.contactId,n.connectionId):e.getType()===t.ContactType.TASK?new t.TaskConnection(e.contactId,n.connectionId):new t.VoiceConnection(e.contactId,n.connectionId)}))},o.prototype.getInitialConnection=function(){return t.find(this.getConnections(),(function(e){return e.isInitialConnection()}))||null},o.prototype.getActiveInitialConnection=function(){var e=this.getInitialConnection();return null!=e&&e.isActive()?e:null},o.prototype.getThirdPartyConnections=function(){return this.getConnections().filter((function(e){return!e.isInitialConnection()&&e.getType()!==t.ConnectionType.AGENT}))},o.prototype.getSingleActiveThirdPartyConnection=function(){return this.getThirdPartyConnections().filter((function(e){return e.isActive()}))[0]||null},o.prototype.getAgentConnection=function(){return t.find(this.getConnections(),(function(e){var n=e.getType();return n===t.ConnectionType.AGENT||n===t.ConnectionType.MONITORING}))},o.prototype.getName=function(){return this._getData().name},o.prototype.getContactMetadata=function(){return this._getData().contactMetadata},o.prototype.getDescription=function(){return this._getData().description},o.prototype.getReferences=function(){return this._getData().references},o.prototype.getAttributes=function(){return this._getData().attributes},o.prototype.getContactFeatures=function(){return this._getData().contactFeatures},o.prototype.isSoftphoneCall=function(){return null!=t.find(this.getConnections(),(function(e){return null!=e.getSoftphoneMediaInfo()}))},o.prototype._isInbound=function(){return this._getData().initiationMethod!==t.ContactInitiationMethod.OUTBOUND},o.prototype.isInbound=function(){var e=this.getInitialConnection();return e.getMediaType()===t.MediaType.TASK?this._isInbound():!!e&&e.getType()===t.ConnectionType.INBOUND},o.prototype.isConnected=function(){return this.getStatus().type===t.ContactStateType.CONNECTED},o.prototype.accept=function(e){var n=t.core.getClient(),r=this,o=this.getContactId();n.call(t.ClientMethods.ACCEPT_CONTACT,{contactId:o},{success:function(n){var i=t.core.getUpstream();i.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(o)}),i.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,r.getContactId()),data:new t.Contact(o)});var s=new t.Contact(o);t.isFirefoxBrowser()&&s.isSoftphoneCall()&&t.core.triggerReadyToStartSessionEvent(),e&&e.success&&e.success(n)},failure:e?e.failure:null})},o.prototype.destroy=function(){t.getLog().warn("contact.destroy() has been deprecated.")},o.prototype.reject=function(e){t.core.getClient().call(t.ClientMethods.REJECT_CONTACT,{contactId:this.getContactId()},e)},o.prototype.complete=function(e){t.core.getClient().call(t.ClientMethods.COMPLETE_CONTACT,{contactId:this.getContactId()},e)},o.prototype.clear=function(e){t.core.getClient().call(t.ClientMethods.CLEAR_CONTACT,{contactId:this.getContactId()},e)},o.prototype.notifyIssue=function(e,n,r){t.core.getClient().call(t.ClientMethods.NOTIFY_CONTACT_ISSUE,{contactId:this.getContactId(),issueCode:e,description:n},r)},o.prototype.addConnection=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_ADDITIONAL_CONNECTION,{contactId:this.getContactId(),endpoint:o},n)},o.prototype.toggleActiveConnections=function(e){var n=t.core.getClient(),r=null,o=t.find(this.getConnections(),(function(e){return e.getStatus().type===t.ConnectionStateType.HOLD}));if(null!=o)r=o.getConnectionId();else{var i=this.getConnections().filter((function(e){return e.isActive()}));i.length>0&&(r=i[0].getConnectionId())}n.call(t.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:r},e)},o.prototype.sendSoftphoneMetrics=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,softphoneStreamStatistics:n},r),t.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:e.ccpVersion,stats:n})},o.prototype.sendSoftphoneReport=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n},r),t.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n})},o.prototype.conferenceConnections=function(e){t.core.getClient().call(t.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},o.prototype.toSnapshot=function(){return new t.ContactSnapshot(this._getData())},o.prototype.isMultiPartyConferenceEnabled=function(){var e=this.getContactFeatures();return!(!e||!e.multiPartyConferenceEnabled)};var i=function(e){t.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(o.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new t.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return t.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},s.prototype.getContactId=function(){return this.contactId},s.prototype.getConnectionId=function(){return this.connectionId},s.prototype.getEndpoint=function(){return new t.Endpoint(this._getData().endpoint)},s.prototype.getAddress=s.prototype.getEndpoint,s.prototype.getState=function(){return this._getData().state},s.prototype.getStatus=s.prototype.getState,s.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},s.prototype.getStatusDuration=s.prototype.getStateDuration,s.prototype.getType=function(){return this._getData().type},s.prototype.isInitialConnection=function(){return this._getData().initial},s.prototype.isActive=function(){return t.contains(t.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===t.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){t.core.getClient().call(t.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,n){t.core.getClient().call(t.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},n)},s.prototype.hold=function(e){t.core.getClient().call(t.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){t.core.getClient().call(t.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new t.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&t.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING};var a=function(e){this.contactId=e};a.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){n.call(t.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),awsAccountId:t.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var n={speakerId:e.contactData.customerId};t.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),r(n)}else{var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(i)}},failure:function(e){t.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(n)}})}))},a.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){var n=JSON.parse(e);switch(n.status){case 400:case 404:var i=n;i.type=i.type?i.type:t.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,t.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),r(i);break;default:t.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var s=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(s)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype._optOutSpeakerInLcms=function(e){var n=this,r=t.core.getClient();return new Promise((function(o,i){r.call(t.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:n.contactId,InstanceId:t.core.getAgentDataProvider().getInstanceId(),AWSAccountId:t.core.getAgentDataProvider().getAWSAccountId(),CustomerId:t.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){t.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){t.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);i(n)}})}))},a.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(s){var a=i.speakerId;n.call(t.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:t.assertNotNull(a,"speakerId"),DomainId:s},{success:function(n){e._optOutSpeakerInLcms(a).catch((function(){})),t.getLog().info("optOutSpeaker succeeded").withObject(n).sendInternalLogToServer(),r(n)},failure:function(e){t.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){t.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},a.prototype.startSession=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getDomainId().then((function(i){n.call(t.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),customerAccountId:t.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:i},{success:function(e){if(e.sessionId)r(e);else{t.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(n)}},failure:function(e){t.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(n)}})})).catch((function(e){o(e)}))}))},a.prototype.evaluateSpeaker=function(e){var n=this;n.checkConferenceCall();var r=t.core.getClient(),o=t.core.getAgentDataProvider().getContactData(this.contactId),i=0;return new Promise((function(s,a){function c(){n.getDomainId().then((function(e){r.call(t.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++i=1&&(o=r.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){t.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void n(i)}t.getLog().info("getDomainId succeeded").withObject(r).sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),i=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),n(i)}},failure:function(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var r=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);n(r)}}):n(new Error("Agent doesn't have the permission for Voice ID"))}))},a.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId is not supported for conference calls")},a.prototype.isAuthEnabled=function(e){return e!==t.ContactFlowAuthenticationDecision.NOT_ENABLED},a.prototype.isAuthResultNotEnoughSpeech=function(e){return e===t.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},a.prototype.isAuthResultInconclusive=function(e){return e===t.ContactFlowAuthenticationDecision.INCONCLUSIVE},a.prototype.isFraudEnabled=function(e){return e!==t.ContactFlowFraudDetectionDecision.NOT_ENABLED},a.prototype.isFraudResultNotEnoughSpeech=function(e){return e===t.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},a.prototype.isFraudResultInconclusive=function(e){return e===t.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var c=function(e,t){this._speakerAuthenticator=new a(e),s.call(this,e,t)};(c.prototype=Object.create(s.prototype)).constructor=c,c.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},c.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},c.prototype.getMediaType=function(){return t.MediaType.SOFTPHONE},c.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},c.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},c.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},c.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},c.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},c.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},c.prototype.enrollSpeakerInVoiceId=function(){return this._speakerAuthenticator.enrollSpeaker()},c.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},c.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},c.prototype.isMute=function(){return this._getData().mute},c.prototype.muteParticipant=function(e){t.core.getClient().call(t.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},c.prototype.unmuteParticipant=function(e){t.core.getClient().call(t.ClientMethods.UNMUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)};var u=function(e,t){s.call(this,e,t)};(u.prototype=Object.create(s.prototype)).constructor=u,u.prototype.getMediaInfo=function(){var e=this._getData().chatMediaInfo;if(e){var n=t.core.getAgentDataProvider().getContactData(this.contactId),r={contactId:this.contactId,initialContactId:n.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:t.hitch(this,this.getConnectionToken)};if(e.connectionData)try{r.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(n){t.getLog().error(t.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(n).sendInternalLogToServer(),r.participantToken=null}return r.participantToken=r.participantToken||null,r.originalInfo=this._getData().chatMediaInfo,r}return null},u.prototype.getConnectionToken=function(){var e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(this.contactId),r={transportType:t.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:n.initialContactId||this.contactId};return new Promise((function(n,o){e.call(t.ClientMethods.CREATE_TRANSPORT,r,{success:function(e){t.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),n(e)},failure:function(e,n){t.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:n}),o(Error("getConnectionToken failed"))}})}))},u.prototype.getMediaType=function(){return t.MediaType.CHAT},u.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},u.prototype._initMediaController=function(){this._isAgentConnectionType()&&t.core.mediaFactory.get(this).catch((function(){}))};var l=function(e,t){s.call(this,e,t)};(l.prototype=Object.create(s.prototype)).constructor=l,l.prototype.getMediaType=function(){return t.MediaType.TASK},l.prototype.getMediaInfo=function(){var e=t.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},l.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)};var p=function(e){t.Connection.call(this,e.contactId,e.connectionId),this.connectionData=e};(p.prototype=Object.create(s.prototype)).constructor=p,p.prototype._getData=function(){return this.connectionData},p.prototype._initMediaController=function(){};var h=function(e){var t=e||{};this.endpointARN=t.endpointId||t.endpointARN||null,this.endpointId=this.endpointARN,this.type=t.type||null,this.name=t.name||null,this.phoneNumber=t.phoneNumber||null,this.agentLogin=t.agentLogin||null,this.queue=t.queue||null};h.prototype.stripPhoneNumber=function(){return this.phoneNumber?this.phoneNumber.replace(/sip:([^@]*)@.*/,"$1"):""},h.byPhoneNumber=function(e,n){return new h({type:t.EndpointType.PHONE_NUMBER,phoneNumber:e,name:n||null})};var d=function(e,t,n){this.errorType=e,this.errorMessage=t,this.endPointUrl=n};d.prototype.getErrorType=function(){return this.errorType},d.prototype.getErrorMessage=function(){return this.errorMessage},d.prototype.getEndPointUrl=function(){return this.endPointUrl},t.agent=function(e){var n=t.core.getEventBus().subscribe(t.AgentEvents.INIT,e);return t.agent.initialized&&e(new t.Agent),n},t.agent.initialized=!1,t.contact=function(e){return t.core.getEventBus().subscribe(t.ContactEvents.INIT,e)},t.onWebsocketInitFailure=function(e){var n=t.core.getEventBus().subscribe(t.WebSocketEvents.INIT_FAILURE,e);return t.webSocketInitFailed&&e(),n},t.ifMaster=function(e,n,r,o){if(t.assertNotNull(e,"A topic must be provided."),t.assertNotNull(n,"A true callback must be provided."),!t.core.masterClient)return t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(r&&r());t.core.getMasterClient().call(t.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?n():r&&r()}})},t.becomeMaster=function(e,n,r){t.assertNotNull(e,"A topic must be provided."),t.core.masterClient?t.core.getMasterClient().call(t.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){n&&n()}}):(t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),r&&r())},t.Agent=n,t.AgentSnapshot=r,t.Contact=o,t.ContactSnapshot=i,t.Connection=c,t.BaseConnection=s,t.VoiceConnection=c,t.ChatConnection=u,t.TaskConnection=l,t.ConnectionSnapshot=p,t.Endpoint=h,t.Address=h,t.SoftphoneError=d,t.VoiceId=a}()},827:(e,t,n)=>{var r;!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return o(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var i=void 0,s=0;s-1});var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]","[object DataView]"];t.exports={isEmptyData:function(e){return"string"==typeof e?0===e.length:0===e.byteLength},convertToBuffer:function(e){return"string"==typeof e&&(e=new r(e,"utf8")),ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}}},{"buffer/":81}],12:[function(e,t,n){var r=e("./browserHashUtils");function o(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=r.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var o=new e;o.update(n),n=o.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),o=new Uint8Array(e.BLOCK_SIZE);o.set(n);for(var i=0;i>>32-o)+n&4294967295}function c(e,t,n,r,o,i,s){return a(t&n|~t&r,e,t,o,i,s)}function u(e,t,n,r,o,i,s){return a(t&r|n&~r,e,t,o,i,s)}function l(e,t,n,r,o,i,s){return a(t^n^r,e,t,o,i,s)}function p(e,t,n,r,o,i,s){return a(n^(t|~r),e,t,o,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(r.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=r.convertToBuffer(e),n=0,o=t.byteLength;for(this.bytesHashed+=o;o>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),o--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,r=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var a=this.bufferLength;a>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var c=new DataView(new ArrayBuffer(16));for(a=0;a<4;a++)c.setUint32(4*a,this.state[a],!0);var u=new o(c.buffer,c.byteOffset,c.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],i=t[3];n=c(n,r,o,i,e.getUint32(0,!0),7,3614090360),i=c(i,n,r,o,e.getUint32(4,!0),12,3905402710),o=c(o,i,n,r,e.getUint32(8,!0),17,606105819),r=c(r,o,i,n,e.getUint32(12,!0),22,3250441966),n=c(n,r,o,i,e.getUint32(16,!0),7,4118548399),i=c(i,n,r,o,e.getUint32(20,!0),12,1200080426),o=c(o,i,n,r,e.getUint32(24,!0),17,2821735955),r=c(r,o,i,n,e.getUint32(28,!0),22,4249261313),n=c(n,r,o,i,e.getUint32(32,!0),7,1770035416),i=c(i,n,r,o,e.getUint32(36,!0),12,2336552879),o=c(o,i,n,r,e.getUint32(40,!0),17,4294925233),r=c(r,o,i,n,e.getUint32(44,!0),22,2304563134),n=c(n,r,o,i,e.getUint32(48,!0),7,1804603682),i=c(i,n,r,o,e.getUint32(52,!0),12,4254626195),o=c(o,i,n,r,e.getUint32(56,!0),17,2792965006),n=u(n,r=c(r,o,i,n,e.getUint32(60,!0),22,1236535329),o,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,r,o,e.getUint32(24,!0),9,3225465664),o=u(o,i,n,r,e.getUint32(44,!0),14,643717713),r=u(r,o,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,r,o,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,r,o,e.getUint32(40,!0),9,38016083),o=u(o,i,n,r,e.getUint32(60,!0),14,3634488961),r=u(r,o,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,r,o,i,e.getUint32(36,!0),5,568446438),i=u(i,n,r,o,e.getUint32(56,!0),9,3275163606),o=u(o,i,n,r,e.getUint32(12,!0),14,4107603335),r=u(r,o,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,r,o,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,r,o,e.getUint32(8,!0),9,4243563512),o=u(o,i,n,r,e.getUint32(28,!0),14,1735328473),n=l(n,r=u(r,o,i,n,e.getUint32(48,!0),20,2368359562),o,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,r,o,e.getUint32(32,!0),11,2272392833),o=l(o,i,n,r,e.getUint32(44,!0),16,1839030562),r=l(r,o,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,r,o,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,r,o,e.getUint32(16,!0),11,1272893353),o=l(o,i,n,r,e.getUint32(28,!0),16,4139469664),r=l(r,o,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,r,o,i,e.getUint32(52,!0),4,681279174),i=l(i,n,r,o,e.getUint32(0,!0),11,3936430074),o=l(o,i,n,r,e.getUint32(12,!0),16,3572445317),r=l(r,o,i,n,e.getUint32(24,!0),23,76029189),n=l(n,r,o,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,r,o,e.getUint32(48,!0),11,3873151461),o=l(o,i,n,r,e.getUint32(60,!0),16,530742520),n=p(n,r=l(r,o,i,n,e.getUint32(8,!0),23,3299628645),o,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,r,o,e.getUint32(28,!0),10,1126891415),o=p(o,i,n,r,e.getUint32(56,!0),15,2878612391),r=p(r,o,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,r,o,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,r,o,e.getUint32(12,!0),10,2399980690),o=p(o,i,n,r,e.getUint32(40,!0),15,4293915773),r=p(r,o,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,r,o,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,r,o,e.getUint32(60,!0),10,4264355552),o=p(o,i,n,r,e.getUint32(24,!0),15,2734768916),r=p(r,o,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,r,o,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,r,o,e.getUint32(44,!0),10,3174756917),o=p(o,i,n,r,e.getUint32(8,!0),15,718787259),r=p(r,o,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=r+t[1]&4294967295,t[2]=o+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils");function i(){this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=new Uint32Array(80),this.offset=0,this.shift=24,this.totalLength=0}new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53),t.exports=i,i.BLOCK_SIZE=64,i.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=(e=o.convertToBuffer(e)).length;this.totalLength+=8*t;for(var n=0;n14||14===this.offset&&this.shift<24)&&this.processBlock(),this.offset=14,this.shift=24,this.write(0),this.write(0),this.write(this.totalLength>0xffffffffff?this.totalLength/1099511627776:0),this.write(this.totalLength>4294967295?this.totalLength/4294967296:0);for(var t=24;t>=0;t-=8)this.write(this.totalLength>>t);var n=new r(20),o=new DataView(n.buffer);return o.setUint32(0,this.h0,!1),o.setUint32(4,this.h1,!1),o.setUint32(8,this.h2,!1),o.setUint32(12,this.h3,!1),o.setUint32(16,this.h4,!1),e?n.toString(e):n},i.prototype.processBlock=function(){for(var e=16;e<80;e++){var t=this.block[e-3]^this.block[e-8]^this.block[e-14]^this.block[e-16];this.block[e]=t<<1|t>>>31}var n,r,o=this.h0,i=this.h1,s=this.h2,a=this.h3,c=this.h4;for(e=0;e<80;e++){e<20?(n=a^i&(s^a),r=1518500249):e<40?(n=i^s^a,r=1859775393):e<60?(n=i&s|a&(i|s),r=2400959708):(n=i^s^a,r=3395469782);var u=(o<<5|o>>>27)+n+c+r+(0|this.block[e]);c=a,a=s,s=i<<30|i>>>2,i=o,o=u}for(this.h0=this.h0+o|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+c|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils"),i=64,s=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=Math.pow(2,53)-1;function c(){this.state=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}t.exports=c,c.BLOCK_SIZE=i,c.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=0,n=(e=o.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>a)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},c.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=this.bufferLength;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var s=this.bufferLength;s>>24&255,a[4*s+1]=this.state[s]>>>16&255,a[4*s+2]=this.state[s]>>>8&255,a[4*s+3]=this.state[s]>>>0&255;return e?a.toString(e):a},c.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],a=t[3],c=t[4],u=t[5],l=t[6],p=t[7],h=0;h>>17|d<<15)^(d>>>19|d<<13)^d>>>10,g=((d=this.temp[h-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[h]=(f+this.temp[h-7]|0)+(g+this.temp[h-16]|0)}var m=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(p+(s[h]+this.temp[h]|0)|0)|0,v=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&o^r&o)|0;p=l,l=u,u=c,c=a+m|0,a=o,o=r,r=n,n=m+v|0}t[0]+=n,t[1]+=r,t[2]+=o,t[3]+=a,t[4]+=c,t[5]+=u,t[6]+=l,t[7]+=p}},{"./browserHashUtils":11,"buffer/":81}],16:[function(e,t,n){(function(n){(function(){var n=e("./util");n.crypto.lib=e("./browserCryptoLib"),n.Buffer=e("buffer/").Buffer,n.url=e("url/"),n.querystring=e("querystring/"),n.realClock=e("./realclock/browserClock"),n.environment="js",n.createEventStream=e("./event-stream/buffered-create-event-stream").createEventStream,n.isBrowser=function(){return!0},n.isNode=function(){return!1};var r=e("./core");if(t.exports=r,e("./credentials"),e("./credentials/credential_provider_chain"),e("./credentials/temporary_credentials"),e("./credentials/chainable_temporary_credentials"),e("./credentials/web_identity_credentials"),e("./credentials/cognito_identity_credentials"),e("./credentials/saml_credentials"),r.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===o)var o={browser:!0}}).call(this)}).call(this,e("_process"))},{"./browserCryptoLib":10,"./core":18,"./credentials":19,"./credentials/chainable_temporary_credentials":20,"./credentials/cognito_identity_credentials":21,"./credentials/credential_provider_chain":22,"./credentials/saml_credentials":23,"./credentials/temporary_credentials":24,"./credentials/web_identity_credentials":25,"./event-stream/buffered-create-event-stream":27,"./http/xhr":35,"./realclock/browserClock":52,"./util":71,"./xml/browser_parser":72,_process:86,"buffer/":81,"querystring/":92,"url/":94}],17:[function(e,t,n){var r,o=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),o.Config=o.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),o.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function r(t){e(t,t?null:n.credentials)}function i(e,t){return new o.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get((function(e){e&&(e=i("Could not load credentials from "+n.credentials.constructor.name,e)),r(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),r(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,r(e)})):r(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),o.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||o.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(o.util.readFileSync(e)),n=new o.FileSystemCredentials(e),r=new o.CredentialProviderChain;return r.providers.unshift(n),r.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){o.util.each.call(this,this.keys,(function(e){delete this[e]})),this.set("credentials",void 0),this.set("credentialProvider",void 0)},set:function(e,t,n){void 0===t?(void 0===n&&(n=this.keys[e]),this[e]="function"==typeof n?n.call(this):n):"httpOptions"===e&&this[e]?this[e]=o.util.merge(this[e],t):this[e]=t},keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:void 0,httpOptions:{timeout:12e4},maxRetries:void 0,maxRedirects:10,paramValidation:!0,sslEnabled:!0,s3ForcePathStyle:!1,s3BucketEndpoint:!1,s3DisableBodySigning:!0,computeChecksums:!0,convertResponseTypes:!0,correctClockSkew:!1,customUserAgent:null,dynamoDbCrc32:!0,systemClockOffset:0,signatureVersion:null,signatureCache:!0,retryDelayOptions:{},useAccelerateEndpoint:!1,clientSideMonitoring:!1,endpointDiscoveryEnabled:!1,endpointCacheSize:1e3,hostPrefixEnabled:!0,stsRegionalEndpoints:null},extractCredentials:function(e){return e.accessKeyId&&e.secretAccessKey&&((e=o.util.copy(e)).credentials=new o.Credentials(e)),e},setPromisesDependency:function(e){r=e,null===e&&"function"==typeof Promise&&(r=Promise);var t=[o.Request,o.Credentials,o.CredentialProviderChain];o.S3&&(t.push(o.S3),o.S3.ManagedUpload&&t.push(o.S3.ManagedUpload)),o.util.addPromises(t,r)},getPromisesDependency:function(){return r}}),o.config=new o.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var r={util:e("./util")};({}).toString(),t.exports=r,r.util.update(r,{VERSION:"2.553.0",Signers:{},Protocol:{Json:e("./protocol/json"),Query:e("./protocol/query"),Rest:e("./protocol/rest"),RestJson:e("./protocol/rest_json"),RestXml:e("./protocol/rest_xml")},XML:{Builder:e("./xml/builder"),Parser:null},JSON:{Builder:e("./json/builder"),Parser:e("./json/parser")},Model:{Api:e("./model/api"),Operation:e("./model/operation"),Shape:e("./model/shape"),Paginator:e("./model/paginator"),ResourceWaiter:e("./model/resource_waiter")},apiLoader:e("./api_loader"),EndpointCache:e("../vendor/endpoint-cache").EndpointCache}),e("./sequential_executor"),e("./service"),e("./config"),e("./http"),e("./event_listeners"),e("./request"),e("./response"),e("./resource_waiter"),e("./signers/request_signer"),e("./param_validator"),r.events=new r.SequentialExecutor,r.util.memoizedProperty(r,"endpointCache",(function(){return new r.EndpointCache(r.config.endpointCacheSize)}),!0)},{"../vendor/endpoint-cache":103,"./api_loader":9,"./config":17,"./event_listeners":33,"./http":34,"./json/builder":36,"./json/parser":37,"./model/api":38,"./model/operation":40,"./model/paginator":41,"./model/resource_waiter":42,"./model/shape":43,"./param_validator":44,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./request":55,"./resource_waiter":56,"./response":57,"./sequential_executor":58,"./service":59,"./signers/request_signer":63,"./util":71,"./xml/builder":73}],19:[function(e,t,n){var r=e("./core");r.Credentials=r.util.inherit({constructor:function(){if(r.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"==typeof arguments[0]){var e=arguments[0].credentials||arguments[0];this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken}else this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2]},expiryWindow:15,needsRefresh:function(){var e=r.util.date.getDate().getTime(),t=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&t>this.expireTime)||this.expired||!this.accessKeyId||!this.secretAccessKey},get:function(e){var t=this;this.needsRefresh()?this.refresh((function(n){n||(t.expired=!1),e&&e(n)})):e&&e()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,t){var n=this;1===n.refreshCallbacks.push(e)&&n.load((function(e){r.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):r.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),r.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=r.util.promisifyMethod("get",e),this.prototype.refreshPromise=r.util.promisifyMethod("refresh",e)},r.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},r.util.addPromises(r.Credentials)},{"./core":18}],20:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.ChainableTemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=r.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new r.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=r.util.merge({params:t,credentials:e.masterCredentials||r.config.credentials},e.stsConfig||{});this.service=new o(n)},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(r,o){var i={};r?e(r):(o&&(i.TokenCode=o),t.service[n](i,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,o){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(r.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,o)})):e(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var r=e("../core"),o=e("../../clients/cognitoidentity"),i=e("../../clients/sts");r.CognitoIdentityCredentials=r.util.inherit(r.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=r.util.copy(t||{}),this.loadCachedId();var n=this;Object.defineProperty(this,"identityId",{get:function(){return n.loadCachedId(),n._identityId||n.params.IdentityId},set:function(e){n._identityId=e}})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.data=null,t._identityId=null,t.getId((function(n){n?(t.clearIdOnNotAuthorized(n),e(n)):t.params.RoleArn?t.getCredentialsFromSTS(e):t.getCredentialsForIdentity(e)}))},clearCachedId:function(){this._identityId=null,delete this.params.IdentityId;var e=this.params.IdentityPoolId,t=this.params.LoginId||"";delete this.storage[this.localStorageKey.id+e+t],delete this.storage[this.localStorageKey.providers+e+t]},clearIdOnNotAuthorized:function(e){"NotAuthorizedException"==e.code&&this.clearCachedId()},getId:function(e){var t=this;if("string"==typeof t.params.IdentityId)return e(null,t.params.IdentityId);t.cognito.getId((function(n,r){!n&&r.IdentityId?(t.params.IdentityId=r.IdentityId,e(null,r.IdentityId)):e(n)}))},loadCredentials:function(e,t){e&&t&&(t.expired=!1,t.accessKeyId=e.Credentials.AccessKeyId,t.secretAccessKey=e.Credentials.SecretKey,t.sessionToken=e.Credentials.SessionToken,t.expireTime=e.Credentials.Expiration)},getCredentialsForIdentity:function(e){var t=this;t.cognito.getCredentialsForIdentity((function(n,r){n?t.clearIdOnNotAuthorized(n):(t.cacheId(r),t.data=r,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,r){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(r),t.params.WebIdentityToken=r.Token,t.webIdentityCredentials.refresh((function(n){n||(t.data=t.webIdentityCredentials.data,t.sts.credentialsFrom(t.data,t)),e(n)})))}))},loadCachedId:function(){var e=this;if(r.util.isBrowser()&&!e.params.IdentityId){var t=e.getStorage("id");if(t&&e.params.Logins){var n=Object.keys(e.params.Logins);0!==(e.getStorage("providers")||"").split(",").filter((function(e){return-1!==n.indexOf(e)})).length&&(e.params.IdentityId=t)}else t&&(e.params.IdentityId=t)}},createClients:function(){var e=this._clientConfig;if(this.webIdentityCredentials=this.webIdentityCredentials||new r.WebIdentityCredentials(this.params,e),!this.cognito){var t=r.util.merge({},e);t.params=this.params,this.cognito=new o(t)}this.sts=this.sts||new i(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,r.util.isBrowser()&&(this.setStorage("id",e.IdentityId),this.params.Logins&&this.setStorage("providers",Object.keys(this.params.Logins).join(",")))},getStorage:function(e){return this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]},setStorage:function(e,t){try{this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]=t}catch(e){}},storage:function(){try{var e=r.util.isBrowser()&&null!==window.localStorage&&"object"==typeof window.localStorage?window.localStorage:{};return e["aws.test-storage"]="foobar",delete e["aws.test-storage"],e}catch(e){return{}}}()})},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(e,t,n){var r=e("../core");r.CredentialProviderChain=r.util.inherit(r.Credentials,{constructor:function(e){this.providers=e||r.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var t=this;if(0===t.providers.length)return e(new Error("No providers")),t;if(1===t.resolveCallbacks.push(e)){var n=0,o=t.providers.slice(0);!function e(i,s){if(!i&&s||n===o.length)return r.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var a=o[n++];(s="function"==typeof a?a.call():a).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),r.CredentialProviderChain.defaultProviders=[],r.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=r.util.promisifyMethod("resolve",e)},r.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},r.util.addPromises(r.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.SAMLCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.TemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.loadMasterCredentials(t),this.expired=!0,this.params=e||{},this.params.RoleArn&&(this.params.RoleSessionName=this.params.RoleSessionName||"temporary-credentials")},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.masterCredentials.get((function(){t.service.config.credentials=t.masterCredentials,(t.params.RoleArn?t.service.assumeRole:t.service.getSessionToken).call(t.service,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||r.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new r.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.WebIdentityCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=r.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,r){t.data=null,n||(t.data=r,t.service.credentialsFrom(r,t)),e(n)}))},createClients:function(){if(!this.service){var e=r.util.merge({},this._clientConfig);e.params=this.params,this.service=new o(e)}}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},r=(n.operations,{});return t.config.region&&(r.region=t.config.region),n.serviceId&&(r.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(r.accessKeyId=t.config.credentials.accessKeyId),r}function a(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&o.arrayEach(n.required,(function(r){var o=n.members[r];if(!0===o.endpointDiscoveryId){var i=o.isLocationName?o.name:r;e[i]=String(t[r])}else a(e,t[r],o)}))}function c(e,t){var n={};return a(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,a=c(e,i?i.input:void 0),u=s(e);Object.keys(a).length>0&&(u=o.update(u,a),i&&(u.operation=i.name));var l=r.endpointCache.get(u);if(!l||1!==l.length||""!==l[0].Address)if(l&&l.length>0)e.httpRequest.updateEndpoint(l[0].Address);else{var p=t.makeRequest(n.endpointOperation,{Operation:i.name,Identifiers:a});h(p),p.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",r.EventListeners.Core.RETRY_CHECK),r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?r.endpointCache.put(u,t.Endpoints):e&&r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,a=i.operations?i.operations[e.operation]:void 0,u=a?a.input:void 0,p=c(e,u),d=s(e);Object.keys(p).length>0&&(d=o.update(d,p),a&&(d.operation=a.name));var f=r.EndpointCache.getKeyString(d),g=r.endpointCache.get(f);if(g&&1===g.length&&""===g[0].Address)return l[f]||(l[f]=[]),void l[f].push({request:e,callback:t});if(g&&g.length>0)e.httpRequest.updateEndpoint(g[0].Address),t();else{var m=n.makeRequest(i.endpointOperation,{Operation:a.name,Identifiers:p});m.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),h(m),r.endpointCache.put(f,[{Address:"",CachePeriodInMinutes:60}]),m.send((function(n,i){if(n){var s={code:"EndpointDiscoveryException",message:"Request cannot be fulfilled without specifying an endpoint",retryable:!1};if(e.response.error=o.error(n,s),r.endpointCache.remove(d),l[f]){var a=l[f];o.arrayEach(a,(function(e){e.request.response.error=o.error(n,s),e.callback()})),delete l[f]}}else i&&(r.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(a=l[f],o.arrayEach(a,(function(e){e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address),e.callback()})),delete l[f]);t()}))}}function h(e){var t=e.service.api.apiVersion;t&&!e.httpRequest.headers["x-amz-api-version"]&&(e.httpRequest.headers["x-amz-api-version"]=t)}function d(e){var t=e.error,n=e.httpResponse;if(t&&("InvalidEndpointException"===t.code||421===n.statusCode)){var i=e.request,a=i.service.api.operations||{},u=c(i,a[i.operation]?a[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=o.update(l,u),a[i.operation]&&(l.operation=a[i.operation].name)),r.endpointCache.remove(l)}}function f(e){return["false","0"].indexOf(e)>=0}t.exports={discoverEndpoint:function(e,t){var s=e.service||{};if(function(e){if(e._originalConfig&&e._originalConfig.endpoint&&!0===e._originalConfig.endpointDiscoveryEnabled)throw o.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=r.config[e.serviceIdentifier]||{};return Boolean(r.config.endpoint||t.endpoint||e._originalConfig&&e._originalConfig.endpoint)}(s)||e.isPresigned())return t();if(!function(e){if(!0===(e.service||{}).config.endpointDiscoveryEnabled)return!0;if(o.isBrowser())return!1;for(var t=0;t-1&&(e[t]++,0===e[t]);t--);}i.fromNumber=function(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(e+" is too large (or, if negative, too small) to represent as an Int64");for(var t=new Uint8Array(8),n=7,r=Math.abs(Math.round(e));n>-1&&r>0;n--,r/=256)t[n]=r;return e<0&&s(t),new i(t)},i.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&s(e),parseInt(e.toString("hex"),16)*(t?-1:1)},i.prototype.toString=function(){return String(this.valueOf())},t.exports={Int64:i}},{"../core":18}],30:[function(e,t,n){var r=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var o=r(t),i=o.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],r=new Error(n.value||n);return r.code=r.name=t.value||t,r}(o);if("event"!==i.value)return}var s=o.headers[":event-type"],a=n.members[s.value];if(a){var c={},u=a.eventPayloadMemberName;if(u){var l=a.members[u];"binary"===l.type?c[u]=o.body:c[u]=e.parse(o.body.toString(),l)}for(var p=a.eventHeaderMemberNames,h=0;h=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();r.util.computeSha256(i,(function(n,r){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=r,t())}))}else t()}})),e("SET_CONTENT_LENGTH","afterBuild",(function(e){var t=function(e){if(!e.service.api.operations)return"";var t=e.service.api.operations[e.operation];return t?t.authtype:""}(e),n=r.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var o=r.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=o}catch(r){if(n&&n.isStreaming){if(n.requiresLength)throw r;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw r}throw r}})),e("SET_HTTP_HOST","afterBuild",(function(e){e.httpRequest.headers.Host=e.httpRequest.endpoint.host})),e("RESTART","restart",(function(){var e=this.response.error;e&&e.retryable&&(this.httpRequest=new r.HttpRequest(this.service.endpoint,this.service.region),this.response.retryCount=600?this.emit("sign",[this],(function(e){e?t(e):i()})):i()})),e("HTTP_HEADERS","httpHeaders",(function(e,t,n,o){n.httpResponse.statusCode=e,n.httpResponse.statusMessage=o,n.httpResponse.headers=t,n.httpResponse.body=r.util.buffer.toBuffer(""),n.httpResponse.buffers=[],n.httpResponse.numBytes=0;var i=t.date||t.Date,s=n.request.service;if(i){var a=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(a)&&s.applyClockOffset(a)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(r.util.isNode()){t.httpResponse.numBytes+=e.length;var n=t.httpResponse.headers["content-length"],o={loaded:t.httpResponse.numBytes,total:n};t.request.emit("httpDownloadProgress",[o,t])}t.httpResponse.buffers.push(r.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=r.util.buffer.concat(e.httpResponse.buffers);e.httpResponse.body=t}delete e.httpResponse.numBytes,delete e.httpResponse.buffers})),e("FINALIZE_ERROR","retry",(function(e){e.httpResponse.statusCode&&(e.error.statusCode=e.httpResponse.statusCode,void 0===e.error.retryable&&(e.error.retryable=this.service.retryableError(e.error,this)))})),e("INVALIDATE_CREDENTIALS","retry",(function(e){if(e.error)switch(e.error.code){case"RequestExpired":case"ExpiredTokenException":case"ExpiredToken":e.error.retryable=!0,e.request.service.config.credentials.expired=!0}})),e("EXPIRED_SIGNATURE","retry",(function(e){var t=e.error;t&&"string"==typeof t.code&&"string"==typeof t.message&&t.code.match(/Signature/)&&t.message.match(/expired/)&&(e.error.retryable=!0)})),e("CLOCK_SKEWED","retry",(function(e){e.error&&this.service.clockSkewError(e.error)&&this.service.config.correctClockSkew&&(e.error.retryable=!0)})),e("REDIRECT","retry",(function(e){e.error&&e.error.statusCode>=300&&e.error.statusCode<400&&e.httpResponse.headers.location&&(this.httpRequest.endpoint=new r.Endpoint(e.httpResponse.headers.location),this.httpRequest.headers.Host=this.httpRequest.endpoint.host,e.error.redirect=!0,e.error.retryable=!0)})),e("RETRY_CHECK","retry",(function(e){e.error&&(e.error.redirect&&e.redirectCount=this.HEADERS_RECEIVED&&!p&&(c.statusCode=l.status,c.headers=s.parseHeaders(l.getAllResponseHeaders()),c.emit("headers",c.statusCode,c.headers,l.statusText),p=!0),this.readyState===this.DONE&&s.finishRequest(l,c)}),!1),l.upload.addEventListener("progress",(function(e){c.emit("sendProgress",e)})),l.addEventListener("progress",(function(e){c.emit("receiveProgress",e)}),!1),l.addEventListener("timeout",(function(){i(r.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),l.addEventListener("error",(function(){i(r.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),l.addEventListener("abort",(function(){i(r.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(c),l.open(e.method,u,!1!==t.xhrAsync),r.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&l.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(l.timeout=t.timeout),t.xhrWithCredentials&&(l.withCredentials=!0);try{l.responseType="arraybuffer"}catch(e){}try{e.body?l.send(e.body):l.send()}catch(t){if(!e.body||"object"!=typeof e.body.buffer)throw t;l.send(e.body.buffer)}return c},parseHeaders:function(e){var t={};return r.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],r=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=r)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var o=e.response;n=new r.util.Buffer(o.byteLength);for(var i=new Uint8Array(o),s=0;s-1?t||"":t,this.isJsonValue?JSON.parse(t):t&&"function"==typeof t.toString?t.toString():t},this.toWireFormat=function(e){return this.isJsonValue?JSON.stringify(e):e}}function d(){a.apply(this,arguments),this.toType=function(e){var t=o.base64.decode(e);if(this.isSensitive&&o.isNode()&&"function"==typeof o.Buffer.alloc){var n=o.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=o.base64.encode}function f(){d.apply(this,arguments)}function g(){a.apply(this,arguments),this.toType=function(e){return"boolean"==typeof e?e:null==e?null:"true"===e}}a.normalizedTypes={character:"string",double:"float",long:"integer",short:"integer",biginteger:"integer",bigdecimal:"float",blob:"binary"},a.types={structure:u,list:l,map:p,boolean:g,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)i(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)i(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)i(this,"timestampFormat","rfc822");else if("querystring"===this.location)i(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":i(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":i(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?o.date.parseTimestamp(e):null},this.toWireFormat=function(e){return o.date.format(e,t.timestampFormat)}},float:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseFloat(e)},this.toWireFormat=this.toType},integer:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseInt(e,10)},this.toWireFormat=this.toType},string:h,base64:f,binary:d},a.resolve=function(e,t){if(e.shape){var n=t.api.shapes[e.shape];if(!n)throw new Error("Cannot find shape reference: "+e.shape);return n}return null},a.create=function(e,t,n){if(e.isShape)return e;var r=a.resolve(e,t);if(r){var o=Object.keys(e);t.documentation||(o=o.filter((function(e){return!e.match(/documentation/)})));var i=function(){r.constructor.call(this,e,t,n)};return i.prototype=r,new i}e.type||(e.members?e.type="structure":e.member?e.type="list":e.key?e.type="map":e.type="string");var s=e.type;if(a.normalizedTypes[e.type]&&(e.type=a.normalizedTypes[e.type]),a.types[e.type])return new a.types[e.type](e,t,n);throw new Error("Unrecognized shape type: "+s)},a.shapes={StructureShape:u,ListShape:l,MapShape:p,StringShape:h,BooleanShape:g,Base64Shape:f},t.exports=a},{"../util":71,"./collection":39}],44:[function(e,t,n){var r=e("./core");r.ParamValidator=r.util.inherit({constructor:function(e){!0!==e&&void 0!==e||(e={min:!0}),this.validation=e},validate:function(e,t,n){if(this.errors=[],this.validateMember(e,t||{},n||"params"),this.errors.length>1){var o=this.errors.join("\n* ");throw o="There were "+this.errors.length+" validation errors:\n* "+o,r.util.error(new Error(o),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(r.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){var r;this.validateType(t,n,["object"],"structure");for(var o=0;e.required&&o= 1, but found "'+t+'" for '+n)},validatePattern:function(e,t,n){this.validation.pattern&&void 0!==e.pattern&&(new RegExp(e.pattern).test(t)||this.fail("PatternMatchError",'Provided value "'+t+'" does not match regex pattern /'+e.pattern+"/ for "+n))},validateRange:function(e,t,n,r){this.validation.min&&void 0!==e.min&&t= "+e.min+", but found "+t+" for "+n),this.validation.max&&void 0!==e.max&&t>e.max&&this.fail("MaxRangeError","Expected "+r+" <= "+e.max+", but found "+t+" for "+n)},validateEnum:function(e,t,n){this.validation.enum&&void 0!==e.enum&&-1===e.enum.indexOf(t)&&this.fail("EnumError","Found string value of "+t+", but expected "+e.enum.join("|")+" for "+n)},validateType:function(e,t,n,o){if(null==e)return!1;for(var i=!1,s=0;s63)throw r.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw o.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":18,"../util":71}],46:[function(e,t,n){var r=e("../util"),o=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,r=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",a=n.operations[e.operation].input,c=new o;1===i&&(i="1.0"),t.body=c.build(e.params||{},a),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=r,s(e)},extractError:function(e){var t={},n=e.httpResponse;if(t.code=n.headers["x-amzn-errortype"]||"UnknownError","string"==typeof t.code&&(t.code=t.code.split(":")[0]),n.body.length>0)try{var o=JSON.parse(n.body.toString());(o.__type||o.code)&&(t.code=(o.__type||o.code).split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=o.message||o.Message||null}catch(o){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=r.error(new Error,t)},extractData:function(e){var t=e.httpResponse.body.toString()||"{}";if(!1===e.request.service.config.convertResponseTypes)e.data=JSON.parse(t);else{var n=e.request.service.api.operations[e.request.operation].output||{},r=new i;e.data=r.parse(t,n)}}}},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(e,t,n){var r=e("../core"),o=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),a=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.service.api.operations[e.operation],n=e.httpRequest;n.headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8",n.params={Version:e.service.api.apiVersion,Action:t.name},(new i).serialize(e.params,t.input,(function(e,t){n.params[e]=t})),n.body=o.queryParamsToString(n.params),a(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var c=[];r.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new r.XML.Parser).parse(s.toString(),c);o.update(e.data,p)}}}},{"../core":18,"../util":71,"./rest":48}],51:[function(e,t,n){var r=e("../util");function o(){}function i(e){return e.isQueryName||"ec2"!==e.api.protocol?e.name:e.name[0].toUpperCase()+e.name.substr(1)}function s(e,t,n,o){r.each(n.members,(function(n,r){var s=t[n];if(null!=s){var c=i(r);a(c=e?e+"."+c:c,s,r,o)}}))}function a(e,t,n,o){null!=t&&("structure"===n.type?s(e,t,n,o):"list"===n.type?function(e,t,n,o){var s=n.member||{};0!==t.length?r.arrayEach(t,(function(t,r){var c="."+(r+1);if("ec2"===n.api.protocol)c+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else c="."+(s.name?s.name:"member")+c;a(e+c,t,s,o)})):o.call(this,e,null)}(e,t,n,o):"map"===n.type?function(e,t,n,o){var i=1;r.each(t,(function(t,r){var s=(n.flattened?".":".entry.")+i+++".",c=s+(n.key.name||"key"),u=s+(n.value.name||"value");a(e+c,t,n.key,o),a(e+u,r,n.value,o)}))}(e,t,n,o):o(e,n.toWireFormat(t).toString()))}o.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=o},{"../util":71}],52:[function(e,t,n){t.exports={now:function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}}},{}],53:[function(e,t,n){var r=e("./util"),o=e("./region_config_data.json");function i(e,t){r.each(t,(function(t,n){"globalEndpoint"!==t&&(void 0!==e.config[t]&&null!==e.config[t]||(e.config[t]=n))}))}t.exports=function(e){for(var t=function(e){var t=e.config.region,n=function(e){if(!e)return null;var t=e.split("-");return t.length<3?null:t.slice(0,t.length-2).join("-")+"-*"}(t),r=e.api.endpointPrefix;return[[t,r],[n,r],[t,"*"],[n,"*"],["*",r],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=0;n=0){c=!0;var u=0}var l=function(){c&&u!==a?o.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+a+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?o.end():o.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(c){var h=new e.PassThrough;h._write=function(t){return t&&t.length&&(u+=t.length),e.PassThrough.prototype._write.apply(this,arguments)},h.on("end",l),o.on("error",(function(e){c=!1,p.unpipe(h),h.emit("end"),h.end()})),p.pipe(h).pipe(o,{end:!1})}else p.pipe(o);else c&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){o.emit("data",e)})),p.on("end",l);p.on("error",(function(e){c=!1,o.emit("error",e)}))}})),o},emitEvent:function(e,t,r){"function"==typeof t&&(r=t,t=null),r||(r=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),r.call(this,e)}))},eventParameters:function(e){switch(e){case"restart":case"validate":case"sign":case"build":case"afterValidate":case"afterBuild":return[this];case"error":return[this.response.error,this.response];default:return[this.response]}},presign:function(e,t){return t||"function"!=typeof e||(t=e,e=null),(new n.Signers.Presign).sign(this.toGet(),e,t)},isPresigned:function(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,"presigned-expires")},toUnauthenticated:function(){return this._unAuthenticated=!0,this.removeListener("validate",n.EventListeners.Core.VALIDATE_CREDENTIALS),this.removeListener("sign",n.EventListeners.Core.SIGN),this},toGet:function(){return"query"!==this.service.api.protocol&&"ec2"!==this.service.api.protocol||(this.removeListener("build",this.buildAsGet),this.addListener("build",this.buildAsGet)),this},buildAsGet:function(e){e.httpRequest.method="GET",e.httpRequest.path=e.service.endpoint.path+"?"+e.httpRequest.body,e.httpRequest.body="",delete e.httpRequest.headers["Content-Length"],delete e.httpRequest.headers["Content-Type"]},haltHandlersOnError:function(){this._haltHandlersOnError=!0}}),n.Request.addPromisesToClass=function(e){this.prototype.promise=function(){var t=this;return this.httpRequest.appendToUserAgent("promise"),new e((function(e,n){t.on("complete",(function(t){t.error?n(t.error):e(Object.defineProperty(t.data||{},"$response",{value:t}))})),t.runTo()}))}},n.Request.deletePromisesFromClass=function(){delete this.prototype.promise},n.util.addPromises(n.Request),n.util.mixin(n.Request,n.SequentialExecutor)}).call(this)}).call(this,e("_process"))},{"./core":18,"./state_machine":70,_process:86,jmespath:85}],56:[function(e,t,n){var r=e("./core"),o=r.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,r=!1,o="retry";n.forEach((function(n){if(!r){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(r=!0,o=n.state)}})),!r&&e.error&&(o="failure"),"success"===o?t.setSuccess(e):t.setError(e,"retry"===o)}r.ResourceWaiter=o({constructor:function(e,t){this.service=e,this.state=t,this.loadWaiterConfig(this.state)},service:null,state:null,config:null,matchers:{path:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(r,t)},pathAll:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}Array.isArray(r)||(r=[r]);var o=r.length;if(!o)return!1;for(var s=0;s-1&&n.splice(o,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var r=this.listeners(e),o=r.length;return this.callListeners(r,t,n),o>0},callListeners:function(e,t,n,o){var i=this,s=o||null;function a(o){if(o&&(s=r.util.error(s||new Error,o),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var c=e.shift();if(c._isAsync)return void c.apply(i,t.concat([a]));try{c.apply(i,t)}catch(e){s=r.util.error(s||new Error,e)}if(s&&i._haltHandlersOnError)return void n.call(i,s)}n.call(i,s)},addListeners:function(e){var t=this;return e._events&&(e=e._events),r.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),r.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,r){return this[e]=n,this.addListener(t,n,r),this},addNamedAsyncListener:function(e,t,n,r){return n._isAsync=!0,this.addNamedListener(e,t,n,r)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),r.SequentialExecutor.prototype.addListener=r.SequentialExecutor.prototype.on,t.exports=r.SequentialExecutor},{"./core":18}],59:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./model/api"),i=e("./region_config"),s=r.util.inherit,a=0;r.Service=s({constructor:function(e){if(!this.loadServiceClass)throw r.util.error(new Error,"Service must be constructed with `new' operator");var t=this.loadServiceClass(e||{});if(t){var n=r.util.copy(e),o=new t(e);return Object.defineProperty(o,"_originalConfig",{get:function(){return n},enumerable:!1,configurable:!0}),o._clientId=++a,o}this.initialize(e)},initialize:function(e){var t=r.config[this.serviceIdentifier];if(this.config=new r.Config(r.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||i(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),r.SequentialExecutor.call(this),r.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||r.Service._clientSideMonitoring)&&this.publisher){var o=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){o.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){o.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(r.util.isEmpty(this.api)){if(t.apiConfig)return r.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new r.Config(r.config)).update(e,!0);var n=t.apiVersions[this.constructor.serviceIdentifier];return n=n||t.apiVersion,this.getLatestServiceClass(n)}return null}return null},getLatestServiceClass:function(e){return e=this.getLatestServiceVersion(e),null===this.constructor.services[e]&&r.Service.defineServiceApi(this.constructor,e),this.constructor.services[e]},getLatestServiceVersion:function(e){if(!this.constructor.services||0===this.constructor.services.length)throw new Error("No services defined on "+this.constructor.serviceIdentifier);if(e?r.util.isType(e,Date)&&(e=r.util.date.iso8601(e).split("T")[0]):e="latest",Object.hasOwnProperty(this.constructor.services,e))return e;for(var t=Object.keys(this.constructor.services).sort(),n=null,o=t.length-1;o>=0;o--)if("*"!==t[o][t[o].length-1]&&(n=t[o]),t[o].substr(0,10)<=e)return n;throw new Error("Could not find "+this.constructor.serviceIdentifier+" API to satisfy version constraint `"+e+"'")},api:{},defaultRetryCount:3,customizeRequests:function(e){if(e){if("function"!=typeof e)throw new Error("Invalid callback type '"+typeof e+"' provided in customizeRequests");this.customRequestHandler=e}else this.customRequestHandler=null},makeRequest:function(e,t,n){if("function"==typeof t&&(n=t,t=null),t=t||{},this.config.params){var o=this.api.operations[e];o&&(t=r.util.copy(t),r.util.each(this.config.params,(function(e,n){o.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new r.Request(this,e,t);return this.addAllRequestListeners(i),this.attachMonitoringEmitter(i),n&&i.send(n),i},makeUnauthenticatedRequest:function(e,t,n){"function"==typeof t&&(n=t,t={});var r=this.makeRequest(e,t).toUnauthenticated();return n?r.send(n):r},waitFor:function(e,t,n){return new r.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[r.events,r.EventListeners.Core,this.serviceInterface(),r.EventListeners.CorePost],n=0;n299?(o.code&&(n.FinalAwsException=o.code),o.message&&(n.FinalAwsExceptionMessage=o.message)):((o.code||o.name)&&(n.FinalSdkException=o.code||o.name),o.message&&(n.FinalSdkExceptionMessage=o.message))}return n},apiAttemptEvent:function(e){var t=e.service.api.operations[e.operation],n={Type:"ApiCallAttempt",Api:t?t.name:e.operation,Version:1,Service:e.service.api.serviceId||e.service.api.endpointPrefix,Fqdn:e.httpRequest.endpoint.hostname,UserAgent:e.httpRequest.getUserAgent()},r=e.response;return r.httpResponse.statusCode&&(n.HttpStatusCode=r.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),r.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),r.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=r.httpResponse.headers["x-amzn-requestid"]),r.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=r.httpResponse.headers["x-amz-request-id"]),r.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=r.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,r=n.error;return n.httpResponse.statusCode>299?(r.code&&(t.AwsException=r.code),r.message&&(t.AwsExceptionMessage=r.message)):((r.code||r.name)&&(t.SdkException=r.code||r.name),r.message&&(t.SdkExceptionMessage=r.message)),t},attachMonitoringEmitter:function(e){var t,n,o,i,s,a,c=0,u=this;e.on("validate",(function(){i=r.util.realClock.now(),a=Date.now()}),!0),e.on("sign",(function(){n=r.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,c++}),!0),e.on("validateResponse",(function(){o=Math.round(r.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=o>=0?o:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,o=o||Math.round(r.util.realClock.now()-n),i.AttemptLatency=o>=0?o:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=c,!(t.AttemptCount<=0)){t.Timestamp=a;var n=Math.round(r.util.realClock.now()-i);t.Latency=n>=0?n:0;var o=e.response;"number"==typeof o.retryCount&&"number"==typeof o.maxRetries&&o.retryCount>=o.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSignerClass:function(e){var t,n=null,o="";return e&&(o=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===o||"v4-unsigned-body"===o?"v4":this.api.signatureVersion,r.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return r.EventListeners.Query;case"json":return r.EventListeners.Json;case"rest-json":return r.EventListeners.RestJson;case"rest-xml":return r.EventListeners.RestXml}if(this.api.protocol)throw new Error("Invalid service `protocol' "+this.api.protocol+" in API config")},successfulResponse:function(e){return e.httpResponse.statusCode<300},numRetries:function(){return void 0!==this.config.maxRetries?this.config.maxRetries:this.defaultRetryCount},retryDelays:function(e){return r.util.calculateRetryDelay(e,this.config.retryDelayOptions)},retryableError:function(e){return!!this.timeoutError(e)||!!this.networkingError(e)||!!this.expiredCredentialsError(e)||!!this.throttledError(e)||e.statusCode>=500},networkingError:function(e){return"NetworkingError"===e.code},timeoutError:function(e){return"TimeoutError"===e.code},expiredCredentialsError:function(e){return"ExpiredTokenException"===e.code},clockSkewError:function(e){switch(e.code){case"RequestTimeTooSkewed":case"RequestExpired":case"InvalidSignatureException":case"SignatureDoesNotMatch":case"AuthFailure":case"RequestInTheFuture":return!0;default:return!1}},getSkewCorrectedDate:function(){return new Date(Date.now()+this.config.systemClockOffset)},applyClockOffset:function(e){e&&(this.config.systemClockOffset=e-Date.now())},isClockSkewed:function(e){if(e)return Math.abs(this.getSkewCorrectedDate().getTime()-e)>=3e4},throttledError:function(e){if(429===e.statusCode)return!0;switch(e.code){case"ProvisionedThroughputExceededException":case"Throttling":case"ThrottlingException":case"RequestLimitExceeded":case"RequestThrottled":case"RequestThrottledException":case"TooManyRequestsException":case"TransactionInProgressException":return!0;default:return!1}},endpointFromTemplate:function(e){if("string"!=typeof e)return e;var t=e;return t=(t=(t=t.replace(/\{service\}/g,this.api.endpointPrefix)).replace(/\{region\}/g,this.config.region)).replace(/\{scheme\}/g,this.config.sslEnabled?"https":"http")},setEndpoint:function(e){this.endpoint=new r.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var o=new Error;throw r.util.error(o,"No pagination configuration for "+e)}return null}return n}}),r.util.update(r.Service,{defineMethods:function(e){r.util.each(e.prototype.api.operations,(function(t){e.prototype[t]||("none"===e.prototype.api.operations[t].authtype?e.prototype[t]=function(e,n){return this.makeUnauthenticatedRequest(t,e,n)}:e.prototype[t]=function(e,n){return this.makeRequest(t,e,n)})}))},defineService:function(e,t,n){r.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var o=s(r.Service,n||{});if("string"==typeof e){r.Service.addVersions(o,t);var i=o.serviceIdentifier||e;o.serviceIdentifier=i}else o.prototype.api=e,r.Service.defineMethods(o);if(r.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&r.util.clientSideMonitoring){var a=r.util.clientSideMonitoring.Publisher,c=(0,r.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new a(c),c.enabled&&(r.Service._clientSideMonitoring=!0)}return r.SequentialExecutor.call(o.prototype),r.Service.addDefaultMonitoringListeners(o.prototype),o},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n=0))throw n.util.error(new Error,t);this.config.stsRegionalEndpoints=e.toLowerCase()},validateRegionalEndpointsFlag:function(){var e=this.config;if(e.stsRegionalEndpoints&&this.validateRegionalEndpointsFlagValue(e.stsRegionalEndpoints,{code:"InvalidConfiguration",message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" or "regional". Got "'+e.stsRegionalEndpoints+'".'}),n.util.isNode()){if(Object.prototype.hasOwnProperty.call(t.env,o)){var r=t.env.AWS_STS_REGIONAL_ENDPOINTS;this.validateRegionalEndpointsFlagValue(r,{code:"InvalidEnvironmentalVariable",message:'invalid AWS_STS_REGIONAL_ENDPOINTS environmental variable. Expect "legacy" or "regional". Got "'+t.env.AWS_STS_REGIONAL_ENDPOINTS+'".'})}var s={};try{s=n.util.getProfilesFromSharedConfig(n.util.iniLoader)[t.env.AWS_PROFILE||n.util.defaultProfile]}catch(e){}if(s&&Object.prototype.hasOwnProperty.call(s,i)){var a=s.sts_regional_endpoints;this.validateRegionalEndpointsFlagValue(a,{code:"InvalidConfiguration",message:'invalid sts_regional_endpoints profile config. Expect "legacy" or "regional". Got "'+s.sts_regional_endpoints+'".'})}}},optInRegionalEndpoint:function(){this.validateRegionalEndpointsFlag();var e=this.config;if("regional"===e.stsRegionalEndpoints){if(r(this),!this.isGlobalEndpoint)return;if(this.isGlobalEndpoint=!1,!e.region)throw n.util.error(new Error,{code:"ConfigError",message:"Missing region in config"});var t=e.endpoint.indexOf(".amazonaws.com");e.endpoint=e.endpoint.substring(0,t)+"."+e.region+e.endpoint.substring(t)}},validateService:function(){this.optInRegionalEndpoint()}})}).call(this)}).call(this,e("_process"))},{"../core":18,"../region_config":53,_process:86}],62:[function(e,t,n){var r=e("../core"),o=r.util.inherit,i="presigned-expires";function s(e){var t=e.httpRequest.headers[i],n=e.service.getSignerClass(e);if(delete e.httpRequest.headers["User-Agent"],delete e.httpRequest.headers["X-Amz-User-Agent"],n===r.Signers.V4){if(t>604800)throw r.util.error(new Error,{code:"InvalidExpiryTime",message:"Presigning does not support expiry time greater than a week with SigV4 signing.",retryable:!1});e.httpRequest.headers[i]=t}else{if(n!==r.Signers.S3)throw r.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var o=e.service?e.service.getSkewCorrectedDate():r.util.date.getDate();e.httpRequest.headers[i]=parseInt(r.util.date.unixTimestamp(o)+t,10).toString()}}function a(e){var t=e.httpRequest.endpoint,n=r.util.urlParse(e.httpRequest.path),o={};n.search&&(o=r.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),o.AWSAccessKeyId=s[0],o.Signature=s[1],r.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete o[e],e=e.toLowerCase()),o[e]=t})),delete e.httpRequest.headers[i],delete o.Authorization,delete o.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var a=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];o["X-Amz-Signature"]=a,delete o.Expires}t.pathname=n.pathname,t.search=r.util.queryParamsToString(o)}r.Signers.Presign=o({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",a),e.removeListener("afterBuild",r.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",r.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return r.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,r.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=r.Signers.Presign},{"../core":18}],63:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.RequestSigner=o({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),r.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return r.Signers.V2;case"v3":return r.Signers.V3;case"s3v4":case"v4":return r.Signers.V4;case"s3":return r.Signers.S3;case"v3https":return r.Signers.V3Https}throw new Error("Unknown signing version "+e)},e("./v2"),e("./v3"),e("./v3https"),e("./v4"),e("./s3"),e("./presign")},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.S3=o(r.Signers.RequestSigner,{subResources:{acl:1,accelerate:1,analytics:1,cors:1,lifecycle:1,delete:1,inventory:1,location:1,logging:1,metrics:1,notification:1,partNumber:1,policy:1,requestPayment:1,replication:1,restore:1,tagging:1,torrent:1,uploadId:1,uploads:1,versionId:1,versioning:1,versions:1,website:1},responseHeaders:{"response-content-type":1,"response-content-language":1,"response-expires":1,"response-cache-control":1,"response-content-disposition":1,"response-content-encoding":1},addAuthorization:function(e,t){this.request.headers["presigned-expires"]||(this.request.headers["X-Amz-Date"]=r.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),o="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=o},stringToSign:function(){var e=this.request,t=[];t.push(e.method),t.push(e.headers["Content-MD5"]||""),t.push(e.headers["Content-Type"]||""),t.push(e.headers["presigned-expires"]||"");var n=this.canonicalizedAmzHeaders();return n&&t.push(n),t.push(this.canonicalizedResource()),t.join("\n")},canonicalizedAmzHeaders:function(){var e=[];r.util.each(this.request.headers,(function(t){t.match(/^x-amz-/i)&&e.push(t)})),e.sort((function(e,t){return e.toLowerCase()=0?"&":"?";this.request.path+=i+r.util.queryParamsToString(o)},authorization:function(e,t){var n=[],r=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+r),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=o.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return r.util.crypto.hmac(n,this.stringToSign(t),"hex")},stringToSign:function(e){var t=[];return t.push("AWS4-HMAC-SHA256"),t.push(e),t.push(this.credentialString(e)),t.push(this.hexEncodedHash(this.canonicalString())),t.join("\n")},canonicalString:function(){var e=[],t=this.request.pathname();return"s3"!==this.serviceName&&"s3v4"!==this.signatureVersion&&(t=r.util.uriEscapePath(t)),e.push(this.request.method),e.push(t),e.push(this.request.search()),e.push(this.canonicalHeaders()+"\n"),e.push(this.signedHeaders()),e.push(this.hexEncodedBodyHash()),e.join("\n")},canonicalHeaders:function(){var e=[];r.util.each.call(this,this.request.headers,(function(t,n){e.push([t,n])})),e.sort((function(e,t){return e[0].toLowerCase()50&&delete o[i.shift()]),d},emptyCache:function(){o={},i=[]}}},{"../core":18}],70:[function(e,t,n){function r(e,t){this.currentState=t||null,this.states=e||{}}r.prototype.runTo=function(e,t,n,r){"function"==typeof e&&(r=n,n=t,t=e,e=null);var o=this,i=o.states[o.currentState];i.fn.call(n||o,r,(function(r){if(r){if(!i.fail)return t?t.call(n,r):null;o.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;o.currentState=i.accept}if(o.currentState===e)return t?t.call(n,r):null;o.runTo(e,t,n,r)}))},r.prototype.addState=function(e,t,n,r){return"function"==typeof t?(r=t,t=null,n=null):"function"==typeof n&&(r=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:r},this},t.exports=r},{}],71:[function(e,t,n){(function(n,r){(function(){var o,i={environment:"nodejs",engine:function(){if(i.isBrowser()&&"undefined"!=typeof navigator)return navigator.userAgent;var e=n.platform+"/"+n.version;return n.env.AWS_EXECUTION_ENV&&(e+=" exec-env/"+n.env.AWS_EXECUTION_ENV),e},userAgent:function(){var t=i.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+i.engine()),n},uriEscape:function(e){var t=encodeURIComponent(e);return t=(t=t.replace(/[^A-Za-z0-9_.~\-%]+/g,escape)).replace(/[*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))},uriEscapePath:function(e){var t=[];return i.arrayEach(e.split("/"),(function(e){t.push(i.uriEscape(e))})),t.join("/")},urlParse:function(e){return i.url.parse(e)},urlFormat:function(e){return i.url.format(e)},queryStringParse:function(e){return i.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=i.uriEscape,r=Object.keys(e).sort();return i.arrayEach(r,(function(r){var o=e[r],s=n(r),a=s+"=";if(Array.isArray(o)){var c=[];i.arrayEach(o,(function(e){c.push(n(e))})),a=s+"="+c.sort().join("&"+s+"=")}else null!=o&&(a=s+"="+n(o));t.push(a)})),t.join("&")},readFileSync:function(t){return i.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 encode number "+e));return null==e?e:i.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 decode number "+e));return null==e?e:i.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof i.Buffer.from&&i.Buffer.from!==Uint8Array.from?i.Buffer.from(e,t):new i.Buffer(e,t)},alloc:function(e,t,n){if("number"!=typeof e)throw new Error("size passed to alloc must be a number.");if("function"==typeof i.Buffer.alloc)return i.Buffer.alloc(e,t,n);var r=new i.Buffer(e);return void 0!==t&&"function"==typeof r.fill&&r.fill(t,void 0,void 0,n),r},toStream:function(e){i.Buffer.isBuffer(e)||(e=i.buffer.toBuffer(e));var t=new i.stream.Readable,n=0;return t._read=function(r){if(n>=e.length)return t.push(null);var o=n+r;o>e.length&&(o=e.length),t.push(e.slice(n,o)),n=o},t},concat:function(e){var t,n,r=0,o=0;for(n=0;n>>8^t[255&(n^e.readUInt8(r))];return(-1^n)>>>0},hmac:function(e,t,n,r){return n||(n="binary"),"buffer"===n&&(n=void 0),r||(r="sha256"),"string"==typeof t&&(t=i.buffer.toBuffer(t)),i.crypto.lib.createHmac(r,e).update(t).digest(n)},md5:function(e,t,n){return i.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return i.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,r){var o=i.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=i.buffer.toBuffer(t));var s=i.arraySliceFn(t),a=i.Buffer.isBuffer(t);if(i.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),r&&"object"==typeof t&&"function"==typeof t.on&&!a)t.on("data",(function(e){o.update(e)})),t.on("error",(function(e){r(e)})),t.on("end",(function(){r(null,o.digest(n))}));else{if(!r||!s||a||"undefined"==typeof FileReader){i.isBrowser()&&"object"==typeof t&&!a&&(t=new i.Buffer(new Uint8Array(t)));var c=o.update(t).digest(n);return r&&r(null,c),c}var u=0,l=new FileReader;l.onerror=function(){r(new Error("Failed to read data."))},l.onload=function(){var e=new i.Buffer(new Uint8Array(l.result));o.update(e),u+=e.length,l._continueReading()},l._continueReading=function(){if(u>=t.size)r(null,o.digest(n));else{var e=u+524288;e>t.size&&(e=t.size),l.readAsArrayBuffer(s.call(t,u,e))}},l._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),o.config.isClockSkewed},applyClockOffset:function(e){e&&(o.config.systemClockOffset=e-(new Date).getTime())},extractRequestId:function(e){var t=e.httpResponse.headers["x-amz-request-id"]||e.httpResponse.headers["x-amzn-requestid"];!t&&e.data&&e.data.ResponseMetadata&&(t=e.data.ResponseMetadata.RequestId),t&&(e.requestId=t),e.error&&(e.error.requestId=t)},addPromises:function(e,t){var n=!1;void 0===t&&o&&o.config&&(t=o.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var r=0;r=500||429===r});o&&s.retryable&&(s.retryAfter=o),c(s)}}))}),c)};o.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,r=t.service.api.operations[n].output||{};r.payload&&e.data[r.payload]&&(e.data[r.payload]=e.data[r.payload].toString())},defer:function(e){"object"==typeof n&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof r?r(e):setTimeout(e,0)},getRequestPayloadShape:function(e){var t=e.service.api.operations;if(t){var n=(t||{})[e.operation];if(n&&n.input&&n.input.payload)return n.input.members[n.input.payload]}},getProfilesFromSharedConfig:function(e,t){var r={},o={};n.env[i.configOptInEnv]&&(o=e.loadFrom({isConfig:!0,filename:n.env[i.sharedConfigFileEnv]}));for(var s=e.loadFrom({filename:t||n.env[i.configOptInEnv]&&n.env[i.sharedCredentialsFileEnv]}),a=0,c=Object.keys(o);a0||r?i.toString():""},t.exports=s},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(e,t,n){t.exports={escapeAttribute:function(e){return e.replace(/&/g,"&").replace(/'/g,"'").replace(//g,">").replace(/"/g,""")}}},{}],75:[function(e,t,n){t.exports={escapeElement:function(e){return e.replace(/&/g,"&").replace(//g,">")}}},{}],76:[function(e,t,n){var r=e("./escape-attribute").escapeAttribute;function o(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}o.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},o.prototype.addChildNode=function(e){return this.children.push(e),this},o.prototype.removeAttribute=function(e){return delete this.attributes[e],this},o.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,o=0,i=Object.keys(n);o"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:o}},{"./escape-attribute":74}],77:[function(e,t,n){var r=e("./escape-element").escapeElement;function o(e){this.value=e}o.prototype.toString=function(){return r(""+this.value)},t.exports={XmlText:o}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=u(e),n=t[0],r=t[1];return 3*(n+r)/4-r},n.toByteArray=function(e){var t,n,r=u(e),s=r[0],a=r[1],c=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),l=0,p=a>0?s-4:s;for(n=0;n>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===a&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[l++]=255&t),1===a&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},n.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],s=16383,a=0,c=n-o;ac?c:a+s));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var o,i,s=[],a=t;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],79:[function(e,t,n){},{}],80:[function(e,t,o){(function(e){(function(){!function(i){"object"==typeof o&&o&&o.nodeType,"object"==typeof t&&t&&t.nodeType;var s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self;var a,c=2147483647,u=36,l=/^xn--/,p=/[^\x20-\x7E]/,h=/[\x2E\u3002\uFF0E\uFF61]/g,d={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function m(e){throw RangeError(d[e])}function v(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function y(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+v((e=e.replace(h,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=g((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=g(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function C(e,t,n){var r=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;r+=u)e=f(e/35);return f(r+36*e/(e+38))}function T(e){var t,n,r,o,i,s,a,l,p,h,d,g=[],v=e.length,y=0,E=128,b=72;for((n=e.lastIndexOf("-"))<0&&(n=0),r=0;r=128&&m("not-basic"),g.push(e.charCodeAt(r));for(o=n>0?n+1:0;o=v&&m("invalid-input"),((l=(d=e.charCodeAt(o++))-48<10?d-22:d-65<26?d-65:d-97<26?d-97:u)>=u||l>f((c-y)/s))&&m("overflow"),y+=l*s,!(l<(p=a<=b?1:a>=b+26?26:a-b));a+=u)s>f(c/(h=u-p))&&m("overflow"),s*=h;b=C(y-i,t=g.length+1,0==i),f(y/t)>c-E&&m("overflow"),E+=f(y/t),y%=t,g.splice(y++,0,E)}return S(g)}function I(e){var t,n,r,o,i,s,a,l,p,h,d,v,y,S,T,I=[];for(v=(e=E(e)).length,t=128,n=0,i=72,s=0;s=t&&df((c-n)/(y=r+1))&&m("overflow"),n+=(a-t)*y,t=a,s=0;sc&&m("overflow"),d==t){for(l=n,p=u;!(l<(h=p<=i?1:p>=i+26?26:p-i));p+=u)T=l-h,S=u-h,I.push(g(b(h+T%S,0))),l=f(T/S);I.push(g(b(l,0))),i=C(n,y,r==o),n=0,++r}++n,++t}return I.join("")}a={version:"1.3.2",ucs2:{decode:E,encode:S},decode:T,encode:I,toASCII:function(e){return y(e,(function(e){return p.test(e)?"xn--"+I(e):e}))},toUnicode:function(e){return y(e,(function(e){return l.test(e)?T(e.slice(4).toLowerCase()):e}))}},void 0===(r=function(){return a}.call(o,n,o,t))||(t.exports=r)}()}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(e,t,r){(function(t,n){(function(){"use strict";var n=e("base64-js"),o=e("ieee754"),i=e("isarray");function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;ia&&(n=a-c),i=n;i>=0;i--){for(var p=!0,h=0;ho&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:u>223?3:u>191?2:1;if(o+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",r=0;r0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,r,o){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),a=Math.min(i,s),u=this.slice(r,o),l=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;oo)&&(n=o);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function P(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function x(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function M(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||M(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,i){return i||M(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||O(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||O(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||D(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function j(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"base64-js":78,buffer:81,ieee754:83,isarray:84}],82:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function o(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,a,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(s(n=this._events[e]))return!1;if(o(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),r=(u=n.slice()).length,c=0;c0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!o(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,s,a;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(o(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],83:[function(e,t,n){n.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<>1,l=-7,p=n?o-1:0,h=n?-1:1,d=e[t+p];for(p+=h,i=d&(1<<-l)-1,d>>=-l,l+=a;l>0;i=256*i+e[t+p],p+=h,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+p],p+=h,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,r),i-=u}return(d?-1:1)*s*Math.pow(2,i-r)},n.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:i-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?h/c:h*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=l?(a=0,s=l):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+d]=255&a,d+=f,a/=256,o-=8);for(s=s<0;e[n+d]=255&s,d+=f,s/=256,u-=8);e[n+d-f]|=128*g}},{}],84:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],85:[function(e,t,n){!function(e){"use strict";function t(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e,o){if(e===o)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(o))return!1;if(!0===t(e)){if(e.length!==o.length)return!1;for(var i=0;i":!0,"=":!0,"!":!0},q={" ":!0,"\t":!0,"\n":!0};function B(e){return e>="0"&&e<="9"||"-"===e}function j(){}j.prototype={tokenize:function(e){var t,n,r,o,i=[];for(this._current=0;this._current="a"&&o<="z"||o>="A"&&o<="Z"||"_"===o)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:u,value:n,start:t});else if(void 0!==U[e[this._current]])i.push({type:U[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(B(e[this._current]))r=this._consumeNumber(e),i.push(r);else if("["===e[this._current])r=this._consumeLBracket(e),i.push(r);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:l,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:M,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:M,value:s,start:t})}else if(void 0!==F[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==q[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:b,value:"&&",start:t})):i.push({type:y,value:"&",start:t});else{if("|"!==e[this._current]){var a=new Error("Unknown character:"+e[this._current]);throw a.name="LexerError",a}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:S,value:"||",start:t})):i.push({type:E,value:"|",start:t})}return i},_consumeUnquotedIdentifier:function(e){var t,n=this._current;for(this._current++;this._current="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t);)this._current++;return e.slice(n,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var n=e.length;'"'!==e[this._current]&&this._current"===n?"="===e[this._current]?(this._current++,{type:_,value:">=",start:t}):{type:T,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:C,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,r=e.length;"`"!==e[this._current]&&this._current=0)return!0;if(["true","false","null"].indexOf(e)>=0)return!0;if(!("-0123456789".indexOf(e[0])>=0))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var V={};function H(){}function W(e){this.runtime=e}function G(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[8]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,3]},{types:[1]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,3,4]}]},map:{_func:this._functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this._functionMax,_signature:[{types:[8,9]}]},merge:{_func:this._functionMerge,_signature:[{types:[4],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[3]},{types:[6]}]},sum:{_func:this._functionSum,_signature:[{types:[8]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[3]},{types:[6]}]},type:{_func:this._functionType,_signature:[{types:[1]}]},keys:{_func:this._functionKeys,_signature:[{types:[4]}]},values:{_func:this._functionValues,_signature:[{types:[4]}]},sort:{_func:this._functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[3]},{types:[6]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[9]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,3]}]},to_array:{_func:this._functionToArray,_signature:[{types:[1]}]},to_string:{_func:this._functionToString,_signature:[{types:[1]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[1]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[1],variadic:!0}]}}}V.EOF=0,V.UnquotedIdentifier=0,V.QuotedIdentifier=0,V.Rbracket=0,V.Rparen=0,V.Comma=0,V.Rbrace=0,V.Number=0,V.Current=0,V.Expref=0,V.Pipe=1,V.Or=2,V.And=3,V.EQ=5,V.GT=5,V.LT=5,V.GTE=5,V.LTE=5,V.NE=5,V.Flatten=9,V.Star=20,V.Filter=21,V.Dot=40,V.Not=45,V.Lbrace=50,V.Lbracket=55,V.Lparen=60,H.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==c){var n=this._lookaheadToken(0),r=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw r.name="ParserError",r}return t},_loadTokens:function(e){var t=(new j).tokenize(e);t.push({type:c,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),r=this._lookahead(0);e=0?this.expression(e):t===P?(this._match(P),this._parseMultiselectList()):t===D?(this._match(D),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(V[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===P)t=this.expression(e);else if(this._lookahead(0)===k)t=this.expression(e);else{if(this._lookahead(0)!==L){var n=this._lookaheadToken(0),r=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw r.name="ParserError",r}this._match(L),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==p;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===d&&(this._match(d),this._lookahead(0)===p))throw new Error("Unexpected token Rbracket")}return this._match(p),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,r=[],o=[u,l];;){if(e=this._lookaheadToken(0),o.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(f),n={type:"KeyValuePair",name:t,value:this.expression(0)},r.push(n),this._lookahead(0)===d)this._match(d);else if(this._lookahead(0)===g){this._match(g);break}}return{type:"MultiSelectHash",children:r}}},W.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,a,c,u,l,p,h,d,f;switch(e.type){case"Field":return null===i?null:n(i)?void 0===(p=i[e.name])?null:p:null;case"Subexpression":for(c=this.visit(e.children[0],i),f=1;f0)for(f=b;fN;f+=k)c.push(i[f]);return c;case"Projection":var L=this.visit(e.children[0],i);if(!t(L))return null;for(d=[],f=0;fl;break;case _:c=u>=l;break;case I:c=u=e&&(t=n<0?e-1:e),t}},G.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var r,o,i,s;if(n[n.length-1].variadic){if(t.length=0;r--)n+=t[r];return n}var o=e[0].slice(0);return o.reverse(),o},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],r=0;r=0},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return n(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],n=this._interpreter,r=e[0],o=e[1],i=0;i0){if(this._getTypeName(e[0][0])===s)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;r0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;ra?1:sc&&(c=n,t=o[u]);return t},_functionMinBy:function(e){for(var t,n,r=e[1],o=e[0],i=this.createKeyFunction(r,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>c&&(u=c);for(var l=0;l=0?(p=g.substr(0,m),h=g.substr(m+1)):(p=g,h=""),d=decodeURIComponent(p),f=decodeURIComponent(h),r(s,d)?o(s[d])?s[d].push(f):s[d]=[s[d],f]:s[d]=f}return s};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],88:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?i(s(e),(function(s){var a=encodeURIComponent(r(s))+n;return o(e[s])?i(e[s],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[s]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&c>a&&(c=a);for(var u=0;u=0?(l=f.substr(0,g),p=f.substr(g+1)):(l=f,p=""),h=decodeURIComponent(l),d=decodeURIComponent(p),r(i,h)?Array.isArray(i[h])?i[h].push(d):i[h]=[i[h],d]:i[h]=d}return i}},{}],91:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,o){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map((function(o){var i=encodeURIComponent(r(o))+n;return Array.isArray(e[o])?e[o].map((function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):o?encodeURIComponent(r(o))+n+encodeURIComponent(r(e)):""}},{}],92:[function(e,t,n){arguments[4][89][0].apply(n,arguments)},{"./decode":90,"./encode":91,dup:89}],93:[function(e,t,n){(function(t,r){(function(){var o=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function u(e,t){this._id=e,this._clearFn=t}n.setTimeout=function(){return new u(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new u(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n.setImmediate="function"==typeof t?t:function(e){var t=c++,r=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,o((function(){a[t]&&(r?e.apply(null,r):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof r?r:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":86,timers:93}],94:[function(e,t,n){var r=e("punycode");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=v,n.resolve=function(e,t){return v(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},n.format=function(e){return y(e)&&(e=v(e)),e instanceof o?e.format():o.prototype.format.call(e)},n.Url=o;var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(a),u=["%","/","?",";","#"].concat(c),l=["/","?","#"],p=/^[a-z0-9A-Z_-]{0,63}$/,h=/^([a-z0-9A-Z_-]{0,63})(.*)$/,d={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},m=e("querystring");function v(e,t,n){if(e&&E(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function y(e){return"string"==typeof e}function E(e){return"object"==typeof e&&null!==e}function S(e){return null===e}o.prototype.parse=function(e,t,n){if(!y(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e;o=o.trim();var s=i.exec(o);if(s){var a=(s=s[0]).toLowerCase();this.protocol=a,o=o.substr(s.length)}if(n||s||o.match(/^\/\/[^@\/]+@[^@\/]+/)){var v="//"===o.substr(0,2);!v||s&&f[s]||(o=o.substr(2),this.slashes=!0)}if(!f[s]&&(v||s&&!g[s])){for(var E,S,b=-1,C=0;C127?R+="x":R+=w[N];if(!R.match(p)){var L=_.slice(0,C),O=_.slice(C+1),D=w.match(h);D&&(L.push(D[1]),O.unshift(D[2])),O.length&&(o="/"+O.join(".")+o),this.hostname=L.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!I){var P=this.hostname.split("."),x=[];for(C=0;C0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),n.search=e.search,n.query=e.query,S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!p.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var d=p.slice(-1)[0],m=(n.host||e.host)&&("."===d||".."===d)||""===d,v=0,E=p.length;E>=0;E--)"."==(d=p[E])?p.splice(E,1):".."===d?(p.splice(E,1),v++):v&&(p.splice(E,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),m&&"/"!==p.join("/").substr(-1)&&p.push("");var b,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return h&&(n.hostname=n.host=C?"":p.length?p.shift():"",(b=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:80,querystring:89}],95:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],96:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],97:[function(e,t,r){(function(t,n){(function(){var o=/%[sdj%]/g;r.format=function(e){if(!v(e)){for(var t=[],n=0;n=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),c=r[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),f(t)?n.showHidden=t:t&&r._extend(n,t),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),l(n,e,n.depth)}function c(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function u(e,t){return e}function l(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var o=t.inspect(n,e);return v(o)||(o=l(e,o,n)),o}var i=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return m(t)?e.stylize(""+t,"number"):f(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),C(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(b(t))return e.stylize(Date.prototype.toString.call(t),"date");if(C(t))return p(t)}var u,S="",I=!1,_=["{","}"];return d(t)&&(I=!0,_=["[","]"]),T(t)&&(S=" [Function"+(t.name?": "+t.name:"")+"]"),E(t)&&(S=" "+RegExp.prototype.toString.call(t)),b(t)&&(S=" "+Date.prototype.toUTCString.call(t)),C(t)&&(S=" "+p(t)),0!==s.length||I&&0!=t.length?n<0?E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=I?function(e,t,n,r,o){for(var i=[],s=0,a=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,S,_)):_[0]+S+_[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,n,r,o,i){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),R(r,o)||(s="["+o+"]"),a||(e.seen.indexOf(c.value)<0?(a=g(n)?l(e,c.value,null):l(e,c.value,n-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),y(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function d(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function v(e){return"string"==typeof e}function y(e){return void 0===e}function E(e){return S(e)&&"[object RegExp]"===I(e)}function S(e){return"object"==typeof e&&null!==e}function b(e){return S(e)&&"[object Date]"===I(e)}function C(e){return S(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(y(i)&&(i=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!s[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var n=t.pid;s[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else s[e]=function(){};return s[e]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=f,r.isNull=g,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=v,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=y,r.isRegExp=E,r.isObject=S,r.isDate=b,r.isError=C,r.isFunction=T,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function w(){var e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){console.log("%s - %s",w(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!S(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this)}).call(this,e("_process"),void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":96,_process:86,inherits:95}],98:[function(e,t,n){var r=e("./v1"),o=e("./v4"),i=o;i.v1=r,i.v4=o,t.exports=i},{"./v1":101,"./v4":102}],99:[function(e,t,n){for(var r=[],o=0;o<256;++o)r[o]=(o+256).toString(16).substr(1);t.exports=function(e,t){var n=t||0,o=r;return[o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]]].join("")}},{}],100:[function(e,t,n){var r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(r){var o=new Uint8Array(16);t.exports=function(){return r(o),o}}else{var i=new Array(16);t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},{}],101:[function(e,t,n){var r,o,i=e("./lib/rng"),s=e("./lib/bytesToUuid"),a=0,c=0;t.exports=function(e,t,n){var u=t&&n||0,l=t||[],p=(e=e||{}).node||r,h=void 0!==e.clockseq?e.clockseq:o;if(null==p||null==h){var d=i();null==p&&(p=r=[1|d[0],d[1],d[2],d[3],d[4],d[5]]),null==h&&(h=o=16383&(d[6]<<8|d[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:c+1,m=f-a+(g-c)/1e4;if(m<0&&void 0===e.clockseq&&(h=h+1&16383),(m<0||f>a)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=f,c=g,o=h;var v=(1e4*(268435455&(f+=122192928e5))+g)%4294967296;l[u++]=v>>>24&255,l[u++]=v>>>16&255,l[u++]=v>>>8&255,l[u++]=255&v;var y=f/4294967296*1e4&268435455;l[u++]=y>>>8&255,l[u++]=255&y,l[u++]=y>>>24&15|16,l[u++]=y>>>16&255,l[u++]=h>>>8|128,l[u++]=255&h;for(var E=0;E<6;++E)l[u+E]=p[E];return t||s(l)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(e,t,n){var r=e("./lib/rng"),o=e("./lib/bytesToUuid");t.exports=function(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||o(s)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var r=e("./utils/LRU"),o=function(){function e(e){void 0===e&&(e=1e3),this.maxSize=e,this.cache=new r.LRUCache(e)}return Object.defineProperty(e.prototype,"size",{get:function(){return this.cache.length},enumerable:!0,configurable:!0}),e.prototype.put=function(t,n){var r="string"!=typeof t?e.getKeyString(t):t,o=this.populateValue(n);this.cache.put(r,o)},e.prototype.get=function(t){var n="string"!=typeof t?e.getKeyString(t):t,r=Date.now(),o=this.cache.get(n);if(o)for(var i=0;i{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.ClientMethods=t.makeEnum(["getAgentSnapshot","putAgentState","getAgentStates","getDialableCountryCodes","getRoutingProfileQueues","getAgentPermissions","getAgentConfiguration","updateAgentConfiguration","acceptContact","createOutboundContact","createTaskContact","clearContact","completeContact","destroyContact","rejectContact","notifyContactIssue","updateContactAttributes","createAdditionalConnection","destroyConnection","holdConnection","resumeConnection","toggleActiveConnections","conferenceConnections","sendClientLogs","sendDigits","sendSoftphoneCallReport","sendSoftphoneCallMetrics","getEndpoints","getNewAuthToken","createTransport","muteParticipant","unmuteParticipant"]),t.AgentAppClientMethods={GET_CONTACT:"AgentAppService.Lcms.getContact",DELETE_SPEAKER:"AgentAppService.VoiceId.deleteSpeaker",ENROLL_BY_SESSION:"AgentAppService.VoiceId.enrollBySession",EVALUATE_SESSION:"AgentAppService.VoiceId.evaluateSession",DESCRIBE_SPEAKER:"AgentAppService.VoiceId.describeSpeaker",OPT_OUT_SPEAKER:"AgentAppService.VoiceId.optOutSpeaker",UPDATE_VOICE_ID_DATA:"AgentAppService.Lcms.updateVoiceIdData",DESCRIBE_SESSION:"AgentAppService.VoiceId.describeSession",UPDATE_SESSION:"AgentAppService.VoiceId.updateSession",START_VOICE_ID_SESSION:"AgentAppService.Nasa.startVoiceIdSession",LIST_INTEGRATION_ASSOCIATIONS:"AgentAppService.Acs.listIntegrationAssociations"},t.MasterMethods=t.makeEnum(["becomeMaster","checkMaster"]);var n=function(){};n.EMPTY_CALLBACKS={success:function(){},failure:function(){}},n.prototype.call=function(e,r,o){t.assertNotNull(e,"method");var i=r||{},s=o||n.EMPTY_CALLBACKS;this._callImpl(e,i,s)},n.prototype._callImpl=function(e,n,r){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){if(r&&r.failure){var o=t.sprintf("No such method exists on NULL client: %s",e);r.failure(new t.ValueError(o),{message:o})}};var o=function(e,r,o){n.call(this),this.conduit=e,this.requestEvent=r,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,t.hitch(this,this._handleResponse))};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._callImpl=function(e,n,r){var o=t.EventFactory.createRequest(this.requestEvent,e,n);this._requestIdCallbacksMap[o.requestId]=r,this.conduit.sendUpstream(o.event,o)},o.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},o.prototype._handleResponse=function(e){var t=this._getCallbacksForRequest(e.requestId);null!=t&&(e.err&&t.failure?t.failure(e.err,e.data):t.success&&t.success(e.data))};var i=function(e){o.call(this,e,t.EventType.API_REQUEST,t.EventType.API_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e){o.call(this,e,t.EventType.MASTER_REQUEST,t.EventType.MASTER_RESPONSE)};(s.prototype=Object.create(o.prototype)).constructor=s;var a=function(e,r,o){t.assertNotNull(e,"authCookieName"),t.assertNotNull(r,"authToken"),t.assertNotNull(o,"endpoint"),n.call(this),this.endpointUrl=t.getUrlWithProtocol(o),this.authToken=r,this.authCookieName=e};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype._callImpl=function(e,n,r){var o=this,i={};i[o.authCookieName]=o.authToken;var s={method:"post",body:JSON.stringify(n||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(i)}};t.fetch(o.endpointUrl,s).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))};var c=function(e,r,o){t.assertNotNull(e,"authToken"),t.assertNotNull(r,"region"),n.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=r,this.authToken=e;var i=t.getBaseUrl(),s=o||(i.includes(".awsapps.com")?i+"/connect/api":i+"/api"),a=new AWS.Endpoint(s);this.client=new AWS.Connect({endpoint:a})};(c.prototype=Object.create(n.prototype)).constructor=c,c.prototype._callImpl=function(e,n,r){var o=this,i=t.getLog();if(t.contains(this.client,e))n=this._translateParams(e,n),i.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](n).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(n,o){try{if(n){if(n.code===t.CTIExceptions.UNAUTHORIZED_EXCEPTION)r.authFailure();else if(!r.accessDenied||n.code!==t.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==n.statusCode){var s={};s.type=n.code,s.message=n.message,s.stack=n.stack?n.stack.split("\n"):[],r.failure(s,o)}else r.accessDenied();i.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(n)).sendInternalLogToServer()}else i.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),r.success(o)}catch(n){t.getLog().error("Failed to handle AWS API request for method %s",e).withException(n).sendInternalLogToServer()}}));else{var s=t.sprintf("No such method exists on AWS client: %s",e);r.failure(new t.ValueError(s),{message:s})}},c.prototype._requiresAuthenticationParam=function(e){return e!==t.ClientMethods.COMPLETE_CONTACT&&e!==t.ClientMethods.CLEAR_CONTACT&&e!==t.ClientMethods.REJECT_CONTACT&&e!==t.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,n){switch(e){case t.ClientMethods.UPDATE_AGENT_CONFIGURATION:n.configuration=this._translateAgentConfiguration(n.configuration);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:n.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(n.softphoneStreamStatistics);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:n.report=this._translateSoftphoneCallReport(n.report)}return this._requiresAuthenticationParam(e)&&(n.authentication={authToken:this.authToken}),n},c.prototype._translateAgentConfiguration=function(e){return{name:e.name,softphoneEnabled:e.softphoneEnabled,softphoneAutoAccept:e.softphoneAutoAccept,extension:e.extension,routingProfile:this._translateRoutingProfile(e.routingProfile),agentPreferences:e.agentPreferences}},c.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},c.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},c.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach((function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)})),e},c.prototype._translateSoftphoneCallReport=function(e){return"handshakingTimeMillis"in e&&(e.handshakeTimeMillis=e.handshakingTimeMillis,delete e.handshakingTimeMillis),"preTalkingTimeMillis"in e&&(e.preTalkTimeMillis=e.preTalkingTimeMillis,delete e.preTalkingTimeMillis),"handshakingFailure"in e&&(e.handshakeFailure=e.handshakingFailure,delete e.handshakingFailure),"talkingTimeMillis"in e&&(e.talkTimeMillis=e.talkingTimeMillis,delete e.talkingTimeMillis),e.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics),e},t.ClientBase=n,t.NullClient=r,t.UpstreamConduitClient=i,t.UpstreamConduitMasterClient=s,t.AWSClient=c,t.AgentAppClient=a}()},895:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.core={},t.core.initialized=!1,t.version="2.1.1",t.DEFAULT_BATCH_SIZE=500;var n="Amazon Connect CCP",r="https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}",o="06919f4fd8ed324e",i="/auth/authorize",s="/connect/auth/authorize",a="IframeRefreshAttempts",c="IframeInitializationSuccess";function u(e){var t=e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gi);return t.length?t[0]:""}t.numberOfConnectedCCPs=0,t.core.checkNotInitialized=function(){t.core.initialized&&t.getLog().warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer()},t.core.init=function(e){t.core.eventBus=new t.EventBus,t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.initClient(e),t.core.initAgentAppClient(e),t.core.initialized=!0},t.core.initClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.region,"params.region"),o=e.endpoint||null;t.core.client=new t.AWSClient(n,r,o)},t.core.initAgentAppClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.authCookieName,"params.authCookieName"),o=t.assertNotNull(e.agentAppEndpoint,"params.agentAppEndpoint");t.core.agentAppClient=new t.AgentAppClient(r,n,o)},t.core.terminate=function(){t.core.client=new t.NullClient,t.core.agentAppClient=new t.NullClient,t.core.masterClient=new t.NullClient;var e=t.core.getEventBus();e&&e.unsubscribeAll(),t.core.bus=new t.EventBus,t.core.agentDataProvider=null,t.core.softphoneManager=null,t.core.upstream=null,t.core.keepaliveManager=null,t.agent.initialized=!1,t.core.initialized=!1},t.core.softphoneUserMediaStream=null,t.core.getSoftphoneUserMediaStream=function(){return t.core.softphoneUserMediaStream},t.core.setSoftphoneUserMediaStream=function(e){t.core.softphoneUserMediaStream=e},t.core.initRingtoneEngines=function(e){t.assertNotNull(e,"params");var n=function(e){t.assertNotNull(e,"ringtoneSettings"),t.assertNotNull(e.voice,"ringtoneSettings.voice"),t.assertTrue(e.voice.ringtoneUrl||e.voice.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"),t.assertNotNull(e.queue_callback,"ringtoneSettings.queue_callback"),t.assertTrue(e.queue_callback.ringtoneUrl||e.queue_callback.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"),t.core.ringtoneEngines={},t.agent((function(n){n.onRefresh((function(){t.ifMaster(t.MasterTopics.RINGTONE,(function(){e.voice.disabled||t.core.ringtoneEngines.voice||(t.core.ringtoneEngines.voice=new t.VoiceRingtoneEngine(e.voice),t.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer()),e.chat.disabled||t.core.ringtoneEngines.chat||(t.core.ringtoneEngines.chat=new t.ChatRingtoneEngine(e.chat),t.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer()),e.task.disabled||t.core.ringtoneEngines.task||(t.core.ringtoneEngines.task=new t.TaskRingtoneEngine(e.task),t.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer()),e.queue_callback.disabled||t.core.ringtoneEngines.queue_callback||(t.core.ringtoneEngines.queue_callback=new t.QueueCallbackRingtoneEngine(e.queue_callback),t.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer())}))}))})),l()},r=function(e,n){e.ringtone=e.ringtone||{},e.ringtone.voice=e.ringtone.voice||{},e.ringtone.queue_callback=e.ringtone.queue_callback||{},e.ringtone.chat=e.ringtone.chat||{disabled:!0},e.ringtone.task=e.ringtone.task||{disabled:!0},n.softphone&&(n.softphone.disableRingtone&&(e.ringtone.voice.disabled=!0,e.ringtone.queue_callback.disabled=!0),n.softphone.ringtoneUrl&&(e.ringtone.voice.ringtoneUrl=n.softphone.ringtoneUrl,e.ringtone.queue_callback.ringtoneUrl=n.softphone.ringtoneUrl)),n.chat&&(n.chat.disableRingtone&&(e.ringtone.chat.disabled=!0),n.chat.ringtoneUrl&&(e.ringtone.chat.ringtoneUrl=n.chat.ringtoneUrl)),n.ringtone&&(e.ringtone.voice=t.merge(e.ringtone.voice,n.ringtone.voice||{}),e.ringtone.queue_callback=t.merge(e.ringtone.queue_callback,n.ringtone.voice||{}),e.ringtone.chat=t.merge(e.ringtone.chat,n.ringtone.chat||{}))};r(e,e),t.isFramed()?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(t){this.unsubscribe(),r(e,t),n(e.ringtone)})):n(e.ringtone)};var l=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_RINGER_DEVICE,p)},p=function(e){if(0!==t.keys(t.core.ringtoneEngines).length&&e&&e.deviceId){var n=e.deviceId;for(var r in t.core.ringtoneEngines)t.core.ringtoneEngines[r].setOutputDevice(n);t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.RINGER_DEVICE_CHANGED,data:{deviceId:n}})}};t.core.initSoftphoneManager=function(e){t.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer();var n=e||{},r=function(e){var r=t.merge(n.softphone||{},e);t.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(),t.agent((function(e){e.getChannelConcurrency(t.ChannelType.VOICE)&&e.onRefresh((function(){var n=this;t.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(),t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(),!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),n.unsubscribe())}))}))}))};function o(e){var r=t.merge(n.softphone||{},e);t.core.softphoneParams=r,t.isFirefoxBrowser()&&(t.core.getUpstream().onUpstream(t.EventType.MASTER_RESPONSE,(function(e){if(e.data&&e.data.topic===t.MasterTopics.SOFTPHONE&&e.data.takeOver&&e.data.masterId!==t.core.portStreamId){t.core.softphoneManager&&(t.core.softphoneManager.onInitContactSub.unsubscribe(),delete t.core.softphoneManager);var n=t.core.getSoftphoneUserMediaStream();n&&(n.getTracks().forEach((function(e){e.stop()})),t.core.setSoftphoneUserMediaStream(null))}})),t.core.getEventBus().subscribe(t.ConnectionEvents.READY_TO_START_SESSION,(function(){t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.core.softphoneManager&&t.core.softphoneManager.startSession()}),(function(){t.becomeMaster(t.MasterTopics.SOFTPHONE,(function(){t.agent((function(e){!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),t.core.softphoneManager.startSession())}))}))}))})),t.contact((function(e){t.agent((function(n){e.onRefresh((function(e){if(t.hasOtherConnectedCCPs()&&"visible"===document.visibilityState&&(e.getStatus().type===t.ContactStatusType.CONNECTING||e.getStatus().type===t.ContactStatusType.INCOMING)){var r=e.isSoftphoneCall()&&!e.isInbound(),o=e.isSoftphoneCall()&&n.getConfiguration().softphoneAutoAccept,i=e.getType()===t.ContactType.QUEUE_CALLBACK;(r||o||i)&&t.core.triggerReadyToStartSessionEvent()}}))}))})))}t.isFramed()&&!n.allowFramedSoftphone?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(e){t.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(),e.softphone&&e.softphone.allowFramedSoftphone&&(this.unsubscribe(),r(e.softphone)),o(e.softphone)})):(r(n),o(n)),t.agent((function(e){e.isSoftphoneEnabled()&&e.getChannelConcurrency(t.ChannelType.VOICE)&&t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE})}))},t.core.triggerReadyToStartSessionEvent=function(){var e=t.core.softphoneParams&&t.core.softphoneParams.allowFramedSoftphone;t.isCCP()?e?t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):t.isFramed()?t.core.getUpstream().sendDownstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):e?t.core.getUpstream().sendUpstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION)},t.core.initPageOptions=function(e){if(t.assertNotNull(e,"params"),t.isFramed()){var n=t.core.getEventBus();n.subscribe(t.EventType.CONFIGURE,(function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.CONFIGURE,data:e})})),n.subscribe(t.EventType.MEDIA_DEVICE_REQUEST,(function(){function e(e){t.core.getUpstream().sendDownstream(t.EventType.MEDIA_DEVICE_RESPONSE,e)}navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})).catch((function(t){e({error:t.message})})):e({error:"No navigator or navigator.mediaDevices object found"})}))}},t.core.getFrameMediaDevices=function(e){var n=null,r=e||1e3,o=new Promise((function(e,t){setTimeout((function(){t(new Error("Timeout exceeded"))}),r)})),i=new Promise((function(e,r){if(t.isFramed()||t.isCCP())navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})):r(new Error("No navigator or navigator.mediaDevices object found"));else{var o=t.core.getEventBus();n=o.subscribe(t.EventType.MEDIA_DEVICE_RESPONSE,(function(t){t.error?r(new Error(t.error)):e(t)})),t.core.getUpstream().sendUpstream(t.EventType.MEDIA_DEVICE_REQUEST)}}));return Promise.race([i,o]).finally((function(){n&&n.unsubscribe()}))},t.core.authorize=function(e){var n=e;return n||(n=t.core.isLegacyDomain()?s:i),t.fetch(n,{credentials:"include"},2e3,5)},t.core.verifyDomainAccess=function(e,n){if(t.getLog().warn("This API will be deprecated in the next major version release"),!t.isFramed())return Promise.resolve();var r={headers:{"X-Amz-Bearer":e}},o=null;return o=n||(t.core.isLegacyDomain()?"/connect/whitelisted-origins":"/whitelisted-origins"),t.fetch(o,r,2e3,5).then((function(e){var t=u(window.document.referrer);return e.whitelistedOrigins.some((function(e){return t===u(e)}))?Promise.resolve():Promise.reject()}))},t.core.isLegacyDomain=function(e){return(e=e||window.location.href).includes(".awsapps.com")},t.core.initSharedWorker=function(n){if(t.core.checkNotInitialized(),!t.core.initialized){t.assertNotNull(n,"params");var r=t.assertNotNull(n.sharedWorkerUrl,"params.sharedWorkerUrl"),o=t.assertNotNull(n.authToken,"params.authToken"),a=t.assertNotNull(n.refreshToken,"params.refreshToken"),c=t.assertNotNull(n.authTokenExpiration,"params.authTokenExpiration"),u=t.assertNotNull(n.region,"params.region"),l=n.endpoint||null,p=n.authorizeEndpoint;p||(p=t.core.isLegacyDomain()?s:i);var h=n.agentAppEndpoint||null,g=n.authCookieName||null;try{t.core.eventBus=new t.EventBus({logEvents:!0}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(n);var m=new SharedWorker(r,"ConnectSharedWorker"),v=new t.Conduit("ConnectSharedWorkerConduit",new t.PortStream(m.port),new t.WindowIOStream(window,parent));t.core.upstream=v,t.core.webSocketProvider=new d,e.onunload=function(){v.sendUpstream(t.EventType.CLOSE),m.port.close()},t.getLog().scheduleUpstreamLogPush(v),t.getLog().scheduleDownstreamClientSideLogsPush(),v.onAllUpstream(t.core.getEventBus().bridge()),v.onAllUpstream(v.passDownstream()),t.isFramed()&&(v.onAllDownstream(t.core.getEventBus().bridge()),v.onAllDownstream(v.passUpstream())),v.sendUpstream(t.EventType.CONFIGURE,{authToken:o,authTokenExpiration:c,endpoint:l,refreshToken:a,region:u,authorizeEndpoint:p,agentAppEndpoint:h,authCookieName:g}),v.onUpstream(t.EventType.ACKNOWLEDGE,(function(e){t.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(),t.core.initialized=!0,t.core.portStreamId=e.id,this.unsubscribe()})),v.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),v.onUpstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))})),v.onDownstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.isFramed()&&Array.isArray(e)&&e.forEach((function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))}))})),v.onDownstream(t.EventType.LOG,(function(e){t.isFramed()&&e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),v.onUpstream(t.EventType.AUTH_FAIL,(function(e){location.reload()})),t.getLog().info("User Agent: "+navigator.userAgent).sendInternalLogToServer(),t.getLog().info("isCCPv2: "+!0).sendInternalLogToServer(),t.getLog().info("isFramed: "+t.isFramed()).sendInternalLogToServer(),t.core.upstream.onDownstream(t.EventType.OUTER_CONTEXT_INFO,(function(e){var n=e.streamsVersion;t.getLog().info("StreamsJS Version: "+n).sendInternalLogToServer()})),v.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.getLog().info("Number of connected CCPs updated: "+e.length).sendInternalLogToServer(),t.numberOfConnectedCCPs=e.length})),t.core.client=new t.UpstreamConduitClient(v),t.core.masterClient=new t.UpstreamConduitMasterClient(v),t.core.getEventBus().subscribe(t.EventType.TERMINATE,v.passUpstream()),t.core.getEventBus().subscribe(t.EventType.TERMINATED,(function(){window.location.reload(!0)})),m.port.start(),v.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.agent((function(){(new t.VoiceId).getDomainId().then((function(e){t.getLog().info("voiceId domainId successfully fetched at agent initialization: "+e).sendInternalLogToServer()})).catch((function(e){t.getLog().info("voiceId domainId not fetched at agent initialization").withObject({err:e}).sendInternalLogToServer()}))})),t.core.getNotificationManager().requestPermission()}catch(e){t.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer()}}},t.core.initCCP=function(n,i){if(t.core.checkNotInitialized(),!t.core.initialized){t.getLog().info("Iframe initialization started").sendInternalLogToServer();var s=Date.now();try{if(t.core._getCCPIframe())return void t.getLog().error("Attempted to call initCCP when an iframe generated by initCCP already exists").sendInternalLogToServer()}catch(e){t.getLog().error("Error while checking if initCCP has already been called").withException(e).sendInternalLogToServer()}var u={};"string"==typeof i?u.ccpUrl=i:u=i,t.assertNotNull(n,"containerDiv"),t.assertNotNull(u.ccpUrl,"params.ccpUrl");var l=t.core._createCCPIframe(n,u);t.core.eventBus=new t.EventBus({logEvents:!1}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(u);var p=new t.IFrameConduit(u.ccpUrl,window,l);t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(l,p),t.core.upstream=p,t.core.webSocketProvider=new d,p.onAllUpstream(t.core.getEventBus().bridge()),t.core.keepaliveManager=new h(p,t.core.getEventBus(),u.ccpSynTimeout||1e3,u.ccpAckTimeout||3e3),t.core.iframeRefreshTimeout=null,t.core.ccpLoadTimeoutInstance=e.setTimeout((function(){t.core.ccpLoadTimeoutInstance=null,t.core.getEventBus().trigger(t.EventType.ACK_TIMEOUT)}),u.ccpLoadTimeout||5e3),t.getLog().scheduleUpstreamOuterContextCCPLogsPush(p),t.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(p),p.onUpstream(t.EventType.ACKNOWLEDGE,(function(n){if(t.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(),t.core.client=new t.UpstreamConduitClient(p),t.core.masterClient=new t.UpstreamConduitMasterClient(p),t.core.portStreamId=n.id,(u.softphone||u.chat||u.pageOptions)&&p.sendUpstream(t.EventType.CONFIGURE,{softphone:u.softphone,chat:u.chat,pageOptions:u.pageOptions}),t.core.ccpLoadTimeoutInstance&&(e.clearTimeout(t.core.ccpLoadTimeoutInstance),t.core.ccpLoadTimeoutInstance=null),p.sendUpstream(t.EventType.OUTER_CONTEXT_INFO,{streamsVersion:t.version}),t.core.keepaliveManager.start(),this.unsubscribe(),t.core.initialized=!0,t.core.getEventBus().trigger(t.EventType.INIT),s){var r=Date.now()-s,o=t.core.iframeRefreshAttempt||0;t.getLog().info("Iframe initialization succeeded").sendInternalLogToServer(),t.getLog().info(`Iframe initialization time ${r}`).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${o}`).sendInternalLogToServer(),t.publishMetric({name:a,data:o}),t.publishMetric({name:c,data:1}),t.publishMetric({name:"IframeInitializationTime",data:r}),s=null}})),p.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.getEventBus().subscribe(t.EventType.ACK_TIMEOUT,(function(){if(!1!==u.loginPopup)try{var i=function(n){var i="https://lily.us-east-1.amazonaws.com/taw/auth/code";return t.assertNotNull(i),n.loginUrl?n.loginUrl:n.alias?(log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."),r.replace("{alias}",n.alias).replace("{client_id}",o).replace("{redirect}",e.encodeURIComponent(i))):n.ccpUrl}(u);t.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(),u.loginUrl&&t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),t.core.loginWindow=t.core.getPopupManager().open(i,t.MasterTopics.LOGIN_POPUP,u.loginOptions)}catch(e){t.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer()}if(null==t.core.iframeRefreshTimeout)try{p.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=null,t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),(u.loginPopupAutoClose||u.loginOptions&&u.loginOptions.autoClose)&&t.core.loginWindow&&(t.core.loginWindow.close(),t.core.loginWindow=null)})),t.core._refreshIframeOnTimeout(u,n)}catch(e){t.getLog().error("Error occurred while refreshing iframe").withException(e).sendInternalLogToServer()}})),u.onViewContact&&t.core.onViewContact(u.onViewContact),p.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.numberOfConnectedCCPs=e.length})),p.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,(function(){if(s){var e=t.core.iframeRefreshAttempt-1;t.getLog().info("Iframe initialization failed").sendInternalLogToServer(),t.getLog().info("Time after iframe initialization started "+(Date.now()-s)).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${e}`).sendInternalLogToServer(),t.publishMetric({name:a,data:e}),t.publishMetric({name:c,data:0}),s=null}})),t.core.softphoneParams=u.softphone}},t.core.onIframeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,e)},t.core._refreshIframeOnTimeout=function(n,r){t.assertNotNull(n,"initCCPParams"),t.assertNotNull(r,"containerDiv");var o=(n.disasterRecoveryOn?1e4:5e3)+AWS.util.calculateRetryDelay(t.core.iframeRefreshAttempt||0,{base:2e3});e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=e.setTimeout((function(){if(t.core.iframeRefreshAttempt=(t.core.iframeRefreshAttempt||0)+1,t.core.iframeRefreshAttempt<=6){try{var o=t.core._getCCPIframe();o&&o.parentNode.removeChild(o);var i=t.core._createCCPIframe(r,n);t.core.upstream.upstream.output=i.contentWindow,t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(i,t.core.upstream)}catch(e){t.getLog().error("Error while checking for, and recreating, the CCP IFrame").withException(e).sendInternalLogToServer()}t.core._refreshIframeOnTimeout(n,r)}else t.core.getEventBus().trigger(t.EventType.IFRAME_RETRIES_EXHAUSTED),e.clearTimeout(t.core.iframeRefreshTimeout)}),o)},t.core._getCCPIframe=function(){for(var e of window.document.getElementsByTagName("iframe"))if(e.name===n)return e;return null},t.core._createCCPIframe=function(e,r){t.assertNotNull(r,"initCCPParams"),t.assertNotNull(e,"containerDiv");var o=document.createElement("iframe");return o.src=r.ccpUrl,o.allow="microphone; autoplay",o.style="width: 100%; height: 100%",o.title=r.iframeTitle||n,o.name=n,e.appendChild(o),o},t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime=function(e,n){t.assertNotNull(e,"iframe"),t.assertNotNull(n,"conduit"),setTimeout((function(){var r={display:window.getComputedStyle(e,null).display,offsetWidth:e.offsetWidth,offsetHeight:e.offsetHeight,clientRectsLength:e.getClientRects().length};n.sendUpstream(t.EventType.IFRAME_STYLE,r)}),1e4)};var h=function(e,t,n,r){this.conduit=e,this.eventBus=t,this.synTimeout=n,this.ackTimeout=r,this.ackTimer=null,this.synTimer=null,this.ackSub=null};h.prototype.start=function(){var n=this;this.conduit.sendUpstream(t.EventType.SYNCHRONIZE),this.ackSub=this.conduit.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(n.ackTimer),n._deferStart()})),this.ackTimer=e.setTimeout((function(){n.ackSub.unsubscribe(),n.eventBus.trigger(t.EventType.ACK_TIMEOUT),n._deferStart()}),this.ackTimeout)},h.prototype._deferStart=function(){this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout)},h.prototype.deferStart=function(){null==this.synTimer&&(this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout))};var d=function(){var e={initFailure:new Set,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},n=function(e,t){e.forEach((function(e){e(t)}))};t.core.getUpstream().onUpstream(t.WebSocketEvents.INIT_FAILURE,(function(){n(e.initFailure)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_OPEN,(function(t){n(e.connectionOpen,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_CLOSE,(function(t){n(e.connectionClose,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_GAIN,(function(){n(e.connectionGain)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_LOST,(function(t){n(e.connectionLost,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,(function(t){n(e.subscriptionUpdate,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,(function(t){n(e.subscriptionFailure,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.ALL_MESSAGE,(function(t){n(e.allMessage,t),e.topic.has(t.topic)&&n(e.topic.get(t.topic),t)})),this.sendMessage=function(e){t.core.getUpstream().sendUpstream(t.WebSocketEvents.SEND,e)},this.onInitFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.initFailure.add(n),function(){return e.initFailure.delete(n)}},this.onConnectionOpen=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionOpen.add(n),function(){return e.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionClose.add(n),function(){return e.connectionClose.delete(n)}},this.onConnectionGain=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionGain.add(n),function(){return e.connectionGain.delete(n)}},this.onConnectionLost=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionLost.add(n),function(){return e.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionUpdate.add(n),function(){return e.subscriptionUpdate.delete(n)}},this.onSubscriptionFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionFailure.add(n),function(){return e.subscriptionFailure.delete(n)}},this.subscribeTopics=function(e){t.assertNotNull(e,"topics"),t.assertTrue(t.isArray(e),"topics must be a array"),t.core.getUpstream().sendUpstream(t.WebSocketEvents.SUBSCRIBE,e)},this.onMessage=function(n,r){return t.assertNotNull(n,"topicName"),t.assertTrue(t.isFunction(r),"method must be a function"),e.topic.has(n)?e.topic.get(n).add(r):e.topic.set(n,new Set([r])),function(){return e.topic.get(n).delete(r)}},this.onAllMessage=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.allMessage.add(n),function(){return e.allMessage.delete(n)}}},f=function(e){this.bus=e,this.bus.subscribe(t.AgentEvents.UPDATE,t.hitch(this,this.updateAgentData))};f.prototype.updateAgentData=function(e){var n=this.agentData;this.agentData=e,null==n&&(t.agent.initialized=!0,this.bus.trigger(t.AgentEvents.INIT,new t.Agent)),this.bus.trigger(t.AgentEvents.REFRESH,new t.Agent),this._fireAgentUpdateEvents(n)},f.prototype.getAgentData=function(){if(null==this.agentData)throw new t.StateError("No agent data is available yet!");return this.agentData},f.prototype.getContactData=function(e){var n=this.getAgentData(),r=t.find(n.snapshot.contacts,(function(t){return t.contactId===e}));if(null==r)throw new t.StateError("Contact %s no longer exists.",e);return r},f.prototype.getConnectionData=function(e,n){var r=this.getContactData(e),o=t.find(r.connections,(function(e){return e.connectionId===n}));if(null==o)throw new t.StateError("Connection %s for contact %s no longer exists.",n,e);return o},f.prototype.getInstanceId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]},f.prototype.getAWSAccountId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]},f.prototype._diffContacts=function(e){var n={added:{},removed:{},common:{},oldMap:t.index(null==e?[]:e.snapshot.contacts,(function(e){return e.contactId})),newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))};return t.keys(n.oldMap).forEach((function(e){t.contains(n.newMap,e)?n.common[e]=n.newMap[e]:n.removed[e]=n.oldMap[e]})),t.keys(n.newMap).forEach((function(e){t.contains(n.oldMap,e)||(n.added[e]=n.newMap[e])})),n},f.prototype._fireAgentUpdateEvents=function(e){var n=this,r=null,o=null==e?t.AgentAvailStates.INIT:e.snapshot.state.name,i=this.agentData.snapshot.state.name,s=null==e?t.AgentStateType.INIT:e.snapshot.state.type,a=this.agentData.snapshot.state.type;s!==a&&t.core.getAgentRoutingEventGraph().getAssociations(this,s,a).forEach((function(e){n.bus.trigger(e,new t.Agent)})),o!==i&&(this.bus.trigger(t.AgentEvents.STATE_CHANGE,{agent:new t.Agent,oldState:o,newState:i}),t.core.getAgentStateEventGraph().getAssociations(this,o,i).forEach((function(e){n.bus.trigger(e,new t.Agent)})));var c=e&&e.snapshot.nextState?e.snapshot.nextState.name:null,u=this.agentData.snapshot.nextState?this.agentData.snapshot.nextState.name:null;c!==u&&u&&n.bus.trigger(t.AgentEvents.ENQUEUED_NEXT_STATE,new t.Agent),r=null!==e?this._diffContacts(e):{added:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId})),removed:{},common:{},oldMap:{},newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))},t.values(r.added).forEach((function(e){n.bus.trigger(t.ContactEvents.INIT,new t.Contact(e.contactId)),n._fireContactUpdateEvents(e.contactId,t.ContactStateType.INIT,e.state.type)})),t.values(r.removed).forEach((function(e){n.bus.trigger(t.ContactEvents.DESTROYED,new t.ContactSnapshot(e)),n.bus.trigger(t.core.getContactEventName(t.ContactEvents.DESTROYED,e.contactId),new t.ContactSnapshot(e)),n._unsubAllContactEventsForContact(e.contactId)})),t.keys(r.common).forEach((function(e){n._fireContactUpdateEvents(e,r.oldMap[e].state.type,r.newMap[e].state.type)}))},f.prototype._fireContactUpdateEvents=function(e,n,r){var o=this;n!==r&&t.core.getContactEventGraph().getAssociations(this,n,r).forEach((function(n){o.bus.trigger(n,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(n,e),new t.Contact(e))})),o.bus.trigger(t.ContactEvents.REFRESH,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(t.ContactEvents.REFRESH,e),new t.Contact(e))},f.prototype._unsubAllContactEventsForContact=function(e){var n=this;t.values(t.ContactEvents).forEach((function(r){n.bus.getSubscriptions(t.core.getContactEventName(r,e)).map((function(e){e.unsubscribe()}))}))},t.core.onViewContact=function(e){t.core.getUpstream().onUpstream(t.ContactEvents.VIEW,e)},t.core.viewContact=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.VIEW,data:{contactId:e}})},t.core.onActivateChannelWithViewType=function(e){t.core.getUpstream().onUpstream(t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,e)},t.core.activateChannelWithViewType=function(e,n,r){const o={viewType:e,mediaType:n};r&&(o.source=r),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,data:o})},t.core.triggerTaskCreated=function(e){t.core.getUpstream().upstreamBus.trigger(t.TaskEvents.CREATED,e)},t.core.onAccessDenied=function(e){t.core.getUpstream().onUpstream(t.EventType.ACCESS_DENIED,e)},t.core.onAuthFail=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTH_FAIL,e)},t.core.onSoftphoneSessionInit=function(e){t.core.getUpstream().onUpstream(t.ConnectionEvents.SESSION_INIT,e)},t.core.onConfigure=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.CONFIGURE,e)},t.core.onInitialized=function(e){t.core.getEventBus().subscribe(t.EventType.INIT,e)},t.core.getContactEventName=function(e,n){if(t.assertNotNull(e,"eventName"),t.assertNotNull(n,"contactId"),!t.contains(t.values(t.ContactEvents),e))throw new t.ValueError("%s is not a valid contact event.",e);return t.sprintf("%s::%s",e,n)},t.core.getEventBus=function(){return t.core.eventBus},t.core.getWebSocketManager=function(){return t.core.webSocketProvider},t.core.getAgentDataProvider=function(){return t.core.agentDataProvider},t.core.getLocalTimestamp=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp},t.core.getSkew=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.skew},t.core.getAgentRoutingEventGraph=function(){return t.core.agentRoutingEventGraph},t.core.agentRoutingEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.AgentStateType.ROUTABLE,t.AgentEvents.ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.NOT_ROUTABLE,t.AgentEvents.NOT_ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.OFFLINE,t.AgentEvents.OFFLINE),t.core.getAgentStateEventGraph=function(){return t.core.agentStateEventGraph},t.core.agentStateEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.values(t.AgentErrorStates),t.AgentEvents.ERROR).assoc(t.EventGraph.ANY,t.AgentAvailStates.AFTER_CALL_WORK,t.AgentEvents.ACW),t.core.getContactEventGraph=function(){return t.core.contactEventGraph},t.core.contactEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.ContactStateType.INCOMING,t.ContactEvents.INCOMING).assoc(t.EventGraph.ANY,t.ContactStateType.PENDING,t.ContactEvents.PENDING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTING,t.ContactEvents.CONNECTING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTED,t.ContactEvents.CONNECTED).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.ContactStateType.INCOMING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.EventGraph.ANY,t.ContactStateType.ENDED,t.ContactEvents.ACW).assoc(t.values(t.CONTACT_ACTIVE_STATES),t.values(t.relativeComplement(t.CONTACT_ACTIVE_STATES,t.ContactStateType)),t.ContactEvents.ENDED).assoc(t.EventGraph.ANY,t.ContactStateType.ERROR,t.ContactEvents.ERROR).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.MISSED,t.ContactEvents.MISSED),t.core.getClient=function(){if(!t.core.client)throw new t.StateError("The connect core has not been initialized!");return t.core.client},t.core.client=null,t.core.getAgentAppClient=function(){if(!t.core.agentAppClient)throw new t.StateError("The connect AgentApp Client has not been initialized!");return t.core.agentAppClient},t.core.agentAppClient=null,t.core.getMasterClient=function(){if(!t.core.masterClient)throw new t.StateError("The connect master client has not been initialized!");return t.core.masterClient},t.core.masterClient=null,t.core.getSoftphoneManager=function(){return t.core.softphoneManager},t.core.softphoneManager=null,t.core.getNotificationManager=function(){return t.core.notificationManager||(t.core.notificationManager=new t.NotificationManager),t.core.notificationManager},t.core.notificationManager=null,t.core.getPopupManager=function(){return t.core.popupManager},t.core.popupManager=new t.PopupManager,t.core.getUpstream=function(){if(!t.core.upstream)throw new t.StateError("There is no upstream conduit!");return t.core.upstream},t.core.upstream=null,t.core.AgentDataProvider=f}()},592:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t;var n="<>",r=t.makeEnum(["acknowledge","ack_timeout","init","api_request","api_response","auth_fail","access_denied","close","configure","log","master_request","master_response","synchronize","terminate","terminated","send_logs","reload_agent_configuration","broadcast","api_metric","client_metric","softphone_stats","softphone_report","client_side_logs","server_bound_internal_log","mute","iframe_style","iframe_retries_exhausted","update_connected_ccps","outer_context_info","media_device_request","media_device_response"]),o=t.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),i=t.makeNamespacedEnum("agent",["init","update","refresh","routable","not_routable","pending","contact_pending","offline","error","softphone_error","websocket_connection_lost","websocket_connection_gained","state_change","acw","mute_toggle","local_media_stream_created","enqueued_next_state"]),s=t.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),a=t.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),c=t.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),u=t.makeNamespacedEnum("task",["created"]),l=t.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),p=t.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),h=t.makeNamespacedEnum("voiceId",["update_domain_id"]),d=function(){};d.createRequest=function(e,n,r){return{event:e,requestId:t.randomId(),method:n,params:r}},d.createResponse=function(e,t,n,r){return{event:e,requestId:t.requestId,data:n,err:r||null}};var f=function(e,n,r){this.subMap=e,this.id=t.randomId(),this.eventName=n,this.f=r};f.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var g=function(){this.subIdMap={},this.subEventNameMap={}};g.prototype.subscribe=function(e,t){var n=new f(this,e,t);this.subIdMap[n.id]=n;var r=this.subEventNameMap[e]||[];return r.push(n),this.subEventNameMap[e]=r,n},g.prototype.unsubscribe=function(e,n){t.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==n})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),t.contains(this.subIdMap,n)&&delete this.subIdMap[n]},g.prototype.getAllSubscriptions=function(){return t.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},g.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var m=function(e){var t=e||{};this.subMap=new g,this.logEvents=t.logEvents||!1};m.prototype.subscribe=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.subMap.subscribe(e,n)},m.prototype.subscribeAll=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.subMap.subscribe(n,e)},m.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},m.prototype.trigger=function(e,r){t.assertNotNull(e,"eventName");var o=this,i=this.subMap.getSubscriptions(n),s=this.subMap.getSubscriptions(e);this.logEvents&&e!==t.EventType.LOG&&e!==t.EventType.MASTER_RESPONSE&&e!==t.EventType.API_METRIC&&e!==t.EventType.SERVER_BOUND_INTERNAL_LOG&&t.getLog().trace("Publishing event: %s",e).sendInternalLogToServer(),e.startsWith(t.ContactEvents.ACCEPTED)&&r&&r.contactId&&!(r instanceof t.Contact)&&(r=new t.Contact(r.contactId)),i.concat(s).forEach((function(n){try{n.f(r||null,e,o)}catch(n){t.getLog().error("'%s' event handler failed.",e).withException(n).sendInternalLogToServer()}}))},m.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},m.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},t.EventBus=m,t.EventFactory=d,t.EventType=r,t.AgentEvents=i,t.ConfigurationEvents=p,t.ConnectionEvents=l,t.ConnnectionEvents=l,t.ContactEvents=a,t.ChannelViewEvents=c,t.TaskEvents=u,t.VoiceIdEvents=h,t.WebSocketEvents=s,t.MasterTopics=o}()},286:()=>{!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";var r=n(1),o="DEBUG",i="aws/subscribe",s="aws/heartbeat",a="disconnected";function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var u={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return u.assertTrue(null!==e&&void 0!==c(e),Object(r.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==c(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},l=new RegExp("^(wss://)\\w*");u.validWSUrl=function(e){return l.test(e)},u.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},u.assertIsObject=function(e,t){if(!u.isObject(e))throw new Error(t+" is not an object!")},u.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)},u.isNetworkOnline=function(){return navigator.onLine},u.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var p=u;function h(e){return(h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function d(e){return(d=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var n=0;n=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var t=e.prefix||"";return this._logsDestination===o?this.consoleLoggerWrapper:new C(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||E.DEBUG,this._clientLogger=t.logger||null,this._logsDestination="NULL",t.debug&&(this._logsDestination=o),t.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),e}(),b=function(){function e(){g(this,e)}return v(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),C=function(e){function t(e){var n;return g(this,t),(n=function(e,t){return!t||"object"!==h(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}(this,d(t).call(this))).prefix=e||"",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}(t,b),v(t,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:2e3;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}var t,n;return t=e,(n=[{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}}])&&_(t.prototype,n),e}();n.d(t,"a",(function(){return R}));var w=function(){var e=I.getLogger({}),t=p.isNetworkOnline(),n={primary:null,secondary:null},r={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},o={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},c={pendingResponse:!1,intervalHandle:null},u={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},l={connConfig:null,promiseHandle:null,promiseCompleted:!0},h={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},d={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},f=new A((function(){B()})),g=new Set([i,"aws/unsubscribe",s]),m=setInterval((function(){if(t!==p.isNetworkOnline()){if(!(t=p.isNetworkOnline()))return void H(e.info("Network offline"));var n=T();t&&(!n||S(n,WebSocket.CLOSING)||S(n,WebSocket.CLOSED))&&(H(e.info("Network online, connecting to WebSocket server")),B())}}),250),v=function(t,n){t.forEach((function(t){try{t(n)}catch(t){H(e.error("Error executing callback",t))}}))},y=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"}},E=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";H(e.debug("["+t+"] Primary WebSocket: "+y(n.primary)+" | Secondary WebSocket: "+y(n.secondary)))},S=function(e,t){return e&&e.readyState===t},b=function(e){return S(e,WebSocket.OPEN)},C=function(e){return null===e||void 0===e.readyState||S(e,WebSocket.CLOSED)},T=function(){return null!==n.secondary?n.secondary:n.primary},_=function(){return b(T())},w=function(){if(c.pendingResponse)return H(e.warn("Heartbeat response not received")),clearInterval(c.intervalHandle),c.pendingResponse=!1,void B();_()?(H(e.debug("Sending heartbeat")),T().send(F(s)),c.pendingResponse=!0):(H(e.warn("Failed to send heartbeat since WebSocket is not open")),E("sendHeartBeat"),B())},R=function(){r.exponentialBackOffTime=1e3,c.pendingResponse=!1,r.reconnectWebSocket=!0,clearTimeout(r.lifeTimeTimeoutHandle),clearInterval(c.intervalHandle),clearTimeout(r.exponentialTimeoutHandle),clearTimeout(r.webSocketInitCheckerTimeoutId)},N=function(){d.consecutiveFailedSubscribeAttempts=0,d.consecutiveNoResponseRequest=0,clearInterval(d.responseCheckIntervalId),clearInterval(d.reSubscribeIntervalId)},k=function(){o.connectWebSocketRetryCount=0,o.connectionAttemptStartTime=null,o.noOpenConnectionsTimestamp=null},L=function(){try{H(e.info("WebSocket connection established!")),E("webSocketOnOpen"),null!==r.connState&&r.connState!==a||v(u.connectionGain),r.connState="connected";var t=Date.now();v(u.connectionOpen,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,noOpenConnectionsTimestamp:o.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-o.connectionAttemptStartTime,timeWithoutConnection:o.noOpenConnectionsTimestamp?t-o.noOpenConnectionsTimestamp:null}),k(),R(),T().openTimestamp=Date.now(),0===h.subscribed.size&&b(n.secondary)&&x(n.primary,"[Primary WebSocket] Closing WebSocket"),(h.subscribed.size>0||h.pending.size>0)&&(b(n.secondary)&&H(e.info("Subscribing secondary websocket to topics of primary websocket")),h.subscribed.forEach((function(e){h.subscriptionHistory.add(e),h.pending.add(e)})),h.subscribed.clear(),P()),w(),c.intervalHandle=setInterval(w,1e4);var i=1e3*l.connConfig.webSocketTransport.transportLifeTimeInSeconds;H(e.debug("Scheduling WebSocket manager reconnection, after delay "+i+" ms")),r.lifeTimeTimeoutHandle=setTimeout((function(){H(e.debug("Starting scheduled WebSocket manager reconnection")),B()}),i)}catch(t){H(e.error("Error after establishing WebSocket connection",t))}},O=function(t){E("webSocketOnError"),H(e.error("WebSocketManager Error, error_event: ",JSON.stringify(t))),B()},D=function(t){var r=JSON.parse(t.data);switch(r.topic){case i:if(H(e.debug("Subscription Message received from webSocket server",t.data)),d.requestCompleted=!0,d.consecutiveNoResponseRequest=0,"success"===r.content.status)d.consecutiveFailedSubscribeAttempts=0,r.content.topics.forEach((function(e){h.subscriptionHistory.delete(e),h.pending.delete(e),h.subscribed.add(e)})),0===h.subscriptionHistory.size?b(n.secondary)&&(H(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),x(n.primary,"[Primary WebSocket] Closing WebSocket")):P(),v(u.subscriptionUpdate,r);else{if(clearInterval(d.reSubscribeIntervalId),++d.consecutiveFailedSubscribeAttempts,5===d.consecutiveFailedSubscribeAttempts)return v(u.subscriptionFailure,r),void(d.consecutiveFailedSubscribeAttempts=0);d.reSubscribeIntervalId=setInterval((function(){P()}),500)}break;case s:H(e.debug("Heartbeat response received")),c.pendingResponse=!1;break;default:if(r.topic){if(H(e.debug("Message received for topic "+r.topic)),b(n.primary)&&b(n.secondary)&&0===h.subscriptionHistory.size&&this===n.primary)return void H(e.warn("Ignoring Message for Topic "+r.topic+", to avoid duplicates"));if(0===u.allMessage.size&&0===u.topic.size)return void H(e.warn("No registered callback listener for Topic",r.topic));v(u.allMessage,r),u.topic.has(r.topic)&&v(u.topic.get(r.topic),r)}else r.message?H(e.warn("WebSocketManager Message Error",r)):H(e.warn("Invalid incoming message",r))}},P=function t(){if(d.consecutiveNoResponseRequest>3)return H(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void v(u.subscriptionFailure,p.getSubscriptionResponse(i,!1,Array.from(h.pending)));_()?(clearInterval(d.responseCheckIntervalId),T().send(F(i,{topics:Array.from(h.pending)})),d.requestCompleted=!1,d.responseCheckIntervalId=setInterval((function(){d.requestCompleted||(++d.consecutiveNoResponseRequest,t())}),1e3)):H(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},x=function(t,n){S(t,WebSocket.CONNECTING)||S(t,WebSocket.OPEN)?t.close(1e3,n):H(e.warn("Ignoring WebSocket Close request, WebSocket State: "+y(t)))},M=function(e){x(n.primary,"[Primary] WebSocket "+e),x(n.secondary,"[Secondary] WebSocket "+e)},U=function(t){R(),N(),H(e.error("WebSocket Initialization failed")),r.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(m),v(u.initFailure,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,reason:t}),k()},F=function(e,t){return JSON.stringify({topic:e,content:t})},q=function(t){return!!(p.isObject(t)&&p.isObject(t.webSocketTransport)&&p.isNonEmptyString(t.webSocketTransport.url)&&p.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(H(e.error("Invalid WebSocket Connection Configuration",t)),!1)},B=function(){if(p.isNetworkOnline())if(r.websocketInitFailed)H(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(l.promiseCompleted)return R(),H(e.info("Fetching new WebSocket connection configuration")),o.connectionAttemptStartTime=o.connectionAttemptStartTime||Date.now(),l.promiseCompleted=!1,l.promiseHandle=u.getWebSocketTransport(),l.promiseHandle.then((function(t){return l.promiseCompleted=!0,H(e.debug("Successfully fetched webSocket connection configuration",t)),q(t)?(l.connConfig=t,l.connConfig.urlConnValidTime=Date.now()+85e3,f.connected(),j()):(U("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return l.promiseCompleted=!0,H(e.error("Failed to fetch webSocket connection configuration",t)),p.isNetworkFailure(t)?(H(e.info("Retrying fetching new WebSocket connection configuration")),f.retry()):U("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));H(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else H(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},j=function(){if(r.websocketInitFailed)return H(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!p.isNetworkOnline())return H(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};H(e.info("Initializing Websocket Manager")),E("initWebSocket");try{if(q(l.connConfig)){var t=null;return b(n.primary)?(H(e.debug("Primary Socket connection is already open")),S(n.secondary,WebSocket.CONNECTING)||(H(e.debug("Establishing a secondary web-socket connection")),n.secondary=V()),t=n.secondary):(S(n.primary,WebSocket.CONNECTING)||(H(e.debug("Establishing a primary web-socket connection")),n.primary=V()),t=n.primary),r.webSocketInitCheckerTimeoutId=setTimeout((function(){b(t)||function(){o.connectWebSocketRetryCount++;var t=p.addJitter(r.exponentialBackOffTime,.3);Date.now()+t<=l.connConfig.urlConnValidTime?(H(e.debug("Scheduling WebSocket reinitialization, after delay "+t+" ms")),r.exponentialTimeoutHandle=setTimeout((function(){return j()}),t),r.exponentialBackOffTime*=2):(H(e.warn("WebSocket URL cannot be used to establish connection")),B())}()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return H(e.error("Error Initializing web-socket-manager",t)),U("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},V=function(){var t=new WebSocket(l.connConfig.webSocketTransport.url);return t.addEventListener("open",L),t.addEventListener("message",D),t.addEventListener("error",O),t.addEventListener("close",(function(i){return function(t,i){H(e.info("Socket connection is closed",t)),E("webSocketOnClose before-cleanup"),v(u.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),C(n.primary)&&(n.primary=null),C(n.secondary)&&(n.secondary=null),r.reconnectWebSocket&&(b(n.primary)||b(n.secondary)?C(n.primary)&&b(n.secondary)&&(H(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(H(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),r.connState===a?H(e.info("Ignoring connectionLost callback invocation")):(v(u.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),o.noOpenConnectionsTimestamp=Date.now()),r.connState=a,B()),E("webSocketOnClose after-cleanup"))}(i,t)})),t},H=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(p.assertTrue(p.isFunction(t),"transportHandle must be a function"),null===u.getWebSocketTransport)return u.getWebSocketTransport=t,B();H(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.initFailure.add(e),r.websocketInitFailed&&e(),function(){return u.initFailure.delete(e)}},this.onConnectionOpen=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionOpen.add(e),function(){return u.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionClose.add(e),function(){return u.connectionClose.delete(e)}},this.onConnectionGain=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionGain.add(e),_()&&e(),function(){return u.connectionGain.delete(e)}},this.onConnectionLost=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionLost.add(e),r.connState===a&&e(),function(){return u.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionUpdate.add(e),function(){return u.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionFailure.add(e),function(){return u.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return p.assertNotNull(e,"topicName"),p.assertTrue(p.isFunction(t),"cb must be a function"),u.topic.has(e)?u.topic.get(e).add(t):u.topic.set(e,new Set([t])),function(){return u.topic.get(e).delete(t)}},this.onAllMessage=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.allMessage.add(e),function(){return u.allMessage.delete(e)}},this.subscribeTopics=function(e){p.assertNotNull(e,"topics"),p.assertIsList(e),e.forEach((function(e){h.subscribed.has(e)||h.pending.add(e)})),d.consecutiveNoResponseRequest=0,P()},this.sendMessage=function(t){if(p.assertIsObject(t,"payload"),void 0===t.topic||g.has(t.topic))H(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void H(e.warn("Error stringify message",t))}_()?T().send(t):H(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){R(),N(),r.reconnectWebSocket=!1,clearInterval(m),M("User request to close WebSocket")},this.terminateWebSocketManager=U},R={create:function(){return new w},setGlobalConfig:function(e){var t=e.loggerConfig;I.updateLoggerConfig(t)},LogLevel:E,Logger:y}},function(e,t,n){var r;!function(){"use strict";var o={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,t){var n,r,s,a,c,u,l,p,h,d=1,f=e.length,g="";for(r=0;r=0),a.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,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}o.json.test(a.type)?g+=n:(!o.number.test(a.type)||p&&!a.sign?h="":(h=p?"+":"-",n=n.toString().replace(o.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(h+n).length,c=a.width&&l>0?u.repeat(l):"",g+=a.align?h+n+c:"0"===u?h+c+n:c+h+n)}return g}(function(e){if(a[e])return a[e];for(var t,n=e,r=[],i=0;n;){if(null!==(t=o.text.exec(n)))r.push(t[0]);else if(null!==(t=o.modulo.exec(n)))r.push("%");else{if(null===(t=o.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var s=[],c=t[2],u=[];if(null===(u=o.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=o.key_access.exec(c)))s.push(u[1]);else{if(null===(u=o.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");r.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 a[e]=r}(e),arguments)}function s(e,t){return i.apply(null,[e].concat(t||[]))}var a=Object.create(null);t.sprintf=i,t.vsprintf=s,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=s,void 0===(r=function(){return{sprintf:i,vsprintf:s}}.call(t,n,t,e))||(e.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return o}));var r=n(0);e.connect=e.connect||{},connect.WebSocketManager=r.a;var o=r.a}.call(this,n(3))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n}])},151:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},r={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},o={TEST:0,TRACE:10,DEBUG:20,INFO:30,LOG:40,WARN:50,ERROR:100,CRITICAL:200},i={TRACE:function(e){console.info(e)},DEBUG:function(e){console.info(e)},INFO:function(e){console.info(e)},LOG:function(e){console.log(e)},TEST:function(e){console.log(e)},WARN:function(e){console.warn(e)},ERROR:function(e){console.error(e)},CRITICAL:function(e){console.error(e)}},s=function(e){var t,n,o=Array.prototype.slice.call(e,0),i=o.shift();return function(e){return-1!==Object.values(r).indexOf(e)}(i)?(n=i,t=o.shift()):(t=i,n=r.CCP),{format:t,component:n,args:o}},a=function(e,n,r,o){this.component=e,this.level=n,this.text=r,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{t.agent.initialized&&(this.agentResourceId=(new t.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};a.fromObject=function(e){var t=new a(r.CCP,e.level,e.text,e.loggerId);return"[object Date]"===Object.prototype.toString.call(e.time)?t.time=new Date(e.time.getTime()):"number"==typeof e.time?t.time=new Date(e.time):"string"==typeof e.time?t.time=Date.parse(e.time):t.time=new Date,t.exception=e.exception,t.objects=e.objects,t};var c=function(e){var t=/AuthToken.*\=/g;e&&"object"==typeof e&&Object.keys(e).forEach((function(n){"object"==typeof e[n]?c(e[n]):"string"==typeof e[n]&&("url"===n||"text"===n?e[n]=e[n].replace(t,"[redacted]"):"quickConnectName"===n&&(e[n]="[redacted]"))}))},u=function(e){this.type=e instanceof Error?e.name:e.code||Object.prototype.toString.call(e),this.message=e.message,this.stack=e.stack?e.stack.split("\n"):[]};a.prototype.toString=function(){return t.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},a.prototype.getTime=function(){return this.time},a.prototype.getAgentResourceId=function(){return this.agentResourceId},a.prototype.getLevel=function(){return this.level},a.prototype.getText=function(){return this.text},a.prototype.getComponent=function(){return this.component},a.prototype.withException=function(e){return this.exception=new u(e),this},a.prototype.withObject=function(e){var n=t.deepcopy(e);return c(n),this.objects.push(n),this},a.prototype.withCrossOriginEventObject=function(e){var n=t.deepcopyCrossOriginEvent(e);return c(n),this.objects.push(n),this},a.prototype.sendInternalLogToServer=function(){return t.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=o.INFO,this._logLevel=o.INFO,this._lineCount=0,this._logRollInterval=0,this._logRollTimer=null,this._loggerId=(new Date).getTime()+"-"+Math.random().toString(36).slice(2),this.setLogRollInterval(18e5),this._startLogIndexToPush=0};l.prototype.setLogRollInterval=function(t){var n=this;this._logRollTimer&&t===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&e.clearInterval(this._logRollTimer),this._logRollInterval=t,this._logRollTimer=e.setInterval((function(){n._rolledLogs=n._logs,n._logs=[],n._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._logLevel=o[e]},l.prototype.setEchoLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._echoLevel=o[e]},l.prototype.write=function(e,t,n){var r=new a(e,t,n,this.getLoggerId());return c(r),this.addLogEntry(r),r},l.prototype.addLogEntry=function(e){c(e),this._logs.push(e),r.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=i._logLevel})));var a=new e.Blob([JSON.stringify(s,void 0,4)],["text/plain"]),c=document.createElement("a");n=n||"agent-log",c.href=e.URL.createObjectURL(a),c.download=n+".txt",document.body.appendChild(c),c.click(),document.body.removeChild(c)},l.prototype.scheduleUpstreamLogPush=function(n){t.upstreamLogPushScheduled||(t.upstreamLogPushScheduled=!0,e.setInterval(t.hitch(this,this.reportMasterLogsUpStream,n),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var n=this._logsToPush.slice();this._logsToPush=[],t.ifMaster(t.MasterTopics.SEND_LOGS,(function(){n.length>0&&e.sendUpstream(t.EventType.SEND_LOGS,n)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,n),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPLogsUpstream,n),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var n=0;n500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),t.publishClientSideLogs(e))};var p=function(n){l.call(this),this.conduit=n,e.setInterval(t.hitch(this,this._pushLogsDownstream),p.LOG_PUSH_INTERVAL),e.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,p.prototype=Object.create(l.prototype),p.prototype.constructor=p,p.prototype.pushLogsDownstream=function(e){var n=this;e.forEach((function(e){n.conduit.sendDownstream(t.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(n){e.conduit.sendDownstream(t.EventType.LOG,n)})),this._logs=[];for(var n=0;n{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.ChatMediaController=function(e,n){var r=t.getLog(),o=t.LogComponent.CHAT,i=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},s=function(e){e.onConnectionBroken((function(e){r.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),i("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){r.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),i("Chat Session connection established",e)}))};return{get:function(){return function(){i("Chat media controller init",e.contactId),r.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),t.ChatSession.setGlobalConfig({loggerConfig:{logger:r},region:n.region});var a=t.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:t.core.getWebSocketManager()});return s(a),a.connect().then((function(t){return r.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),i("Chat Session Successfully established",e.contactId),a})).catch((function(t){throw r.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),i("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},279:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.MediaFactory=function(e){var n={},r=new Set,o=t.getLog(),i=t.LogComponent.CHAT,s=t.merge({},e)||{};s.region=s.region||"us-west-2";var a=function(e){n[e]&&!r.has(e)&&(o.info(i,"Destroying mediaController for %s",e),r.add(e),n[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete n[e],r.delete(e)})).catch((function(){delete n[e],r.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var r=e.getConnectionId();if(!e.getMediaInfo())return o.error(i,"Media info does not exist for a media type %s",e.getMediaType()).withObject(e).sendInternalLogToServer(),Promise.reject("Media info does not exist for this connection");if(n[r])return n[r];switch(o.info(i,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case t.MediaType.CHAT:return n[r]=new t.ChatMediaController(e.getMediaInfo(),s).get();case t.MediaType.SOFTPHONE:return n[r]=new t.SoftphoneMediaController(e.getMediaInfo()).get();case t.MediaType.TASK:return n[r]=new t.TaskMediaController(e.getMediaInfo()).get();default:return o.error(i,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(a(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:a}}}()},418:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},187:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.TaskMediaController=function(e){var n=t.getLog(),r=t.LogComponent.TASK,o=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},i=function(e){e.onConnectionBroken((function(e){n.error(r,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(r,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),n.info(r,"Task media controller init").withObject(e);var s=t.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:t.core.getWebSocketManager()});return i(s),s.connect().then((function(){return n.info(r,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(r,"Task Session establishement failed for contact %s",e.contactId).withException(t),o("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},743:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var r=this;if(this._prevContactId=null,t.assertNotNull(n,"ringtoneConfig"),!n.ringtoneUrl)throw new Error("ringtoneUrl is required!");e.Audio&&void 0!==e.Promise?this._playableAudioPromise=new Promise((function(e,t){r._audio=new Audio(n.ringtoneUrl),r._audio.loop=!0,r._audio.addEventListener("canplay",(function(){r._audioPlayable=!0,e(r._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),r._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){var n=this;this._audio&&(this._audio.play().catch((function(r){n._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").withException(r).withObject({currentSrc:n._audio.currentSrc,sinkId:n._audio.sinkId,volume:n._audio.volume}).sendInternalLogToServer()})),n._publishTelemetryEvent("Ringtone Start",e),t.getLog().info("Ringtone Start").sendInternalLogToServer())},n.prototype._stopRingtone=function(e){this._audio&&(this._audio.pause(),this._audio.currentTime=0,this._publishTelemetryEvent("Ringtone Stop",e),t.getLog().info("Ringtone Stop").sendInternalLogToServer())},n.prototype.stopRingtone=function(){this._stopRingtone()},n.prototype._ringtoneSetup=function(e){var n=this;t.ifMaster(t.MasterTopics.RINGTONE,(function(){n._startRingtone(e),n._prevContactId=e.getContactId(),e.onConnected(lily.hitch(n,n._stopRingtone)),e.onAccepted(lily.hitch(n,n._stopRingtone)),e.onEnded(lily.hitch(n,n._stopRingtone)),e.onRefresh((function(e){e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING&&n._stopRingtone()}))}))},n.prototype._publishTelemetryEvent=function(e,n){n&&n.getContactId()&&t.publishMetric({name:e,contactId:n.getContactId()})},n.prototype.setOutputDevice=function(t){return this._playableAudioPromise?Promise.race([this._playableAudioPromise,new Promise((function(t,n){e.setTimeout((function(){n("Timed out waiting for playable audio")}),3e3)}))]).then((function(e){return e?e.setSinkId?Promise.resolve(e.setSinkId(t)):Promise.reject("Not supported"):Promise.reject("No audio found")})):e.Promise?Promise.reject("Not eligible ringtone owner"):void 0};var r=function(e){n.call(this,e)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.VOICE&&n.isSoftphoneCall()&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Ringtone Connecting",n),t.getLog().info("Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)})),(new t.Agent).getContacts().forEach((function(e){e.getStatus().type===t.ContactStatusType.CONNECTING&&n(e)}))};var o=function(e){n.call(this,e)};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.CHAT&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Chat Ringtone Connecting",n),t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var i=function(e){n.call(this,e)};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.TASK&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Task Ringtone Connecting",n),t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var s=function(e){n.call(this,e)};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype._driveRingtone=function(){var e=this;t.contact((function(n){n.onIncoming((function(){n.getType()===lily.ContactType.QUEUE_CALLBACK&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Callback Ringtone Connecting",n),t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer())}))}))},t.VoiceRingtoneEngine=r,t.ChatRingtoneEngine=o,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},642:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,e.ccpVersion="V2";var n={};n[t.SoftphoneCallType.AUDIO_ONLY]="Audio",n[t.SoftphoneCallType.VIDEO_ONLY]="Video",n[t.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[t.SoftphoneCallType.NONE]="None";var r="audio_input",o="audio_output";({})[t.ContactType.VOICE]="Voice";var i=[],s={},a={},c=null,u=null,l=null,p=t.SoftphoneErrorTypes,h={},d=t.randomId(),f=function(e){return new Promise((function(n,r){t.core.getClient().call(t.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){n(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&w("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),r(Error("requestIceAccess failed"))},authFailure:function(){r(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){r(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var n=t.core.getUpstream(),r=e.getAgentConnection();if(r){var o=r.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),n.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(e.contactId)}),n.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,e.contactId),data:new t.Contact(e.contactId)})):l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer():l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer()}else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer()},m=function(){t.core.getEventBus().subscribe(t.EventType.MUTE,b)},v=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_SPEAKER_DEVICE,C)},y=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_MICROPHONE_DEVICE,T)},E=function(){try{t.isChromeBrowser()&&t.getChromeBrowserVersion()>43&&navigator.permissions.query({name:"microphone"}).then((function(e){e.onchange=function(){l.info("Microphone Permission: "+e.state),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:e.state}),"denied"===e.state&&w(p.MICROPHONE_NOT_SHARED,"Your microphone is not enabled in your browser. ","")}}))}catch(e){l.error("Failed in detecting microphone permission status: "+e)}},S=function(e){delete h[e],t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},b=function(e){var n;if(0!==t.keys(h).length){for(var r in e&&void 0!==e.mute&&(n=e.mute),h)if(h.hasOwnProperty(r)){var o=h[r].stream;if(o){var i=o.getAudioTracks()[0];void 0!==n?(i.enabled=!n,h[r].muted=n,n?l.info("Agent has muted the contact, connectionId - "+r).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+r).sendInternalLogToServer()):n=h[r].muted||!1}}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:n}})}},C=function(e){if(0!==t.keys(h).length&&e&&e.deviceId){var n=e.deviceId,r=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+n),r&&"function"==typeof r.setSinkId&&r.setSinkId(n)}catch(e){l.error("Failed to set speaker to device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:n}})}},T=function(e){if(0!==t.keys(h).length&&e&&e.deviceId){var n=e.deviceId,r=t.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:n}}}).then((function(e){var t=e.getAudioTracks()[0];for(var n in h)h.hasOwnProperty(n)&&(h[n].stream,r.getSession(n)._pc.getSenders()[0].replaceTrack(t).then((function(){r.replaceLocalMediaTrack(n,t)})))}))}catch(e){l.error("Failed to set microphone device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:n}})}},I=function(e,n){if(n===t.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var r="\n",o=0;o0?t.success(e):t.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){t.failure(p.MICROPHONE_NOT_SHARED)})),r}t.failure(p.UNSUPPORTED_BROWSER)},w=function(e,n,r){l.error("Softphone error occurred : ",e,n||"").sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.SOFTPHONE_ERROR,data:new t.SoftphoneError(e,n,r)})},R=function(e,t){N("Softphone Session Failed",e,{failedReason:t})},N=function(e,n,r){t.publishMetric({name:e,contactId:n,data:r})},k=function(e,t,n){N(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},L=function(){return!!(t.isOperaBrowser()&&t.getOperaBrowserVersion()>17)||!!(t.isChromeBrowser()&&t.getChromeBrowserVersion()>22)||!!(t.isFirefoxBrowser()&&t.getFirefoxBrowserVersion()>21)},O=function(e){var t=i.slice();i=[],t.length>0&&e.sendSoftphoneMetrics(t,{success:function(){l.info("sendSoftphoneMetrics success"+JSON.stringify(t)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer()}})},D=function(e){c=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(M(s,t,r))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=a;a=e,i.push(M(a,t,o))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},P=function(e){u=window.setInterval((function(){O(e)}),3e4)},x=function(){s=null,a=null,i=[],c=null,u=null},M=function(e,t,n){if(t&&e){var r=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,o=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,r,o,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},U=function(e){return null!==e&&window.clearInterval(e),null},F=function(e,t){c=U(c),u=U(u),function(e,t,n,i){t.streamStats=[B(n,r),B(i,o)];var s={callStartTime:t.sessionStartTime,callEndTime:t.sessionEndTime,gumTimeMillis:t.gumTimeMillis,initializationTimeMillis:t.initializationTimeMillis,iceCollectionTimeMillis:t.iceCollectionTimeMillis,signallingConnectTimeMillis:t.signallingConnectTimeMillis,handshakingTimeMillis:t.handshakingTimeMillis,preTalkingTimeMillis:t.preTalkingTimeMillis,talkingTimeMillis:t.talkingTimeMillis,cleanupTimeMillis:t.cleanupTimeMillis,iceCollectionFailure:t.iceCollectionFailure,signallingConnectionFailure:t.signallingConnectionFailure,handshakingFailure:t.handshakingFailure,gumOtherFailure:t.gumOtherFailure,gumTimeoutFailure:t.gumTimeoutFailure,createOfferFailure:t.createOfferFailure,setLocalDescriptionFailure:t.setLocalDescriptionFailure,userBusyFailure:t.userBusyFailure,invalidRemoteSDPFailure:t.invalidRemoteSDPFailure,noRemoteIceCandidateFailure:t.noRemoteIceCandidateFailure,setRemoteDescriptionFailure:t.setRemoteDescriptionFailure,softphoneStreamStatistics:t.streamStats};e.sendSoftphoneReport(s,{success:function(){l.info("sendSoftphoneReport success"+JSON.stringify(s)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer()}})}(e,t,B(s,r),B(a,o)),O(e)},q=function(e,t,n,r,o,i,s){this.softphoneStreamType=r,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=o,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},B=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var n=this;this._tee=function(e,r){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),r.apply(n._originalLogger,[t.LogComponent.SOFTPHONE,o].concat(e))}}};j.prototype.debug=function(){return this._tee(1,this._originalLogger.debug)(arguments)},j.prototype.info=function(){return this._tee(2,this._originalLogger.info)(arguments)},j.prototype.log=function(){return this._tee(3,this._originalLogger.log)(arguments)},j.prototype.warn=function(){return this._tee(4,this._originalLogger.warn)(arguments)},j.prototype.error=function(){return this._tee(5,this._originalLogger.error)(arguments)},t.SoftphoneManager=function(e){var n,r=this;(l=new j(t.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),t.RtcPeerConnectionFactory&&(n=new t.RtcPeerConnectionFactory(l,t.core.getWebSocketManager(),d,t.hitch(r,f,{transportType:"softphone",softphoneClientId:d}),t.hitch(r,w))),L()||w(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){t.core.setSoftphoneUserMediaStream(e),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"granted"})},failure:function(e){w(e,"Your microphone is not enabled in your browser. ",""),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"denied"})}}),m(),v(),y(),E(),this.ringtoneEngine=null;var o={},i={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var s=!1,a=null,c=null,u=function(){s=!1,a=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=h[e].stream;if(n){var r=n.getAudioTracks()[0];t.enabled=r.enabled,r.enabled=!1,n.removeTrack(r),n.addTrack(t)}};var b=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,r){delete o[e],delete i[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,r){var p=s?a:e,d=s?c:r;if(p&&d){u(),i[d]=!0,l.info("Softphone call detected:","contactId "+p.getContactId(),"agent connectionId "+d).sendInternalLogToServer(),function(e){if(Object.keys(e).length>0){for(var t in e)e.hasOwnProperty(t)&&(k("MultiSessionHangUp",e[t].callId,t),b(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===t.ContactStatusType.CONNECTING&&N("Softphone Connecting",p.getContactId()),x();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=_(m.callConfigJson);v.useWebSocketProvider&&(f=t.core.getWebSocketManager());var y=new t.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),d,f);o[d]=y,t.core.getSoftphoneUserMediaStream()&&(y.mediaStream=t.core.getSoftphoneUserMediaStream()),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConnectionEvents.SESSION_INIT,data:{connectionId:d}}),y.onSessionFailed=function(e,t){delete o[d],delete i[d],I(e,t),R(p.getContactId(),t),F(p,e.sessionReport)},y.onSessionConnected=function(e){N("Softphone Session Connected",p.getContactId()),t.becomeMaster(t.MasterTopics.SEND_LOGS),D(e),P(p),g(p)},y.onSessionCompleted=function(e){N("Softphone Session Completed",p.getContactId()),delete o[d],delete i[d],F(p,e.sessionReport),S(d)},y.onLocalStreamAdded=function(e,n){h[d]={stream:n},t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:d}})},y.remoteAudioElement=document.getElementById("remote-audio"),n?y.connect(n.get(v.iceServers)):y.connect()}};var C=function(e,n){o[n]&&function(e){return e.getStatus().type===t.ContactStatusType.ENDED||e.getStatus().type===t.ContactStatusType.ERROR||e.getStatus().type===t.ContactStatusType.MISSED}(e)&&(b(n),u()),!e.isSoftphoneCall()||i[n]||e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING||(t.isFirefoxBrowser()&&t.hasOtherConnectedCCPs()?function(e,t){s=!0,a=e,c=t}(e,n):r.startSession(e,n))},T=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),i[t]||e.onRefresh((function(){C(e,t)}))};r.onInitContactSub=t.contact(T),(new t.Agent).getContacts().forEach((function(e){var t=e.getAgentConnection().connectionId;l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId"+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),T(e),C(e,t)}))}}()},944:()=>{!function(){var e=this||window,t=function(){return t.cache.hasOwnProperty(arguments[0])||(t.cache[arguments[0]]=t.parse(arguments[0])),t.format.call(null,t.cache[arguments[0]],arguments)};function n(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}t.format=function(e,o){var i,s,a,c,u,l,p,h=1,d=e.length,f="",g=[];for(s=0;s>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}i=/[def]/.test(c[8])&&c[3]&&i>=0?"+"+i:i,l=c[4]?"0"==c[4]?"0":c[4].charAt(1):" ",p=c[6]-String(i).length,u=c[6]?r(l,p):"",g.push(c[5]?i+u:u+i)}return g.join("")},t.cache={},t.parse=function(e){for(var t=e,n=[],r=[],o=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))r.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))r.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){o|=1;var i=[],s=n[2],a=[];if(null===(a=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(a[1]);""!==(s=s.substring(a[0].length));)if(null!==(a=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(a[1]);else{if(null===(a=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(a[1])}n[2]=i}else o|=2;if(3===o)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";r.push(n)}t=t.substring(n[0].length)}return r},e.sprintf=t,e.vsprintf=function(e,n,r){return(r=n.slice(0)).splice(0,0,e),t.apply(null,r)}}()},82:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(){};n.prototype.send=function(e){throw new t.NotImplementedError},n.prototype.onMessage=function(e){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.onMessage=function(e){},r.prototype.send=function(e){};var o=function(e,t){n.call(this),this.window=e,this.domain=t||"*"};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.send=function(e){this.window.postMessage(e,this.domain)},o.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var i=function(e,t,r){n.call(this),this.input=e,this.output=t,this.domain=r||"*"};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype.send=function(e){this.output.postMessage(e,this.domain)},i.prototype.onMessage=function(e){this.input.addEventListener("message",(t=>{t.source===this.output&&e(t)}))};var s=function(e){n.call(this),this.port=e,this.id=t.randomId()};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype.send=function(e){this.port.postMessage(e)},s.prototype.onMessage=function(e){this.port.addEventListener("message",e)},s.prototype.getId=function(){return this.id};var a=function(e){n.call(this),this.streamMap=e?t.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},a.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},a.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},a.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},a.prototype.getStreams=function(e){return t.values(this.streamMap)},a.prototype.getStreamForPort=function(e){return t.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,n,o){this.name=e,this.upstream=n||new r,this.downstream=o||new r,this.downstreamBus=new t.EventBus,this.upstreamBus=new t.EventBus,this.upstream.onMessage(t.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(t.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.upstreamBus.subscribe(e,n)},c.prototype.onAllUpstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.downstreamBus.subscribe(e,n)},c.prototype.onAllDownstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,n){t.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:n})},c.prototype.sendDownstream=function(e,n){t.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:n})},c.prototype._dispatchEvent=function(e,t){var n=t.data;n.event&&e.trigger(n.event,n.data)},c.prototype.passUpstream=function(){var e=this;return function(t,n){e.upstream.send({event:n,data:t})}},c.prototype.passDownstream=function(){var e=this;return function(t,n){e.downstream.send({event:n,data:t})}},c.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};var u=function(e,t,n,r){c.call(this,e,new i(t,n.contentWindow,r||"*"),null)};(u.prototype=Object.create(c.prototype)).constructor=u,t.Stream=n,t.NullStream=r,t.WindowStream=o,t.WindowIOStream=i,t.PortStream=s,t.StreamMultiplexer=a,t.Conduit=c,t.IFrameConduit=u}()},833:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(e,n){t.assertNotNull(e,"fromState"),t.assertNotNull(n,"toState"),this.fromState=e,this.toState=n};n.prototype.getAssociations=function(e){throw t.NotImplementedError()},n.prototype.getFromState=function(){return this.fromState},n.prototype.getToState=function(){return this.toState};var r=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"associations"),n.call(this,e,r),this.associations=o};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.getAssociations=function(e){return this.associations};var o=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"closure"),t.assertTrue(t.isFunction(o),"closure must be a function"),n.call(this,e,r),this.closure=o};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var i=function(){this.fromMap={}};i.ANY="<>",i.prototype.assoc=function(e,t,n){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!n)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,n)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,n)})):"function"==typeof n?this._addAssociation(new o(e,t,n)):n instanceof Array?this._addAssociation(new r(e,t,n)):this._addAssociation(new r(e,t,[n])),this},i.prototype.getAssociations=function(e,n,r){t.assertNotNull(n,"fromState"),t.assertNotNull(r,"toState");var o=[],s=this.fromMap[i.ANY]||{},a=this.fromMap[n]||{};return o=(o=o.concat(this._getAssociationsFromMap(s,e,n,r))).concat(this._getAssociationsFromMap(a,e,n,r))},i.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];t||(t=this.fromMap[e.getFromState()]={});var n=t[e.getToState()];n||(n=t[e.getToState()]=[]),n.push(e)},i.prototype._getAssociationsFromMap=function(e,t,n,r){return(e[i.ANY]||[]).concat(e[r]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},t.EventGraph=i}()},891:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=navigator.userAgent,r=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];t.sprintf=e.sprintf,t.vsprintf=e.vsprintf,delete e.sprintf,delete e.vsprintf,t.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},t.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},t.hitch=function(){var e=Array.prototype.slice.call(arguments),n=e.shift(),r=e.shift();return t.assertNotNull(n,"scope"),t.assertNotNull(r,"method"),t.assertTrue(t.isFunction(r),"method must be a function"),function(){var t=Array.prototype.slice.call(arguments);return r.apply(n,e.concat(t))}},t.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.keys=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(r);return n},t.values=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(e[r]);return n},t.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},t.merge=function(){var e=Array.prototype.slice.call(arguments,0),n={};return e.forEach((function(e){t.entries(e).forEach((function(e){n[e.key]=e.value}))})),n},t.now=function(){return(new Date).getTime()},t.find=function(e,t){for(var n=0;n{try{n[r]=e[r]}catch(e){t.getLog().info("deepcopyCrossOriginEvent failed on key: ",r).sendInternalLogToServer()}})),t.deepcopy(n)},t.getBaseUrl=function(){var n=e.location;return t.sprintf("%s//%s:%s",n.protocol,n.hostname,n.port)},t.getUrlWithProtocol=function(n){var r=e.location.protocol;return n.substr(0,r.length)!==r?t.sprintf("%s//%s",r,n):n},t.isFramed=function(){try{return window.self!==window.top}catch(e){return!0}},t.hasOtherConnectedCCPs=function(){return t.numberOfConnectedCCPs>1},t.fetch=function(e,n,r,o){return o=o||5,r=r||1e3,n=n||{},new Promise((function(i,s){!function o(a){fetch(e,n).then((function(e){e.status===t.HTTP_STATUS_CODES.SUCCESS?e.json().then((e=>i(e))).catch((()=>i({}))):1!==a&&(e.status>=t.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===t.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--a)}),r):s(e)})).catch((function(e){s(e)}))}(o)}))},t.backoff=function(n,r,o,i){t.assertTrue(t.isFunction(n),"func must be a Function");var s=this;n({success:function(e){i&&i.success&&i.success(e)},failure:function(t,a){if(o>0){var c=2*r*Math.random();e.setTimeout((function(){s.backoff(n,2*c,--o,i)}),c)}else i&&i.failure&&i.failure(t,a)}})},t.publishMetric=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.CLIENT_METRIC,data:e})},t.publishSoftphoneStats=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_STATS,data:e})},t.publishSoftphoneReport=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_REPORT,data:e})},t.publishClientSideLogs=function(e){t.core.getEventBus().trigger(t.EventType.CLIENT_SIDE_LOGS,e)},t.PopupManager=function(){},t.PopupManager.prototype.open=function(e,t,n){var r=this._getLastOpenedTimestamp(t),o=(new Date).getTime(),i=null;if(o-r>864e5){if(n){var s=n.height||578,a=n.width||433,c=n.top||0,u=n.left||0;(i=window.open("",t,"width="+a+", height="+s+", top="+c+", left="+u)).location!==e&&(i=window.open(e,t,"width="+a+", height="+s+", top="+c+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,o)}return i},t.PopupManager.prototype.clear=function(t){var n=this._getLocalStorageKey(t);e.localStorage.removeItem(n)},t.PopupManager.prototype._getLastOpenedTimestamp=function(t){var n=this._getLocalStorageKey(t),r=e.localStorage.getItem(n);return r?parseInt(r,10):0},t.PopupManager.prototype._setLastOpenedTimestamp=function(t,n){var r=this._getLocalStorageKey(t);e.localStorage.setItem(r,""+n)},t.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var o=t.makeEnum(["granted","denied","default"]);t.NotificationManager=function(){this.queue=[],this.permission=o.DEFAULT},t.NotificationManager.prototype.requestPermission=function(){var n=this;"Notification"in e?e.Notification.permission===o.DENIED?(t.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=o.DENIED):this.permission!==o.GRANTED&&e.Notification.requestPermission().then((function(e){n.permission=e,e===o.GRANTED?n._showQueued():n.queue=[]})):(t.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=o.DENIED)},t.NotificationManager.prototype.show=function(e,n){if(this.permission===o.GRANTED)return this._showImpl({title:e,options:n});if(this.permission===o.DENIED)t.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:n});else{var r={title:e,options:n};t.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(r).sendInternalLogToServer(),this.queue.push(r)}},t.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},t.NotificationManager.prototype._showImpl=function(t){var n=new e.Notification(t.title,t.options);return t.options.clicked&&(n.onclick=function(){t.options.clicked.call(n)}),n},t.BaseError=function(n,r){e.Error.call(this,t.vsprintf(n,r))},t.BaseError.prototype=Object.create(Error.prototype),t.BaseError.prototype.constructor=t.BaseError,t.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.ValueError.prototype=Object.create(t.BaseError.prototype),t.ValueError.prototype.constructor=t.ValueError,t.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.NotImplementedError.prototype=Object.create(t.BaseError.prototype),t.NotImplementedError.prototype.constructor=t.NotImplementedError,t.StateError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.StateError.prototype=Object.create(t.BaseError.prototype),t.StateError.prototype.constructor=t.StateError,t.VoiceIdError=function(e,t,n){var r={};return r.type=e,r.message=t,r.stack=Error(t).stack,r.err=n,r},t.isCCP=function(){return"ConnectSharedWorkerConduit"===t.core.getUpstream().name}}()},736:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.worker={};var n=function(){this.topicMasterMap={}};n.prototype.getMaster=function(e){return t.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},n.prototype.setMaster=function(e,n){t.assertNotNull(e,"topic"),t.assertNotNull(n,"id"),this.topicMasterMap[e]=n},n.prototype.removeMaster=function(e){t.assertNotNull(e,"id");var n=this;t.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete n.topicMasterMap[e.key]}))};var r=function(e){t.ClientBase.call(this),this.conduit=e};(r.prototype=Object.create(t.ClientBase.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){var o=this,i=(new Date).getTime();t.containsValue(t.AgentAppClientMethods,e)?t.core.getAgentAppClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.core.getClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t,n){o._recordAPILatency(e,i,t),r.failure(t,n)},authFailure:function(){o._recordAPILatency(e,i),r.authFailure()},accessDenied:function(){r.accessDenied&&r.accessDenied()}})},r.prototype._recordAPILatency=function(e,t,n){var r=(new Date).getTime()-t;this._sendAPIMetrics(e,r,n)},r.prototype._sendAPIMetrics=function(e,n,r){this.conduit.sendDownstream(t.EventType.API_METRIC,{name:e,time:n,dimensions:[{name:"Category",value:"API"}],error:r})};var o=function(){var o=this;this.multiplexer=new t.StreamMultiplexer,this.conduit=new t.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new r(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.masterCoord=new n,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1;var i=null;t.rootLogger=new t.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(t.EventType.SEND_LOGS,(function(e){t.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(t.EventType.CONFIGURE,(function(n){n.authToken&&n.authToken!==o.initData.authToken&&(o.initData=n,t.core.init(n),i?t.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(t.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),t.WebSocketManager.setGlobalConfig({loggerConfig:{logger:t.getLog()}}),(i=t.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(t.WebSocketEvents.INIT_FAILURE)})),i.onConnectionOpen((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_OPEN,e)})),i.onConnectionClose((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_CLOSE,e)})),i.onConnectionGain((function(){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_GAIN)})),i.onConnectionLost((function(e){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_LOST,e)})),i.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),i.onSubscriptionFailure((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),i.onAllMessage((function(e){o.conduit.sendDownstream(t.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(t.WebSocketEvents.SEND,(function(e){i.sendMessage(e)})),o.conduit.onDownstream(t.WebSocketEvents.SUBSCRIBE,(function(e){i.subscribeTopics(e)})),i.init(t.hitch(o,o.getWebSocketUrl)).then((function(n){try{if(n&&!n.webSocketConnectionFailed)t.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),t.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),t.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(t.hitch(o,o.checkAuthToken),3e5);else if(!t.webSocketInitFailed){const e=t.WebSocketEvents.INIT_FAILURE;throw o.conduit.sendDownstream(e),t.webSocketInitFailed=!0,new Error(e)}}catch(e){t.getLog().error("WebSocket failed to initialize").withException(e).sendInternalLogToServer()}}))))})),this.conduit.onDownstream(t.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),t.core.terminate(),o.conduit.sendDownstream(t.EventType.TERMINATED)})),this.conduit.onDownstream(t.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(t.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(t.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var n=e.ports[0],r=new t.PortStream(n);o.multiplexer.addStream(r),n.start();var i=new t.Conduit(r.getId(),null,r);i.sendDownstream(t.EventType.ACKNOWLEDGE,{id:r.getId()}),o.portConduitMap[r.getId()]=i,o.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),i.onDownstream(t.EventType.API_REQUEST,t.hitch(o,o.handleAPIRequest,i)),i.onDownstream(t.EventType.MASTER_REQUEST,t.hitch(o,o.handleMasterRequest,i,r.getId())),i.onDownstream(t.EventType.RELOAD_AGENT_CONFIGURATION,t.hitch(o,o.pollForAgentConfiguration)),i.onDownstream(t.EventType.CLOSE,(function(){o.multiplexer.removeStream(r),delete o.portConduitMap[r.getId()],o.masterCoord.removeMaster(r.getId()),o.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length})}))}};o.prototype.pollForAgent=function(){var n=this,r=t.hitch(n,n.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:n.nextToken,timeout:3e4},{success:function(r){try{n.agent=n.agent||{},n.agent.snapshot=r.snapshot,n.agent.snapshot.localTimestamp=t.now(),n.agent.snapshot.skew=n.agent.snapshot.snapshotTimestamp-n.agent.snapshot.localTimestamp,n.nextToken=r.nextToken,t.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(r).sendInternalLogToServer(),n.updateAgent()}catch(e){t.getLog().error("Long poll failed to update agent.").withObject(r).withException(e).sendInternalLogToServer()}finally{e.setTimeout(t.hitch(n,n.pollForAgent),100)}},failure:function(r,o){try{t.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:r,data:o})}finally{e.setTimeout(t.hitch(n,n.pollForAgent),5e3)}},authFailure:function(){r()},accessDenied:t.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(n){var r=this,o=n||{},i=t.hitch(r,r.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(n){var i=n.configuration;r.pollForAgentPermissions(i),r.pollForAgentStates(i),r.pollForDialableCountryCodes(i),r.pollForRoutingProfileQueues(i),o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration,o),3e4)},failure:function(n,i){try{t.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:n,data:i})}finally{o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration),3e4,o)}},authFailure:function(){i()},accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,n){var r=this;this.client.call(n.method,n.params,{success:function(r){var o=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,r);e.sendDownstream(o.event,o)},failure:function(o,i){var s=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,i,JSON.stringify(o));e.sendDownstream(s.event,s),t.getLog().error("'%s' API request failed",n.method).withObject({request:r.filterAuthToken(n),response:s}).withException(o).sendInternalLogToServer()},authFailure:t.hitch(r,r.handleAuthFail)})},o.prototype.handleMasterRequest=function(e,n,r){var o=this.conduit,i=null;switch(r.method){case t.MasterMethods.BECOME_MASTER:var s=this.masterCoord.getMaster(r.params.topic),a=Boolean(s)&&s!==n;this.masterCoord.setMaster(r.params.topic,n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:n,takeOver:a,topic:r.params.topic}),a&&o.sendDownstream(i.event,i);break;case t.MasterMethods.CHECK_MASTER:(s=this.masterCoord.getMaster(r.params.topic))||r.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(r.params.topic,n),s=n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:s,isMaster:n===s,topic:r.params.topic});break;default:throw new Error("Unknown master method: "+r.method)}e.sendDownstream(i.event,i)},o.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):t.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},o.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&this.agent.snapshot.contacts.length>1&&this.agent.snapshot.contacts.sort((function(e,t){return e.state.timestamp.getTime()-t.state.timestamp.getTime()})),this.agent.snapshot.contacts.forEach((function(e){e.status=e.state,e.connections.forEach((function(e){e.address=e.endpoint}))})),this.agent.configuration.routingProfile.defaultOutboundQueue.queueId=this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN,this.agent.configuration.routingProfile.queues.forEach((function(e){e.queueId=e.queueARN})),this.agent.snapshot.contacts.forEach((function(e){void 0!==e.queue&&(e.queue.queueId=e.queue.queueARN)})),this.agent.configuration.routingProfile.routingProfileId=this.agent.configuration.routingProfile.routingProfileARN,this.conduit.sendDownstream(t.AgentEvents.UPDATE,this.agent)):t.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,n=t.core.getClient(),r=t.hitch(e,e.handleAuthFail),o=t.hitch(e,e.handleAccessDenied);return new Promise((function(e,i){n.call(t.ClientMethods.CREATE_TRANSPORT,{transportType:t.TRANSPORT_TYPES.WEB_SOCKET},{success:function(n){t.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:n}),i({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){t.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),i(Error("Authentication failed while getting getWebSocketUrl")),r()},accessDenied:function(){t.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),i(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,n=[],r=e.logsBuffer.slice();e.logsBuffer=[],r.forEach((function(e){n.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(t.ClientMethods.SEND_CLIENT_LOGS,{logEvents:n},{success:function(e){t.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,n){t.getLog().error("SendLogs request failed.").withObject(n).withException(e).sendInternalLogToServer()},authFailure:t.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(){this.conduit.sendDownstream(t.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(t.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,n=new Date(e.initData.authTokenExpiration),r=(new Date).getTime();n.getTime(){var e={821:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.agentApp={};var n="ccp";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];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)};t.agentApp.initApp=function(e,o,i,s){s=s||{};var a=i.endsWith("/")?i:i+"/",c=s.onLoad?s.onLoad:null,u={endpoint:a,style:s.style,onLoad:c};t.agentApp.AppRegistry.register(e,u,document.getElementById(o)),t.agentApp.AppRegistry.start(e,(function(o){var i=o.endpoint,a=o.containerDOM;return{init:function(){return e===n?(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}},s=t.merge(i,o.ccpParams);t.core.initCCP(n,s)}(i,a,s)):t.agentApp.initAppCommunication(e,i)},destroy:function(){return e===n?(o=r(i)+"/logout",t.fetch(o,{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=o,!1}))):null;var o}}}))},t.agentApp.stopApp=function(e){return t.agentApp.AppRegistry.stop(e)}}()},500:()=>{!function(){var e=this||window,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,s=n[e].style,a=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.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),o}(e,i,s,a);o.appendChild(c)}return n[e].instance=t(n[e]),n[e].instance.init()}},stop:function(e){if(n[e]){var t,r=n[e],o=r.containerDOM.querySelector("iframe");return r.containerDOM.removeChild(o),r.instance&&(t=r.instance.destroy(),delete r.instance),t}}})}()},965:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.AgentStateType=t.makeEnum(["init","routable","not_routable","offline"]),t.AgentStatusType=t.AgentStateType,t.AgentAvailStates=t.makeEnum(["Init","Busy","AfterCallWork","CallingCustomer","Dialing","Joining","PendingAvailable","PendingBusy"]),t.AgentErrorStates=t.makeEnum(["Error","AgentHungUp","BadAddressAgent","BadAddressCustomer","Default","FailedConnectAgent","FailedConnectCustomer","InvalidLocale","LineEngagedAgent","LineEngagedCustomer","MissedCallAgent","MissedCallCustomer","MultipleCcpWindows","RealtimeCommunicationError"]),t.EndpointType=t.makeEnum(["phone_number","agent","queue"]),t.AddressType=t.EndpointType,t.ConnectionType=t.makeEnum(["agent","inbound","outbound","monitoring"]),t.ConnectionStateType=t.makeEnum(["init","connecting","connected","hold","disconnected"]),t.ConnectionStatusType=t.ConnectionStateType,t.CONNECTION_ACTIVE_STATES=t.set([t.ConnectionStateType.CONNECTING,t.ConnectionStateType.CONNECTED,t.ConnectionStateType.HOLD]),t.ContactStateType=t.makeEnum(["init","incoming","pending","connecting","connected","missed","error","ended"]),t.ContactStatusType=t.ContactStateType,t.CONTACT_ACTIVE_STATES=t.makeEnum(["incoming","pending","connecting","connected"]),t.ContactType=t.makeEnum(["voice","queue_callback","chat","task"]),t.ContactInitiationMethod=t.makeEnum(["inbound","outbound","transfer","queue_transfer","callback","api","disconnect"]),t.ContactRecordingVoiceTrackConfig=t.makeEnum(["ALL","TO_AGENT","FROM_AGENT"]),t.ChannelType=t.makeEnum(["VOICE","CHAT","TASK"]),t.MediaType=t.makeEnum(["softphone","chat","task"]),t.SoftphoneCallType=t.makeEnum(["audio_video","video_only","audio_only","none"]),t.SoftphoneErrorTypes=t.makeEnum(["unsupported_browser","microphone_not_shared","signalling_handshake_failure","signalling_connection_failure","ice_collection_timeout","user_busy_error","webrtc_error","realtime_communication_error","other"]),t.VoiceIdErrorTypes=t.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"]),t.CTIExceptions=t.makeEnum(["AccessDeniedException","InvalidStateException","BadEndpointException","InvalidAgentARNException","InvalidConfigurationException","InvalidContactTypeException","PaginationException","RefreshTokenExpiredException","SendDataFailedException","UnauthorizedException","QuotaExceededException"]),t.VoiceIdStreamingStatus=t.makeEnum(["ONGOING","ENDED","PENDING_CONFIGURATION"]),t.VoiceIdAuthenticationDecision=t.makeEnum(["ACCEPT","REJECT","NOT_ENOUGH_SPEECH","SPEAKER_NOT_ENROLLED","SPEAKER_OPTED_OUT","SPEAKER_ID_NOT_PROVIDED","SPEAKER_EXPIRED"]),t.VoiceIdFraudDetectionDecision=t.makeEnum(["NOT_ENOUGH_SPEECH","HIGH_RISK","LOW_RISK"]),t.ContactFlowAuthenticationDecision=t.makeEnum(["Authenticated","NotAuthenticated","Inconclusive","NotEnrolled","OptedOut","NotEnabled","Error"]),t.ContactFlowFraudDetectionDecision=t.makeEnum(["HighRisk","LowRisk","Inconclusive","NotEnabled","Error"]),t.VoiceIdEnrollmentRequestStatus=t.makeEnum(["NOT_ENOUGH_SPEECH","IN_PROGRESS","COMPLETED","FAILED"]),t.VoiceIdSpeakerStatus=t.makeEnum(["OPTED_OUT","ENROLLED","PENDING"]),t.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},t.AgentPermissions={OUTBOUND_CALL:"outboundCall",VOICE_ID:"voiceId",CONTACT_RECORDING:"contactRecording"};var n=function(){if(!t.agent.initialized)throw new t.StateError("The agent is not yet initialized!")};n.prototype._getData=function(){return t.core.getAgentDataProvider().getAgentData()},n.prototype._createContactAPI=function(e){return new t.Contact(e.contactId)},n.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(t.AgentEvents.REFRESH,e)},n.prototype.onRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ROUTABLE,e)},n.prototype.onNotRoutable=function(e){t.core.getEventBus().subscribe(t.AgentEvents.NOT_ROUTABLE,e)},n.prototype.onOffline=function(e){t.core.getEventBus().subscribe(t.AgentEvents.OFFLINE,e)},n.prototype.onError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ERROR,e)},n.prototype.onSoftphoneError=function(e){t.core.getEventBus().subscribe(t.AgentEvents.SOFTPHONE_ERROR,e)},n.prototype.onWebSocketConnectionLost=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e)},n.prototype.onWebSocketConnectionGained=function(e){t.core.getEventBus().subscribe(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED,e)},n.prototype.onAfterCallWork=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ACW,e)},n.prototype.onStateChange=function(e){t.core.getEventBus().subscribe(t.AgentEvents.STATE_CHANGE,e)},n.prototype.onMuteToggle=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.MUTE_TOGGLE,e)},n.prototype.onLocalMediaStreamCreated=function(e){t.core.getUpstream().onUpstream(t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,e)},n.prototype.onSpeakerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,e)},n.prototype.onMicrophoneDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,e)},n.prototype.onRingerDeviceChanged=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.RINGER_DEVICE_CHANGED,e)},n.prototype.mute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!0}})},n.prototype.unmute=function(){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE,data:{mute:!1}})},n.prototype.setSpeakerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_SPEAKER_DEVICE,data:{deviceId:e}})},n.prototype.setMicrophoneDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_MICROPHONE_DEVICE,data:{deviceId:e}})},n.prototype.setRingerDevice=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SET_RINGER_DEVICE,data:{deviceId:e}})},n.prototype.getState=function(){return this._getData().snapshot.state},n.prototype.getNextState=function(){return this._getData().snapshot.nextState},n.prototype.getAvailabilityState=function(){return this._getData().snapshot.agentAvailabilityState},n.prototype.getStatus=n.prototype.getState,n.prototype.getStateDuration=function(){return t.now()-this._getData().snapshot.state.startTimestamp.getTime()+t.core.getSkew()},n.prototype.getStatusDuration=n.prototype.getStateDuration,n.prototype.getPermissions=function(){return this.getConfiguration().permissions},n.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}))},n.prototype.getConfiguration=function(){return this._getData().configuration},n.prototype.getAgentStates=function(){return this.getConfiguration().agentStates},n.prototype.getRoutingProfile=function(){return this.getConfiguration().routingProfile},n.prototype.getChannelConcurrency=function(e){var n=this.getRoutingProfile().channelConcurrencyMap;return n||(n=Object.keys(t.ChannelType).reduce((function(e,n){return"TASK"!==n&&(e[t.ChannelType[n]]=1),e}),{})),e?n[e]||0:n},n.prototype.getName=function(){return this.getConfiguration().name},n.prototype.getExtension=function(){return this.getConfiguration().extension},n.prototype.getDialableCountries=function(){return this.getConfiguration().dialableCountries},n.prototype.isSoftphoneEnabled=function(){return this.getConfiguration().softphoneEnabled},n.prototype.setConfiguration=function(e,n){var r=t.core.getClient();e&&e.agentPreferences&&e.agentPreferences.LANGUAGE&&!e.agentPreferences.locale&&(e.agentPreferences.locale=e.agentPreferences.LANGUAGE),e&&e.agentPreferences&&!t.isValidLocale(e.agentPreferences.locale)?n&&n.failure&&n.failure(t.AgentErrorStates.INVALID_LOCALE):r.call(t.ClientMethods.UPDATE_AGENT_CONFIGURATION,{configuration:t.assertNotNull(e,"configuration")},{success:function(e){t.core.getUpstream().sendUpstream(t.EventType.RELOAD_AGENT_CONFIGURATION),n.success&&n.success(e)},failure:n&&n.failure})},n.prototype.setState=function(e,n,r){t.core.getClient().call(t.ClientMethods.PUT_AGENT_STATE,{state:t.assertNotNull(e,"state"),enqueueNextState:r&&!!r.enqueueNextState},n)},n.prototype.onEnqueuedNextState=function(e){t.core.getEventBus().subscribe(t.AgentEvents.ENQUEUED_NEXT_STATE,e)},n.prototype.setStatus=n.prototype.setState,n.prototype.connect=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_OUTBOUND_CONTACT,{endpoint:t.assertNotNull(o,"endpoint"),queueARN:n&&(n.queueARN||n.queueId)||this.getRoutingProfile().defaultOutboundQueue.queueARN},n&&{success:n.success,failure:n.failure})},n.prototype.getAllQueueARNs=function(){return this.getConfiguration().routingProfile.queues.map((function(e){return e.queueARN}))},n.prototype.getEndpoints=function(e,n,r){var o=this,i=t.core.getClient();t.assertNotNull(n,"callbacks"),t.assertNotNull(n.success,"callbacks.success");var s=r||{};s.endpoints=s.endpoints||[],s.maxResults=s.maxResults||t.DEFAULT_BATCH_SIZE,t.isArray(e)||(e=[e]),i.call(t.ClientMethods.GET_ENDPOINTS,{queueARNs:e,nextToken:s.nextToken||null,maxResults:s.maxResults},{success:function(r){if(r.nextToken)o.getEndpoints(e,n,{nextToken:r.nextToken,maxResults:s.maxResults,endpoints:s.endpoints.concat(r.endpoints)});else{s.endpoints=s.endpoints.concat(r.endpoints);var i=s.endpoints.map((function(e){return new t.Endpoint(e)}));n.success({endpoints:i,addresses:i})}},failure:n.failure})},n.prototype.getAddresses=n.prototype.getEndpoints,n.prototype._getResourceId=function(){var e=this.getAllQueueARNs();for(let t of e){const e=t.match(/\/agent\/([^/]+)/);if(e)return e[1]}return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ",e)},n.prototype.toSnapshot=function(){return new t.AgentSnapshot(this._getData())};var r=function(e){t.Agent.call(this),this.agentData=e};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._getData=function(){return this.agentData},r.prototype._createContactAPI=function(e){return new t.ContactSnapshot(e)};var o=function(e){this.contactId=e};o.prototype._getData=function(){return t.core.getAgentDataProvider().getContactData(this.getContactId())},o.prototype._createConnectionAPI=function(e){return this.getType()===t.ContactType.CHAT?new t.ChatConnection(this.contactId,e.connectionId):this.getType()===t.ContactType.TASK?new t.TaskConnection(this.contactId,e.connectionId):new t.VoiceConnection(this.contactId,e.connectionId)},o.prototype.getEventName=function(e){return t.core.getContactEventName(e,this.getContactId())},o.prototype.onRefresh=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.REFRESH),e)},o.prototype.onIncoming=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.INCOMING),e)},o.prototype.onConnecting=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTING),e)},o.prototype.onPending=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.PENDING),e)},o.prototype.onAccepted=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACCEPTED),e)},o.prototype.onMissed=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.MISSED),e)},o.prototype.onEnded=function(e){var n=t.core.getEventBus();n.subscribe(this.getEventName(t.ContactEvents.ENDED),e),n.subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onDestroy=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.DESTROYED),e)},o.prototype.onACW=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ACW),e)},o.prototype.onConnected=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.CONNECTED),e)},o.prototype.onError=function(e){t.core.getEventBus().subscribe(this.getEventName(t.ContactEvents.ERROR),e)},o.prototype.getContactId=function(){return this.contactId},o.prototype.getOriginalContactId=function(){return this._getData().initialContactId},o.prototype.getInitialContactId=o.prototype.getOriginalContactId,o.prototype.getType=function(){return this._getData().type},o.prototype.getContactDuration=function(){return this._getData().contactDuration},o.prototype.getState=function(){return this._getData().state},o.prototype.getStatus=o.prototype.getState,o.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},o.prototype.getStatusDuration=o.prototype.getStateDuration,o.prototype.getQueue=function(){return this._getData().queue},o.prototype.getQueueTimestamp=function(){return this._getData().queueTimestamp},o.prototype.getConnections=function(){var e=this;return this._getData().connections.map((function(n){return e.getType()===t.ContactType.CHAT?new t.ChatConnection(e.contactId,n.connectionId):e.getType()===t.ContactType.TASK?new t.TaskConnection(e.contactId,n.connectionId):new t.VoiceConnection(e.contactId,n.connectionId)}))},o.prototype.getInitialConnection=function(){return t.find(this.getConnections(),(function(e){return e.isInitialConnection()}))||null},o.prototype.getActiveInitialConnection=function(){var e=this.getInitialConnection();return null!=e&&e.isActive()?e:null},o.prototype.getThirdPartyConnections=function(){return this.getConnections().filter((function(e){return!e.isInitialConnection()&&e.getType()!==t.ConnectionType.AGENT}))},o.prototype.getSingleActiveThirdPartyConnection=function(){return this.getThirdPartyConnections().filter((function(e){return e.isActive()}))[0]||null},o.prototype.getAgentConnection=function(){return t.find(this.getConnections(),(function(e){var n=e.getType();return n===t.ConnectionType.AGENT||n===t.ConnectionType.MONITORING}))},o.prototype.getName=function(){return this._getData().name},o.prototype.getContactMetadata=function(){return this._getData().contactMetadata},o.prototype.getDescription=function(){return this._getData().description},o.prototype.getReferences=function(){return this._getData().references},o.prototype.getAttributes=function(){return this._getData().attributes},o.prototype.getContactFeatures=function(){return this._getData().contactFeatures},o.prototype.getChannelContext=function(){return this._getData().channelContext},o.prototype.isSoftphoneCall=function(){return null!=t.find(this.getConnections(),(function(e){return null!=e.getSoftphoneMediaInfo()}))},o.prototype._isInbound=function(){return this._getData().initiationMethod!==t.ContactInitiationMethod.OUTBOUND},o.prototype.isInbound=function(){var e=this.getInitialConnection();return e.getMediaType()===t.MediaType.TASK?this._isInbound():!!e&&e.getType()===t.ConnectionType.INBOUND},o.prototype.isConnected=function(){return this.getStatus().type===t.ContactStateType.CONNECTED},o.prototype.accept=function(e){var n=t.core.getClient(),r=this,o=this.getContactId();n.call(t.ClientMethods.ACCEPT_CONTACT,{contactId:o},{success:function(n){var i=t.core.getUpstream();i.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(o)}),i.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,r.getContactId()),data:new t.Contact(o)});var s=new t.Contact(o);t.isFirefoxBrowser()&&s.isSoftphoneCall()&&t.core.triggerReadyToStartSessionEvent(),e&&e.success&&e.success(n)},failure:e?e.failure:null})},o.prototype.destroy=function(){t.getLog().warn("contact.destroy() has been deprecated.")},o.prototype.reject=function(e){t.core.getClient().call(t.ClientMethods.REJECT_CONTACT,{contactId:this.getContactId()},e)},o.prototype.complete=function(e){t.core.getClient().call(t.ClientMethods.COMPLETE_CONTACT,{contactId:this.getContactId()},e)},o.prototype.clear=function(e){t.core.getClient().call(t.ClientMethods.CLEAR_CONTACT,{contactId:this.getContactId()},e)},o.prototype.notifyIssue=function(e,n,r){t.core.getClient().call(t.ClientMethods.NOTIFY_CONTACT_ISSUE,{contactId:this.getContactId(),issueCode:e,description:n},r)},o.prototype.addConnection=function(e,n){var r=t.core.getClient(),o=new t.Endpoint(e);delete o.endpointId,r.call(t.ClientMethods.CREATE_ADDITIONAL_CONNECTION,{contactId:this.getContactId(),endpoint:o},n)},o.prototype.toggleActiveConnections=function(e){var n=t.core.getClient(),r=null,o=t.find(this.getConnections(),(function(e){return e.getStatus().type===t.ConnectionStateType.HOLD}));if(null!=o)r=o.getConnectionId();else{var i=this.getConnections().filter((function(e){return e.isActive()}));i.length>0&&(r=i[0].getConnectionId())}n.call(t.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:r},e)},o.prototype.sendSoftphoneMetrics=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,softphoneStreamStatistics:n},r),t.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:e.ccpVersion,stats:n})},o.prototype.sendSoftphoneReport=function(n,r){t.core.getClient().call(t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n},r),t.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:e.ccpVersion,report:n})},o.prototype.conferenceConnections=function(e){t.core.getClient().call(t.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},o.prototype.toSnapshot=function(){return new t.ContactSnapshot(this._getData())},o.prototype.isMultiPartyConferenceEnabled=function(){var e=this.getContactFeatures();return!(!e||!e.multiPartyConferenceEnabled)};var i=function(e){t.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(o.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new t.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return t.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},s.prototype.getContactId=function(){return this.contactId},s.prototype.getConnectionId=function(){return this.connectionId},s.prototype.getEndpoint=function(){return new t.Endpoint(this._getData().endpoint)},s.prototype.getAddress=s.prototype.getEndpoint,s.prototype.getState=function(){return this._getData().state},s.prototype.getStatus=s.prototype.getState,s.prototype.getStateDuration=function(){return t.now()-this._getData().state.timestamp.getTime()+t.core.getSkew()},s.prototype.getStatusDuration=s.prototype.getStateDuration,s.prototype.getType=function(){return this._getData().type},s.prototype.isInitialConnection=function(){return this._getData().initial},s.prototype.isActive=function(){return t.contains(t.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===t.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===t.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){t.core.getClient().call(t.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,n){t.core.getClient().call(t.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},n)},s.prototype.hold=function(e){t.core.getClient().call(t.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){t.core.getClient().call(t.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new t.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&t.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===t.ConnectionType.AGENT||e===t.ConnectionType.MONITORING};var a=function(e){this.contactId=t.core.getAgentDataProvider().getContactData(e)?e:null};a.prototype.startContactRecording=function(e){var n,r,o=this;n=t.core.getClient(),r=t.core.getAgentDataProvider().getContactData(o.contactId);var i=e&&Object.values(t.ContactRecordingVoiceTrackConfig).includes(e)?e:t.ContactRecordingVoiceTrackConfig.ALL;return new Promise((function(e,s){n.call(t.AgentAppClientMethods.START_CONTACT_RECORDING,{initialContactId:r.initialContactId||o.contactId,contactId:o.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),voiceRecordingConfiguration:{voiceRecordingTrack:i}},{success:function(n){t.getLog().info("startContactRecording succeeded").withObject(n).sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("startContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),s(Error("startContactRecording failed",{cause:e}))}})}))},a.prototype.stopContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.STOP_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("stopContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("stopContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("stopContactRecording failed",{cause:e}))}})}))},a.prototype.suspendContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.SUSPEND_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("suspendContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("suspendContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("suspendContactRecording failed",{cause:e}))}})}))},a.prototype.resumeContactRecording=function(){var e,n,r=this;return e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(r.contactId),new Promise((function(o,i){e.call(t.AgentAppClientMethods.RESUME_CONTACT_RECORDING,{initialContactId:n.initialContactId||r.contactId,contactId:r.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId()},{success:function(e){t.getLog().info("resumeContactRecording succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e,n){t.getLog().error("resumeContactRecording failed").sendInternalLogToServer().withObject({err:e,data:n}),i(Error("resumeContactRecording failed"),{cause:e})}})}))};var c=function(e){this.contactId=e};c.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){n.call(t.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),awsAccountId:t.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var n={speakerId:e.contactData.customerId};t.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),r(n)}else{var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(i)}},failure:function(e){t.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(n)}})}))},c.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){var n=JSON.parse(e);switch(n.status){case 400:case 404:var i=n;i.type=i.type?i.type:t.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,t.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),r(i);break;default:t.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var s=t.VoiceIdError(t.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(s)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype._optOutSpeakerInLcms=function(e){var n=this,r=t.core.getClient();return new Promise((function(o,i){r.call(t.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:n.contactId,InstanceId:t.core.getAgentDataProvider().getInstanceId(),AWSAccountId:t.core.getAgentDataProvider().getAWSAccountId(),CustomerId:t.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){t.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){t.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);i(n)}})}))},c.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(s){var a=i.speakerId;n.call(t.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:t.assertNotNull(a,"speakerId"),DomainId:s},{success:function(n){e._optOutSpeakerInLcms(a).catch((function(){})),t.getLog().info("optOutSpeaker succeeded").withObject(n).sendInternalLogToServer(),r(n)},failure:function(e){t.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getSpeakerId().then((function(i){e.getDomainId().then((function(e){n.call(t.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:t.assertNotNull(i.speakerId,"speakerId"),DomainId:e},{success:function(e){t.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),r(e)},failure:function(e){t.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(n)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.startSession=function(){var e=this;e.checkConferenceCall();var n=t.core.getClient();return new Promise((function(r,o){e.getDomainId().then((function(i){n.call(t.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:t.core.getAgentDataProvider().getInstanceId(),customerAccountId:t.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:i},{success:function(e){if(e.sessionId)r(e);else{t.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(n)}},failure:function(e){t.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var n=t.VoiceIdError(t.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(n)}})})).catch((function(e){o(e)}))}))},c.prototype.evaluateSpeaker=function(e){var n=this;n.checkConferenceCall();var r=t.core.getClient(),o=t.core.getAgentDataProvider().getContactData(this.contactId),i=0;return new Promise((function(s,a){function c(){n.getDomainId().then((function(e){r.call(t.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++i=1&&(o=r.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){t.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var i=t.VoiceIdError(t.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void n(i)}t.getLog().info("getDomainId succeeded").withObject(r).sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),i=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),n(i)}},failure:function(e){t.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var r=t.VoiceIdError(t.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);n(r)}}):n(new Error("Agent doesn't have the permission for Voice ID"))}))},c.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId is not supported for conference calls")},c.prototype.isAuthEnabled=function(e){return e!==t.ContactFlowAuthenticationDecision.NOT_ENABLED},c.prototype.isAuthResultNotEnoughSpeech=function(e){return e===t.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},c.prototype.isAuthResultInconclusive=function(e){return e===t.ContactFlowAuthenticationDecision.INCONCLUSIVE},c.prototype.isFraudEnabled=function(e){return e!==t.ContactFlowFraudDetectionDecision.NOT_ENABLED},c.prototype.isFraudResultNotEnoughSpeech=function(e){return e===t.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},c.prototype.isFraudResultInconclusive=function(e){return e===t.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var u=function(e,t){this._speakerAuthenticator=new c(e),this._contactRecorder=new a(e),s.call(this,e,t)};(u.prototype=Object.create(s.prototype)).constructor=u,u.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},u.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},u.prototype.getMediaType=function(){return t.MediaType.SOFTPHONE},u.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},u.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},u.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},u.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},u.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},u.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},u.prototype.enrollSpeakerInVoiceId=function(e){return this._speakerAuthenticator.enrollSpeaker(e)},u.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},u.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},u.prototype.isMute=function(){return this._getData().mute},u.prototype.muteParticipant=function(e){t.core.getClient().call(t.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},u.prototype.unmuteParticipant=function(e){t.core.getClient().call(t.ClientMethods.UNMUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},u.prototype.startContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.startContactRecording()},u.prototype.stopContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.stopContactRecording()},u.prototype.suspendContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.suspendContactRecording()},u.prototype.resumeContactRecording=function(){return this.checkConferenceCall(),this._contactRecorder.resumeContactRecording()},u.prototype.checkConferenceCall=function(){if(t.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return t.contains(t.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new t.NotImplementedError("VoiceId and Contact Recording are not supported for conference calls")};var l=function(e,t){s.call(this,e,t)};(l.prototype=Object.create(s.prototype)).constructor=l,l.prototype.getMediaInfo=function(){var e=this._getData().chatMediaInfo;if(e){var n=t.core.getAgentDataProvider().getContactData(this.contactId),r={contactId:this.contactId,initialContactId:n.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:t.hitch(this,this.getConnectionToken)};if(e.connectionData)try{r.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(n){t.getLog().error(t.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(n).sendInternalLogToServer(),r.participantToken=null}return r.participantToken=r.participantToken||null,r.originalInfo=this._getData().chatMediaInfo,r}return null},l.prototype.getConnectionToken=function(){var e=t.core.getClient(),n=t.core.getAgentDataProvider().getContactData(this.contactId),r={transportType:t.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:n.initialContactId||this.contactId};return new Promise((function(n,o){e.call(t.ClientMethods.CREATE_TRANSPORT,r,{success:function(e){t.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),n(e)},failure:function(e,n){t.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:n}),o(Error("getConnectionToken failed"))}})}))},l.prototype.getMediaType=function(){return t.MediaType.CHAT},l.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)},l.prototype._initMediaController=function(){this._isAgentConnectionType()&&t.core.mediaFactory.get(this).catch((function(){}))};var p=function(e,t){s.call(this,e,t)};(p.prototype=Object.create(s.prototype)).constructor=p,p.prototype.getMediaType=function(){return t.MediaType.TASK},p.prototype.getMediaInfo=function(){var e=t.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},p.prototype.getMediaController=function(){return t.core.mediaFactory.get(this)};var d=function(e){t.Connection.call(this,e.contactId,e.connectionId),this.connectionData=e};(d.prototype=Object.create(s.prototype)).constructor=d,d.prototype._getData=function(){return this.connectionData},d.prototype._initMediaController=function(){};var h=function(e){var t=e||{};this.endpointARN=t.endpointId||t.endpointARN||null,this.endpointId=this.endpointARN,this.type=t.type||null,this.name=t.name||null,this.phoneNumber=t.phoneNumber||null,this.agentLogin=t.agentLogin||null,this.queue=t.queue||null};h.prototype.stripPhoneNumber=function(){return this.phoneNumber?this.phoneNumber.replace(/sip:([^@]*)@.*/,"$1"):""},h.byPhoneNumber=function(e,n){return new h({type:t.EndpointType.PHONE_NUMBER,phoneNumber:e,name:n||null})};var f=function(e,t,n){this.errorType=e,this.errorMessage=t,this.endPointUrl=n};f.prototype.getErrorType=function(){return this.errorType},f.prototype.getErrorMessage=function(){return this.errorMessage},f.prototype.getEndPointUrl=function(){return this.endPointUrl},t.agent=function(e){var n=t.core.getEventBus().subscribe(t.AgentEvents.INIT,e);return t.agent.initialized&&e(new t.Agent),n},t.agent.initialized=!1,t.contact=function(e){return t.core.getEventBus().subscribe(t.ContactEvents.INIT,e)},t.onWebsocketInitFailure=function(e){var n=t.core.getEventBus().subscribe(t.WebSocketEvents.INIT_FAILURE,e);return t.webSocketInitFailed&&e(),n},t.ifMaster=function(e,n,r,o){if(t.assertNotNull(e,"A topic must be provided."),t.assertNotNull(n,"A true callback must be provided."),!t.core.masterClient)return t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(r&&r());t.core.getMasterClient().call(t.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?n():r&&r()}})},t.becomeMaster=function(e,n,r){t.assertNotNull(e,"A topic must be provided."),t.core.masterClient?t.core.getMasterClient().call(t.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){n&&n()}}):(t.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),r&&r())},t.Agent=n,t.AgentSnapshot=r,t.Contact=o,t.ContactSnapshot=i,t.Connection=u,t.BaseConnection=s,t.VoiceConnection=u,t.ChatConnection=l,t.TaskConnection=p,t.ConnectionSnapshot=d,t.Endpoint=h,t.Address=h,t.SoftphoneError=f,t.VoiceId=c,t.ContactRecording=a}()},827:(e,t,n)=>{var r;!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return o(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var i=void 0,s=0;s-1});var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]","[object DataView]"];t.exports={isEmptyData:function(e){return"string"==typeof e?0===e.length:0===e.byteLength},convertToBuffer:function(e){return"string"==typeof e&&(e=new r(e,"utf8")),ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}}},{"buffer/":81}],12:[function(e,t,n){var r=e("./browserHashUtils");function o(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=r.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var o=new e;o.update(n),n=o.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),o=new Uint8Array(e.BLOCK_SIZE);o.set(n);for(var i=0;i>>32-o)+n&4294967295}function c(e,t,n,r,o,i,s){return a(t&n|~t&r,e,t,o,i,s)}function u(e,t,n,r,o,i,s){return a(t&r|n&~r,e,t,o,i,s)}function l(e,t,n,r,o,i,s){return a(t^n^r,e,t,o,i,s)}function p(e,t,n,r,o,i,s){return a(n^(t|~r),e,t,o,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(r.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=r.convertToBuffer(e),n=0,o=t.byteLength;for(this.bytesHashed+=o;o>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),o--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,r=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var a=this.bufferLength;a>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var c=new DataView(new ArrayBuffer(16));for(a=0;a<4;a++)c.setUint32(4*a,this.state[a],!0);var u=new o(c.buffer,c.byteOffset,c.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],i=t[3];n=c(n,r,o,i,e.getUint32(0,!0),7,3614090360),i=c(i,n,r,o,e.getUint32(4,!0),12,3905402710),o=c(o,i,n,r,e.getUint32(8,!0),17,606105819),r=c(r,o,i,n,e.getUint32(12,!0),22,3250441966),n=c(n,r,o,i,e.getUint32(16,!0),7,4118548399),i=c(i,n,r,o,e.getUint32(20,!0),12,1200080426),o=c(o,i,n,r,e.getUint32(24,!0),17,2821735955),r=c(r,o,i,n,e.getUint32(28,!0),22,4249261313),n=c(n,r,o,i,e.getUint32(32,!0),7,1770035416),i=c(i,n,r,o,e.getUint32(36,!0),12,2336552879),o=c(o,i,n,r,e.getUint32(40,!0),17,4294925233),r=c(r,o,i,n,e.getUint32(44,!0),22,2304563134),n=c(n,r,o,i,e.getUint32(48,!0),7,1804603682),i=c(i,n,r,o,e.getUint32(52,!0),12,4254626195),o=c(o,i,n,r,e.getUint32(56,!0),17,2792965006),n=u(n,r=c(r,o,i,n,e.getUint32(60,!0),22,1236535329),o,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,r,o,e.getUint32(24,!0),9,3225465664),o=u(o,i,n,r,e.getUint32(44,!0),14,643717713),r=u(r,o,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,r,o,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,r,o,e.getUint32(40,!0),9,38016083),o=u(o,i,n,r,e.getUint32(60,!0),14,3634488961),r=u(r,o,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,r,o,i,e.getUint32(36,!0),5,568446438),i=u(i,n,r,o,e.getUint32(56,!0),9,3275163606),o=u(o,i,n,r,e.getUint32(12,!0),14,4107603335),r=u(r,o,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,r,o,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,r,o,e.getUint32(8,!0),9,4243563512),o=u(o,i,n,r,e.getUint32(28,!0),14,1735328473),n=l(n,r=u(r,o,i,n,e.getUint32(48,!0),20,2368359562),o,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,r,o,e.getUint32(32,!0),11,2272392833),o=l(o,i,n,r,e.getUint32(44,!0),16,1839030562),r=l(r,o,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,r,o,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,r,o,e.getUint32(16,!0),11,1272893353),o=l(o,i,n,r,e.getUint32(28,!0),16,4139469664),r=l(r,o,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,r,o,i,e.getUint32(52,!0),4,681279174),i=l(i,n,r,o,e.getUint32(0,!0),11,3936430074),o=l(o,i,n,r,e.getUint32(12,!0),16,3572445317),r=l(r,o,i,n,e.getUint32(24,!0),23,76029189),n=l(n,r,o,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,r,o,e.getUint32(48,!0),11,3873151461),o=l(o,i,n,r,e.getUint32(60,!0),16,530742520),n=p(n,r=l(r,o,i,n,e.getUint32(8,!0),23,3299628645),o,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,r,o,e.getUint32(28,!0),10,1126891415),o=p(o,i,n,r,e.getUint32(56,!0),15,2878612391),r=p(r,o,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,r,o,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,r,o,e.getUint32(12,!0),10,2399980690),o=p(o,i,n,r,e.getUint32(40,!0),15,4293915773),r=p(r,o,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,r,o,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,r,o,e.getUint32(60,!0),10,4264355552),o=p(o,i,n,r,e.getUint32(24,!0),15,2734768916),r=p(r,o,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,r,o,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,r,o,e.getUint32(44,!0),10,3174756917),o=p(o,i,n,r,e.getUint32(8,!0),15,718787259),r=p(r,o,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=r+t[1]&4294967295,t[2]=o+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils");function i(){this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=new Uint32Array(80),this.offset=0,this.shift=24,this.totalLength=0}new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53),t.exports=i,i.BLOCK_SIZE=64,i.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=(e=o.convertToBuffer(e)).length;this.totalLength+=8*t;for(var n=0;n14||14===this.offset&&this.shift<24)&&this.processBlock(),this.offset=14,this.shift=24,this.write(0),this.write(0),this.write(this.totalLength>0xffffffffff?this.totalLength/1099511627776:0),this.write(this.totalLength>4294967295?this.totalLength/4294967296:0);for(var t=24;t>=0;t-=8)this.write(this.totalLength>>t);var n=new r(20),o=new DataView(n.buffer);return o.setUint32(0,this.h0,!1),o.setUint32(4,this.h1,!1),o.setUint32(8,this.h2,!1),o.setUint32(12,this.h3,!1),o.setUint32(16,this.h4,!1),e?n.toString(e):n},i.prototype.processBlock=function(){for(var e=16;e<80;e++){var t=this.block[e-3]^this.block[e-8]^this.block[e-14]^this.block[e-16];this.block[e]=t<<1|t>>>31}var n,r,o=this.h0,i=this.h1,s=this.h2,a=this.h3,c=this.h4;for(e=0;e<80;e++){e<20?(n=a^i&(s^a),r=1518500249):e<40?(n=i^s^a,r=1859775393):e<60?(n=i&s|a&(i|s),r=2400959708):(n=i^s^a,r=3395469782);var u=(o<<5|o>>>27)+n+c+r+(0|this.block[e]);c=a,a=s,s=i<<30|i>>>2,i=o,o=u}for(this.h0=this.h0+o|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+c|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var r=e("buffer/").Buffer,o=e("./browserHashUtils"),i=64,s=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=Math.pow(2,53)-1;function c(){this.state=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}t.exports=c,c.BLOCK_SIZE=i,c.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(o.isEmptyData(e))return this;var t=0,n=(e=o.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>a)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},c.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=this.bufferLength;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var s=this.bufferLength;s>>24&255,a[4*s+1]=this.state[s]>>>16&255,a[4*s+2]=this.state[s]>>>8&255,a[4*s+3]=this.state[s]>>>0&255;return e?a.toString(e):a},c.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],o=t[2],a=t[3],c=t[4],u=t[5],l=t[6],p=t[7],d=0;d>>17|h<<15)^(h>>>19|h<<13)^h>>>10,g=((h=this.temp[d-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(f+this.temp[d-7]|0)+(g+this.temp[d-16]|0)}var m=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(p+(s[d]+this.temp[d]|0)|0)|0,v=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&o^r&o)|0;p=l,l=u,u=c,c=a+m|0,a=o,o=r,r=n,n=m+v|0}t[0]+=n,t[1]+=r,t[2]+=o,t[3]+=a,t[4]+=c,t[5]+=u,t[6]+=l,t[7]+=p}},{"./browserHashUtils":11,"buffer/":81}],16:[function(e,t,n){(function(n){(function(){var n=e("./util");n.crypto.lib=e("./browserCryptoLib"),n.Buffer=e("buffer/").Buffer,n.url=e("url/"),n.querystring=e("querystring/"),n.realClock=e("./realclock/browserClock"),n.environment="js",n.createEventStream=e("./event-stream/buffered-create-event-stream").createEventStream,n.isBrowser=function(){return!0},n.isNode=function(){return!1};var r=e("./core");if(t.exports=r,e("./credentials"),e("./credentials/credential_provider_chain"),e("./credentials/temporary_credentials"),e("./credentials/chainable_temporary_credentials"),e("./credentials/web_identity_credentials"),e("./credentials/cognito_identity_credentials"),e("./credentials/saml_credentials"),r.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===o)var o={browser:!0}}).call(this)}).call(this,e("_process"))},{"./browserCryptoLib":10,"./core":18,"./credentials":19,"./credentials/chainable_temporary_credentials":20,"./credentials/cognito_identity_credentials":21,"./credentials/credential_provider_chain":22,"./credentials/saml_credentials":23,"./credentials/temporary_credentials":24,"./credentials/web_identity_credentials":25,"./event-stream/buffered-create-event-stream":27,"./http/xhr":35,"./realclock/browserClock":52,"./util":71,"./xml/browser_parser":72,_process:86,"buffer/":81,"querystring/":92,"url/":94}],17:[function(e,t,n){var r,o=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),o.Config=o.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),o.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function r(t){e(t,t?null:n.credentials)}function i(e,t){return new o.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get((function(e){e&&(e=i("Could not load credentials from "+n.credentials.constructor.name,e)),r(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),r(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,r(e)})):r(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),o.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||o.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(o.util.readFileSync(e)),n=new o.FileSystemCredentials(e),r=new o.CredentialProviderChain;return r.providers.unshift(n),r.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){o.util.each.call(this,this.keys,(function(e){delete this[e]})),this.set("credentials",void 0),this.set("credentialProvider",void 0)},set:function(e,t,n){void 0===t?(void 0===n&&(n=this.keys[e]),this[e]="function"==typeof n?n.call(this):n):"httpOptions"===e&&this[e]?this[e]=o.util.merge(this[e],t):this[e]=t},keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:void 0,httpOptions:{timeout:12e4},maxRetries:void 0,maxRedirects:10,paramValidation:!0,sslEnabled:!0,s3ForcePathStyle:!1,s3BucketEndpoint:!1,s3DisableBodySigning:!0,computeChecksums:!0,convertResponseTypes:!0,correctClockSkew:!1,customUserAgent:null,dynamoDbCrc32:!0,systemClockOffset:0,signatureVersion:null,signatureCache:!0,retryDelayOptions:{},useAccelerateEndpoint:!1,clientSideMonitoring:!1,endpointDiscoveryEnabled:!1,endpointCacheSize:1e3,hostPrefixEnabled:!0,stsRegionalEndpoints:null},extractCredentials:function(e){return e.accessKeyId&&e.secretAccessKey&&((e=o.util.copy(e)).credentials=new o.Credentials(e)),e},setPromisesDependency:function(e){r=e,null===e&&"function"==typeof Promise&&(r=Promise);var t=[o.Request,o.Credentials,o.CredentialProviderChain];o.S3&&(t.push(o.S3),o.S3.ManagedUpload&&t.push(o.S3.ManagedUpload)),o.util.addPromises(t,r)},getPromisesDependency:function(){return r}}),o.config=new o.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var r={util:e("./util")};({}).toString(),t.exports=r,r.util.update(r,{VERSION:"2.553.0",Signers:{},Protocol:{Json:e("./protocol/json"),Query:e("./protocol/query"),Rest:e("./protocol/rest"),RestJson:e("./protocol/rest_json"),RestXml:e("./protocol/rest_xml")},XML:{Builder:e("./xml/builder"),Parser:null},JSON:{Builder:e("./json/builder"),Parser:e("./json/parser")},Model:{Api:e("./model/api"),Operation:e("./model/operation"),Shape:e("./model/shape"),Paginator:e("./model/paginator"),ResourceWaiter:e("./model/resource_waiter")},apiLoader:e("./api_loader"),EndpointCache:e("../vendor/endpoint-cache").EndpointCache}),e("./sequential_executor"),e("./service"),e("./config"),e("./http"),e("./event_listeners"),e("./request"),e("./response"),e("./resource_waiter"),e("./signers/request_signer"),e("./param_validator"),r.events=new r.SequentialExecutor,r.util.memoizedProperty(r,"endpointCache",(function(){return new r.EndpointCache(r.config.endpointCacheSize)}),!0)},{"../vendor/endpoint-cache":103,"./api_loader":9,"./config":17,"./event_listeners":33,"./http":34,"./json/builder":36,"./json/parser":37,"./model/api":38,"./model/operation":40,"./model/paginator":41,"./model/resource_waiter":42,"./model/shape":43,"./param_validator":44,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./request":55,"./resource_waiter":56,"./response":57,"./sequential_executor":58,"./service":59,"./signers/request_signer":63,"./util":71,"./xml/builder":73}],19:[function(e,t,n){var r=e("./core");r.Credentials=r.util.inherit({constructor:function(){if(r.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"==typeof arguments[0]){var e=arguments[0].credentials||arguments[0];this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken}else this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2]},expiryWindow:15,needsRefresh:function(){var e=r.util.date.getDate().getTime(),t=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&t>this.expireTime)||this.expired||!this.accessKeyId||!this.secretAccessKey},get:function(e){var t=this;this.needsRefresh()?this.refresh((function(n){n||(t.expired=!1),e&&e(n)})):e&&e()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,t){var n=this;1===n.refreshCallbacks.push(e)&&n.load((function(e){r.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):r.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),r.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=r.util.promisifyMethod("get",e),this.prototype.refreshPromise=r.util.promisifyMethod("refresh",e)},r.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},r.util.addPromises(r.Credentials)},{"./core":18}],20:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.ChainableTemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=r.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new r.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=r.util.merge({params:t,credentials:e.masterCredentials||r.config.credentials},e.stsConfig||{});this.service=new o(n)},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(r,o){var i={};r?e(r):(o&&(i.TokenCode=o),t.service[n](i,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,o){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(r.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,o)})):e(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var r=e("../core"),o=e("../../clients/cognitoidentity"),i=e("../../clients/sts");r.CognitoIdentityCredentials=r.util.inherit(r.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=r.util.copy(t||{}),this.loadCachedId();var n=this;Object.defineProperty(this,"identityId",{get:function(){return n.loadCachedId(),n._identityId||n.params.IdentityId},set:function(e){n._identityId=e}})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.data=null,t._identityId=null,t.getId((function(n){n?(t.clearIdOnNotAuthorized(n),e(n)):t.params.RoleArn?t.getCredentialsFromSTS(e):t.getCredentialsForIdentity(e)}))},clearCachedId:function(){this._identityId=null,delete this.params.IdentityId;var e=this.params.IdentityPoolId,t=this.params.LoginId||"";delete this.storage[this.localStorageKey.id+e+t],delete this.storage[this.localStorageKey.providers+e+t]},clearIdOnNotAuthorized:function(e){"NotAuthorizedException"==e.code&&this.clearCachedId()},getId:function(e){var t=this;if("string"==typeof t.params.IdentityId)return e(null,t.params.IdentityId);t.cognito.getId((function(n,r){!n&&r.IdentityId?(t.params.IdentityId=r.IdentityId,e(null,r.IdentityId)):e(n)}))},loadCredentials:function(e,t){e&&t&&(t.expired=!1,t.accessKeyId=e.Credentials.AccessKeyId,t.secretAccessKey=e.Credentials.SecretKey,t.sessionToken=e.Credentials.SessionToken,t.expireTime=e.Credentials.Expiration)},getCredentialsForIdentity:function(e){var t=this;t.cognito.getCredentialsForIdentity((function(n,r){n?t.clearIdOnNotAuthorized(n):(t.cacheId(r),t.data=r,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,r){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(r),t.params.WebIdentityToken=r.Token,t.webIdentityCredentials.refresh((function(n){n||(t.data=t.webIdentityCredentials.data,t.sts.credentialsFrom(t.data,t)),e(n)})))}))},loadCachedId:function(){var e=this;if(r.util.isBrowser()&&!e.params.IdentityId){var t=e.getStorage("id");if(t&&e.params.Logins){var n=Object.keys(e.params.Logins);0!==(e.getStorage("providers")||"").split(",").filter((function(e){return-1!==n.indexOf(e)})).length&&(e.params.IdentityId=t)}else t&&(e.params.IdentityId=t)}},createClients:function(){var e=this._clientConfig;if(this.webIdentityCredentials=this.webIdentityCredentials||new r.WebIdentityCredentials(this.params,e),!this.cognito){var t=r.util.merge({},e);t.params=this.params,this.cognito=new o(t)}this.sts=this.sts||new i(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,r.util.isBrowser()&&(this.setStorage("id",e.IdentityId),this.params.Logins&&this.setStorage("providers",Object.keys(this.params.Logins).join(",")))},getStorage:function(e){return this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]},setStorage:function(e,t){try{this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]=t}catch(e){}},storage:function(){try{var e=r.util.isBrowser()&&null!==window.localStorage&&"object"==typeof window.localStorage?window.localStorage:{};return e["aws.test-storage"]="foobar",delete e["aws.test-storage"],e}catch(e){return{}}}()})},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(e,t,n){var r=e("../core");r.CredentialProviderChain=r.util.inherit(r.Credentials,{constructor:function(e){this.providers=e||r.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var t=this;if(0===t.providers.length)return e(new Error("No providers")),t;if(1===t.resolveCallbacks.push(e)){var n=0,o=t.providers.slice(0);!function e(i,s){if(!i&&s||n===o.length)return r.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var a=o[n++];(s="function"==typeof a?a.call():a).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),r.CredentialProviderChain.defaultProviders=[],r.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=r.util.promisifyMethod("resolve",e)},r.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},r.util.addPromises(r.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.SAMLCredentials=r.util.inherit(r.Credentials,{constructor:function(e){r.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.TemporaryCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.loadMasterCredentials(t),this.expired=!0,this.params=e||{},this.params.RoleArn&&(this.params.RoleSessionName=this.params.RoleSessionName||"temporary-credentials")},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.masterCredentials.get((function(){t.service.config.credentials=t.masterCredentials,(t.params.RoleArn?t.service.assumeRole:t.service.getSessionToken).call(t.service,(function(n,r){n||t.service.credentialsFrom(r,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||r.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new r.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new o({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var r=e("../core"),o=e("../../clients/sts");r.WebIdentityCredentials=r.util.inherit(r.Credentials,{constructor:function(e,t){r.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=r.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||r.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,r){t.data=null,n||(t.data=r,t.service.credentialsFrom(r,t)),e(n)}))},createClients:function(){if(!this.service){var e=r.util.merge({},this._clientConfig);e.params=this.params,this.service=new o(e)}}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},r=(n.operations,{});return t.config.region&&(r.region=t.config.region),n.serviceId&&(r.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(r.accessKeyId=t.config.credentials.accessKeyId),r}function a(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&o.arrayEach(n.required,(function(r){var o=n.members[r];if(!0===o.endpointDiscoveryId){var i=o.isLocationName?o.name:r;e[i]=String(t[r])}else a(e,t[r],o)}))}function c(e,t){var n={};return a(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,a=c(e,i?i.input:void 0),u=s(e);Object.keys(a).length>0&&(u=o.update(u,a),i&&(u.operation=i.name));var l=r.endpointCache.get(u);if(!l||1!==l.length||""!==l[0].Address)if(l&&l.length>0)e.httpRequest.updateEndpoint(l[0].Address);else{var p=t.makeRequest(n.endpointOperation,{Operation:i.name,Identifiers:a});d(p),p.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",r.EventListeners.Core.RETRY_CHECK),r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?r.endpointCache.put(u,t.Endpoints):e&&r.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,a=i.operations?i.operations[e.operation]:void 0,u=a?a.input:void 0,p=c(e,u),h=s(e);Object.keys(p).length>0&&(h=o.update(h,p),a&&(h.operation=a.name));var f=r.EndpointCache.getKeyString(h),g=r.endpointCache.get(f);if(g&&1===g.length&&""===g[0].Address)return l[f]||(l[f]=[]),void l[f].push({request:e,callback:t});if(g&&g.length>0)e.httpRequest.updateEndpoint(g[0].Address),t();else{var m=n.makeRequest(i.endpointOperation,{Operation:a.name,Identifiers:p});m.removeListener("validate",r.EventListeners.Core.VALIDATE_PARAMETERS),d(m),r.endpointCache.put(f,[{Address:"",CachePeriodInMinutes:60}]),m.send((function(n,i){if(n){var s={code:"EndpointDiscoveryException",message:"Request cannot be fulfilled without specifying an endpoint",retryable:!1};if(e.response.error=o.error(n,s),r.endpointCache.remove(h),l[f]){var a=l[f];o.arrayEach(a,(function(e){e.request.response.error=o.error(n,s),e.callback()})),delete l[f]}}else i&&(r.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(a=l[f],o.arrayEach(a,(function(e){e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address),e.callback()})),delete l[f]);t()}))}}function d(e){var t=e.service.api.apiVersion;t&&!e.httpRequest.headers["x-amz-api-version"]&&(e.httpRequest.headers["x-amz-api-version"]=t)}function h(e){var t=e.error,n=e.httpResponse;if(t&&("InvalidEndpointException"===t.code||421===n.statusCode)){var i=e.request,a=i.service.api.operations||{},u=c(i,a[i.operation]?a[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=o.update(l,u),a[i.operation]&&(l.operation=a[i.operation].name)),r.endpointCache.remove(l)}}function f(e){return["false","0"].indexOf(e)>=0}t.exports={discoverEndpoint:function(e,t){var s=e.service||{};if(function(e){if(e._originalConfig&&e._originalConfig.endpoint&&!0===e._originalConfig.endpointDiscoveryEnabled)throw o.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=r.config[e.serviceIdentifier]||{};return Boolean(r.config.endpoint||t.endpoint||e._originalConfig&&e._originalConfig.endpoint)}(s)||e.isPresigned())return t();if(!function(e){if(!0===(e.service||{}).config.endpointDiscoveryEnabled)return!0;if(o.isBrowser())return!1;for(var t=0;t-1&&(e[t]++,0===e[t]);t--);}i.fromNumber=function(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(e+" is too large (or, if negative, too small) to represent as an Int64");for(var t=new Uint8Array(8),n=7,r=Math.abs(Math.round(e));n>-1&&r>0;n--,r/=256)t[n]=r;return e<0&&s(t),new i(t)},i.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&s(e),parseInt(e.toString("hex"),16)*(t?-1:1)},i.prototype.toString=function(){return String(this.valueOf())},t.exports={Int64:i}},{"../core":18}],30:[function(e,t,n){var r=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var o=r(t),i=o.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],r=new Error(n.value||n);return r.code=r.name=t.value||t,r}(o);if("event"!==i.value)return}var s=o.headers[":event-type"],a=n.members[s.value];if(a){var c={},u=a.eventPayloadMemberName;if(u){var l=a.members[u];"binary"===l.type?c[u]=o.body:c[u]=e.parse(o.body.toString(),l)}for(var p=a.eventHeaderMemberNames,d=0;d=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();r.util.computeSha256(i,(function(n,r){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=r,t())}))}else t()}})),e("SET_CONTENT_LENGTH","afterBuild",(function(e){var t=function(e){if(!e.service.api.operations)return"";var t=e.service.api.operations[e.operation];return t?t.authtype:""}(e),n=r.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var o=r.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=o}catch(r){if(n&&n.isStreaming){if(n.requiresLength)throw r;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw r}throw r}})),e("SET_HTTP_HOST","afterBuild",(function(e){e.httpRequest.headers.Host=e.httpRequest.endpoint.host})),e("RESTART","restart",(function(){var e=this.response.error;e&&e.retryable&&(this.httpRequest=new r.HttpRequest(this.service.endpoint,this.service.region),this.response.retryCount=600?this.emit("sign",[this],(function(e){e?t(e):i()})):i()})),e("HTTP_HEADERS","httpHeaders",(function(e,t,n,o){n.httpResponse.statusCode=e,n.httpResponse.statusMessage=o,n.httpResponse.headers=t,n.httpResponse.body=r.util.buffer.toBuffer(""),n.httpResponse.buffers=[],n.httpResponse.numBytes=0;var i=t.date||t.Date,s=n.request.service;if(i){var a=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(a)&&s.applyClockOffset(a)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(r.util.isNode()){t.httpResponse.numBytes+=e.length;var n=t.httpResponse.headers["content-length"],o={loaded:t.httpResponse.numBytes,total:n};t.request.emit("httpDownloadProgress",[o,t])}t.httpResponse.buffers.push(r.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=r.util.buffer.concat(e.httpResponse.buffers);e.httpResponse.body=t}delete e.httpResponse.numBytes,delete e.httpResponse.buffers})),e("FINALIZE_ERROR","retry",(function(e){e.httpResponse.statusCode&&(e.error.statusCode=e.httpResponse.statusCode,void 0===e.error.retryable&&(e.error.retryable=this.service.retryableError(e.error,this)))})),e("INVALIDATE_CREDENTIALS","retry",(function(e){if(e.error)switch(e.error.code){case"RequestExpired":case"ExpiredTokenException":case"ExpiredToken":e.error.retryable=!0,e.request.service.config.credentials.expired=!0}})),e("EXPIRED_SIGNATURE","retry",(function(e){var t=e.error;t&&"string"==typeof t.code&&"string"==typeof t.message&&t.code.match(/Signature/)&&t.message.match(/expired/)&&(e.error.retryable=!0)})),e("CLOCK_SKEWED","retry",(function(e){e.error&&this.service.clockSkewError(e.error)&&this.service.config.correctClockSkew&&(e.error.retryable=!0)})),e("REDIRECT","retry",(function(e){e.error&&e.error.statusCode>=300&&e.error.statusCode<400&&e.httpResponse.headers.location&&(this.httpRequest.endpoint=new r.Endpoint(e.httpResponse.headers.location),this.httpRequest.headers.Host=this.httpRequest.endpoint.host,e.error.redirect=!0,e.error.retryable=!0)})),e("RETRY_CHECK","retry",(function(e){e.error&&(e.error.redirect&&e.redirectCount=this.HEADERS_RECEIVED&&!p&&(c.statusCode=l.status,c.headers=s.parseHeaders(l.getAllResponseHeaders()),c.emit("headers",c.statusCode,c.headers,l.statusText),p=!0),this.readyState===this.DONE&&s.finishRequest(l,c)}),!1),l.upload.addEventListener("progress",(function(e){c.emit("sendProgress",e)})),l.addEventListener("progress",(function(e){c.emit("receiveProgress",e)}),!1),l.addEventListener("timeout",(function(){i(r.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),l.addEventListener("error",(function(){i(r.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),l.addEventListener("abort",(function(){i(r.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(c),l.open(e.method,u,!1!==t.xhrAsync),r.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&l.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(l.timeout=t.timeout),t.xhrWithCredentials&&(l.withCredentials=!0);try{l.responseType="arraybuffer"}catch(e){}try{e.body?l.send(e.body):l.send()}catch(t){if(!e.body||"object"!=typeof e.body.buffer)throw t;l.send(e.body.buffer)}return c},parseHeaders:function(e){var t={};return r.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],r=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=r)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var o=e.response;n=new r.util.Buffer(o.byteLength);for(var i=new Uint8Array(o),s=0;s-1?t||"":t,this.isJsonValue?JSON.parse(t):t&&"function"==typeof t.toString?t.toString():t},this.toWireFormat=function(e){return this.isJsonValue?JSON.stringify(e):e}}function h(){a.apply(this,arguments),this.toType=function(e){var t=o.base64.decode(e);if(this.isSensitive&&o.isNode()&&"function"==typeof o.Buffer.alloc){var n=o.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=o.base64.encode}function f(){h.apply(this,arguments)}function g(){a.apply(this,arguments),this.toType=function(e){return"boolean"==typeof e?e:null==e?null:"true"===e}}a.normalizedTypes={character:"string",double:"float",long:"integer",short:"integer",biginteger:"integer",bigdecimal:"float",blob:"binary"},a.types={structure:u,list:l,map:p,boolean:g,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)i(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)i(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)i(this,"timestampFormat","rfc822");else if("querystring"===this.location)i(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":i(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":i(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?o.date.parseTimestamp(e):null},this.toWireFormat=function(e){return o.date.format(e,t.timestampFormat)}},float:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseFloat(e)},this.toWireFormat=this.toType},integer:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseInt(e,10)},this.toWireFormat=this.toType},string:d,base64:f,binary:h},a.resolve=function(e,t){if(e.shape){var n=t.api.shapes[e.shape];if(!n)throw new Error("Cannot find shape reference: "+e.shape);return n}return null},a.create=function(e,t,n){if(e.isShape)return e;var r=a.resolve(e,t);if(r){var o=Object.keys(e);t.documentation||(o=o.filter((function(e){return!e.match(/documentation/)})));var i=function(){r.constructor.call(this,e,t,n)};return i.prototype=r,new i}e.type||(e.members?e.type="structure":e.member?e.type="list":e.key?e.type="map":e.type="string");var s=e.type;if(a.normalizedTypes[e.type]&&(e.type=a.normalizedTypes[e.type]),a.types[e.type])return new a.types[e.type](e,t,n);throw new Error("Unrecognized shape type: "+s)},a.shapes={StructureShape:u,ListShape:l,MapShape:p,StringShape:d,BooleanShape:g,Base64Shape:f},t.exports=a},{"../util":71,"./collection":39}],44:[function(e,t,n){var r=e("./core");r.ParamValidator=r.util.inherit({constructor:function(e){!0!==e&&void 0!==e||(e={min:!0}),this.validation=e},validate:function(e,t,n){if(this.errors=[],this.validateMember(e,t||{},n||"params"),this.errors.length>1){var o=this.errors.join("\n* ");throw o="There were "+this.errors.length+" validation errors:\n* "+o,r.util.error(new Error(o),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(r.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){var r;this.validateType(t,n,["object"],"structure");for(var o=0;e.required&&o= 1, but found "'+t+'" for '+n)},validatePattern:function(e,t,n){this.validation.pattern&&void 0!==e.pattern&&(new RegExp(e.pattern).test(t)||this.fail("PatternMatchError",'Provided value "'+t+'" does not match regex pattern /'+e.pattern+"/ for "+n))},validateRange:function(e,t,n,r){this.validation.min&&void 0!==e.min&&t= "+e.min+", but found "+t+" for "+n),this.validation.max&&void 0!==e.max&&t>e.max&&this.fail("MaxRangeError","Expected "+r+" <= "+e.max+", but found "+t+" for "+n)},validateEnum:function(e,t,n){this.validation.enum&&void 0!==e.enum&&-1===e.enum.indexOf(t)&&this.fail("EnumError","Found string value of "+t+", but expected "+e.enum.join("|")+" for "+n)},validateType:function(e,t,n,o){if(null==e)return!1;for(var i=!1,s=0;s63)throw r.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw o.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":18,"../util":71}],46:[function(e,t,n){var r=e("../util"),o=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,r=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",a=n.operations[e.operation].input,c=new o;1===i&&(i="1.0"),t.body=c.build(e.params||{},a),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=r,s(e)},extractError:function(e){var t={},n=e.httpResponse;if(t.code=n.headers["x-amzn-errortype"]||"UnknownError","string"==typeof t.code&&(t.code=t.code.split(":")[0]),n.body.length>0)try{var o=JSON.parse(n.body.toString());(o.__type||o.code)&&(t.code=(o.__type||o.code).split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=o.message||o.Message||null}catch(o){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=r.error(new Error,t)},extractData:function(e){var t=e.httpResponse.body.toString()||"{}";if(!1===e.request.service.config.convertResponseTypes)e.data=JSON.parse(t);else{var n=e.request.service.api.operations[e.request.operation].output||{},r=new i;e.data=r.parse(t,n)}}}},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(e,t,n){var r=e("../core"),o=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),a=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.service.api.operations[e.operation],n=e.httpRequest;n.headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8",n.params={Version:e.service.api.apiVersion,Action:t.name},(new i).serialize(e.params,t.input,(function(e,t){n.params[e]=t})),n.body=o.queryParamsToString(n.params),a(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var c=[];r.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new r.XML.Parser).parse(s.toString(),c);o.update(e.data,p)}}}},{"../core":18,"../util":71,"./rest":48}],51:[function(e,t,n){var r=e("../util");function o(){}function i(e){return e.isQueryName||"ec2"!==e.api.protocol?e.name:e.name[0].toUpperCase()+e.name.substr(1)}function s(e,t,n,o){r.each(n.members,(function(n,r){var s=t[n];if(null!=s){var c=i(r);a(c=e?e+"."+c:c,s,r,o)}}))}function a(e,t,n,o){null!=t&&("structure"===n.type?s(e,t,n,o):"list"===n.type?function(e,t,n,o){var s=n.member||{};0!==t.length?r.arrayEach(t,(function(t,r){var c="."+(r+1);if("ec2"===n.api.protocol)c+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else c="."+(s.name?s.name:"member")+c;a(e+c,t,s,o)})):o.call(this,e,null)}(e,t,n,o):"map"===n.type?function(e,t,n,o){var i=1;r.each(t,(function(t,r){var s=(n.flattened?".":".entry.")+i+++".",c=s+(n.key.name||"key"),u=s+(n.value.name||"value");a(e+c,t,n.key,o),a(e+u,r,n.value,o)}))}(e,t,n,o):o(e,n.toWireFormat(t).toString()))}o.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=o},{"../util":71}],52:[function(e,t,n){t.exports={now:function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}}},{}],53:[function(e,t,n){var r=e("./util"),o=e("./region_config_data.json");function i(e,t){r.each(t,(function(t,n){"globalEndpoint"!==t&&(void 0!==e.config[t]&&null!==e.config[t]||(e.config[t]=n))}))}t.exports=function(e){for(var t=function(e){var t=e.config.region,n=function(e){if(!e)return null;var t=e.split("-");return t.length<3?null:t.slice(0,t.length-2).join("-")+"-*"}(t),r=e.api.endpointPrefix;return[[t,r],[n,r],[t,"*"],[n,"*"],["*",r],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=0;n=0){c=!0;var u=0}var l=function(){c&&u!==a?o.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+a+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?o.end():o.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(c){var d=new e.PassThrough;d._write=function(t){return t&&t.length&&(u+=t.length),e.PassThrough.prototype._write.apply(this,arguments)},d.on("end",l),o.on("error",(function(e){c=!1,p.unpipe(d),d.emit("end"),d.end()})),p.pipe(d).pipe(o,{end:!1})}else p.pipe(o);else c&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){o.emit("data",e)})),p.on("end",l);p.on("error",(function(e){c=!1,o.emit("error",e)}))}})),o},emitEvent:function(e,t,r){"function"==typeof t&&(r=t,t=null),r||(r=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),r.call(this,e)}))},eventParameters:function(e){switch(e){case"restart":case"validate":case"sign":case"build":case"afterValidate":case"afterBuild":return[this];case"error":return[this.response.error,this.response];default:return[this.response]}},presign:function(e,t){return t||"function"!=typeof e||(t=e,e=null),(new n.Signers.Presign).sign(this.toGet(),e,t)},isPresigned:function(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,"presigned-expires")},toUnauthenticated:function(){return this._unAuthenticated=!0,this.removeListener("validate",n.EventListeners.Core.VALIDATE_CREDENTIALS),this.removeListener("sign",n.EventListeners.Core.SIGN),this},toGet:function(){return"query"!==this.service.api.protocol&&"ec2"!==this.service.api.protocol||(this.removeListener("build",this.buildAsGet),this.addListener("build",this.buildAsGet)),this},buildAsGet:function(e){e.httpRequest.method="GET",e.httpRequest.path=e.service.endpoint.path+"?"+e.httpRequest.body,e.httpRequest.body="",delete e.httpRequest.headers["Content-Length"],delete e.httpRequest.headers["Content-Type"]},haltHandlersOnError:function(){this._haltHandlersOnError=!0}}),n.Request.addPromisesToClass=function(e){this.prototype.promise=function(){var t=this;return this.httpRequest.appendToUserAgent("promise"),new e((function(e,n){t.on("complete",(function(t){t.error?n(t.error):e(Object.defineProperty(t.data||{},"$response",{value:t}))})),t.runTo()}))}},n.Request.deletePromisesFromClass=function(){delete this.prototype.promise},n.util.addPromises(n.Request),n.util.mixin(n.Request,n.SequentialExecutor)}).call(this)}).call(this,e("_process"))},{"./core":18,"./state_machine":70,_process:86,jmespath:85}],56:[function(e,t,n){var r=e("./core"),o=r.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,r=!1,o="retry";n.forEach((function(n){if(!r){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(r=!0,o=n.state)}})),!r&&e.error&&(o="failure"),"success"===o?t.setSuccess(e):t.setError(e,"retry"===o)}r.ResourceWaiter=o({constructor:function(e,t){this.service=e,this.state=t,this.loadWaiterConfig(this.state)},service:null,state:null,config:null,matchers:{path:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(r,t)},pathAll:function(e,t,n){try{var r=i.search(e.data,n)}catch(e){return!1}Array.isArray(r)||(r=[r]);var o=r.length;if(!o)return!1;for(var s=0;s-1&&n.splice(o,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var r=this.listeners(e),o=r.length;return this.callListeners(r,t,n),o>0},callListeners:function(e,t,n,o){var i=this,s=o||null;function a(o){if(o&&(s=r.util.error(s||new Error,o),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var c=e.shift();if(c._isAsync)return void c.apply(i,t.concat([a]));try{c.apply(i,t)}catch(e){s=r.util.error(s||new Error,e)}if(s&&i._haltHandlersOnError)return void n.call(i,s)}n.call(i,s)},addListeners:function(e){var t=this;return e._events&&(e=e._events),r.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),r.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,r){return this[e]=n,this.addListener(t,n,r),this},addNamedAsyncListener:function(e,t,n,r){return n._isAsync=!0,this.addNamedListener(e,t,n,r)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),r.SequentialExecutor.prototype.addListener=r.SequentialExecutor.prototype.on,t.exports=r.SequentialExecutor},{"./core":18}],59:[function(e,t,n){(function(n){(function(){var r=e("./core"),o=e("./model/api"),i=e("./region_config"),s=r.util.inherit,a=0;r.Service=s({constructor:function(e){if(!this.loadServiceClass)throw r.util.error(new Error,"Service must be constructed with `new' operator");var t=this.loadServiceClass(e||{});if(t){var n=r.util.copy(e),o=new t(e);return Object.defineProperty(o,"_originalConfig",{get:function(){return n},enumerable:!1,configurable:!0}),o._clientId=++a,o}this.initialize(e)},initialize:function(e){var t=r.config[this.serviceIdentifier];if(this.config=new r.Config(r.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||i(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),r.SequentialExecutor.call(this),r.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||r.Service._clientSideMonitoring)&&this.publisher){var o=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){o.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){o.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(r.util.isEmpty(this.api)){if(t.apiConfig)return r.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new r.Config(r.config)).update(e,!0);var n=t.apiVersions[this.constructor.serviceIdentifier];return n=n||t.apiVersion,this.getLatestServiceClass(n)}return null}return null},getLatestServiceClass:function(e){return e=this.getLatestServiceVersion(e),null===this.constructor.services[e]&&r.Service.defineServiceApi(this.constructor,e),this.constructor.services[e]},getLatestServiceVersion:function(e){if(!this.constructor.services||0===this.constructor.services.length)throw new Error("No services defined on "+this.constructor.serviceIdentifier);if(e?r.util.isType(e,Date)&&(e=r.util.date.iso8601(e).split("T")[0]):e="latest",Object.hasOwnProperty(this.constructor.services,e))return e;for(var t=Object.keys(this.constructor.services).sort(),n=null,o=t.length-1;o>=0;o--)if("*"!==t[o][t[o].length-1]&&(n=t[o]),t[o].substr(0,10)<=e)return n;throw new Error("Could not find "+this.constructor.serviceIdentifier+" API to satisfy version constraint `"+e+"'")},api:{},defaultRetryCount:3,customizeRequests:function(e){if(e){if("function"!=typeof e)throw new Error("Invalid callback type '"+typeof e+"' provided in customizeRequests");this.customRequestHandler=e}else this.customRequestHandler=null},makeRequest:function(e,t,n){if("function"==typeof t&&(n=t,t=null),t=t||{},this.config.params){var o=this.api.operations[e];o&&(t=r.util.copy(t),r.util.each(this.config.params,(function(e,n){o.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new r.Request(this,e,t);return this.addAllRequestListeners(i),this.attachMonitoringEmitter(i),n&&i.send(n),i},makeUnauthenticatedRequest:function(e,t,n){"function"==typeof t&&(n=t,t={});var r=this.makeRequest(e,t).toUnauthenticated();return n?r.send(n):r},waitFor:function(e,t,n){return new r.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[r.events,r.EventListeners.Core,this.serviceInterface(),r.EventListeners.CorePost],n=0;n299?(o.code&&(n.FinalAwsException=o.code),o.message&&(n.FinalAwsExceptionMessage=o.message)):((o.code||o.name)&&(n.FinalSdkException=o.code||o.name),o.message&&(n.FinalSdkExceptionMessage=o.message))}return n},apiAttemptEvent:function(e){var t=e.service.api.operations[e.operation],n={Type:"ApiCallAttempt",Api:t?t.name:e.operation,Version:1,Service:e.service.api.serviceId||e.service.api.endpointPrefix,Fqdn:e.httpRequest.endpoint.hostname,UserAgent:e.httpRequest.getUserAgent()},r=e.response;return r.httpResponse.statusCode&&(n.HttpStatusCode=r.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),r.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),r.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=r.httpResponse.headers["x-amzn-requestid"]),r.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=r.httpResponse.headers["x-amz-request-id"]),r.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=r.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,r=n.error;return n.httpResponse.statusCode>299?(r.code&&(t.AwsException=r.code),r.message&&(t.AwsExceptionMessage=r.message)):((r.code||r.name)&&(t.SdkException=r.code||r.name),r.message&&(t.SdkExceptionMessage=r.message)),t},attachMonitoringEmitter:function(e){var t,n,o,i,s,a,c=0,u=this;e.on("validate",(function(){i=r.util.realClock.now(),a=Date.now()}),!0),e.on("sign",(function(){n=r.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,c++}),!0),e.on("validateResponse",(function(){o=Math.round(r.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=o>=0?o:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,o=o||Math.round(r.util.realClock.now()-n),i.AttemptLatency=o>=0?o:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=c,!(t.AttemptCount<=0)){t.Timestamp=a;var n=Math.round(r.util.realClock.now()-i);t.Latency=n>=0?n:0;var o=e.response;"number"==typeof o.retryCount&&"number"==typeof o.maxRetries&&o.retryCount>=o.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSignerClass:function(e){var t,n=null,o="";return e&&(o=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===o||"v4-unsigned-body"===o?"v4":this.api.signatureVersion,r.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return r.EventListeners.Query;case"json":return r.EventListeners.Json;case"rest-json":return r.EventListeners.RestJson;case"rest-xml":return r.EventListeners.RestXml}if(this.api.protocol)throw new Error("Invalid service `protocol' "+this.api.protocol+" in API config")},successfulResponse:function(e){return e.httpResponse.statusCode<300},numRetries:function(){return void 0!==this.config.maxRetries?this.config.maxRetries:this.defaultRetryCount},retryDelays:function(e){return r.util.calculateRetryDelay(e,this.config.retryDelayOptions)},retryableError:function(e){return!!this.timeoutError(e)||!!this.networkingError(e)||!!this.expiredCredentialsError(e)||!!this.throttledError(e)||e.statusCode>=500},networkingError:function(e){return"NetworkingError"===e.code},timeoutError:function(e){return"TimeoutError"===e.code},expiredCredentialsError:function(e){return"ExpiredTokenException"===e.code},clockSkewError:function(e){switch(e.code){case"RequestTimeTooSkewed":case"RequestExpired":case"InvalidSignatureException":case"SignatureDoesNotMatch":case"AuthFailure":case"RequestInTheFuture":return!0;default:return!1}},getSkewCorrectedDate:function(){return new Date(Date.now()+this.config.systemClockOffset)},applyClockOffset:function(e){e&&(this.config.systemClockOffset=e-Date.now())},isClockSkewed:function(e){if(e)return Math.abs(this.getSkewCorrectedDate().getTime()-e)>=3e4},throttledError:function(e){if(429===e.statusCode)return!0;switch(e.code){case"ProvisionedThroughputExceededException":case"Throttling":case"ThrottlingException":case"RequestLimitExceeded":case"RequestThrottled":case"RequestThrottledException":case"TooManyRequestsException":case"TransactionInProgressException":return!0;default:return!1}},endpointFromTemplate:function(e){if("string"!=typeof e)return e;var t=e;return t=(t=(t=t.replace(/\{service\}/g,this.api.endpointPrefix)).replace(/\{region\}/g,this.config.region)).replace(/\{scheme\}/g,this.config.sslEnabled?"https":"http")},setEndpoint:function(e){this.endpoint=new r.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var o=new Error;throw r.util.error(o,"No pagination configuration for "+e)}return null}return n}}),r.util.update(r.Service,{defineMethods:function(e){r.util.each(e.prototype.api.operations,(function(t){e.prototype[t]||("none"===e.prototype.api.operations[t].authtype?e.prototype[t]=function(e,n){return this.makeUnauthenticatedRequest(t,e,n)}:e.prototype[t]=function(e,n){return this.makeRequest(t,e,n)})}))},defineService:function(e,t,n){r.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var o=s(r.Service,n||{});if("string"==typeof e){r.Service.addVersions(o,t);var i=o.serviceIdentifier||e;o.serviceIdentifier=i}else o.prototype.api=e,r.Service.defineMethods(o);if(r.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&r.util.clientSideMonitoring){var a=r.util.clientSideMonitoring.Publisher,c=(0,r.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new a(c),c.enabled&&(r.Service._clientSideMonitoring=!0)}return r.SequentialExecutor.call(o.prototype),r.Service.addDefaultMonitoringListeners(o.prototype),o},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n=0))throw n.util.error(new Error,t);this.config.stsRegionalEndpoints=e.toLowerCase()},validateRegionalEndpointsFlag:function(){var e=this.config;if(e.stsRegionalEndpoints&&this.validateRegionalEndpointsFlagValue(e.stsRegionalEndpoints,{code:"InvalidConfiguration",message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" or "regional". Got "'+e.stsRegionalEndpoints+'".'}),n.util.isNode()){if(Object.prototype.hasOwnProperty.call(t.env,o)){var r=t.env.AWS_STS_REGIONAL_ENDPOINTS;this.validateRegionalEndpointsFlagValue(r,{code:"InvalidEnvironmentalVariable",message:'invalid AWS_STS_REGIONAL_ENDPOINTS environmental variable. Expect "legacy" or "regional". Got "'+t.env.AWS_STS_REGIONAL_ENDPOINTS+'".'})}var s={};try{s=n.util.getProfilesFromSharedConfig(n.util.iniLoader)[t.env.AWS_PROFILE||n.util.defaultProfile]}catch(e){}if(s&&Object.prototype.hasOwnProperty.call(s,i)){var a=s.sts_regional_endpoints;this.validateRegionalEndpointsFlagValue(a,{code:"InvalidConfiguration",message:'invalid sts_regional_endpoints profile config. Expect "legacy" or "regional". Got "'+s.sts_regional_endpoints+'".'})}}},optInRegionalEndpoint:function(){this.validateRegionalEndpointsFlag();var e=this.config;if("regional"===e.stsRegionalEndpoints){if(r(this),!this.isGlobalEndpoint)return;if(this.isGlobalEndpoint=!1,!e.region)throw n.util.error(new Error,{code:"ConfigError",message:"Missing region in config"});var t=e.endpoint.indexOf(".amazonaws.com");e.endpoint=e.endpoint.substring(0,t)+"."+e.region+e.endpoint.substring(t)}},validateService:function(){this.optInRegionalEndpoint()}})}).call(this)}).call(this,e("_process"))},{"../core":18,"../region_config":53,_process:86}],62:[function(e,t,n){var r=e("../core"),o=r.util.inherit,i="presigned-expires";function s(e){var t=e.httpRequest.headers[i],n=e.service.getSignerClass(e);if(delete e.httpRequest.headers["User-Agent"],delete e.httpRequest.headers["X-Amz-User-Agent"],n===r.Signers.V4){if(t>604800)throw r.util.error(new Error,{code:"InvalidExpiryTime",message:"Presigning does not support expiry time greater than a week with SigV4 signing.",retryable:!1});e.httpRequest.headers[i]=t}else{if(n!==r.Signers.S3)throw r.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var o=e.service?e.service.getSkewCorrectedDate():r.util.date.getDate();e.httpRequest.headers[i]=parseInt(r.util.date.unixTimestamp(o)+t,10).toString()}}function a(e){var t=e.httpRequest.endpoint,n=r.util.urlParse(e.httpRequest.path),o={};n.search&&(o=r.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),o.AWSAccessKeyId=s[0],o.Signature=s[1],r.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete o[e],e=e.toLowerCase()),o[e]=t})),delete e.httpRequest.headers[i],delete o.Authorization,delete o.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var a=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];o["X-Amz-Signature"]=a,delete o.Expires}t.pathname=n.pathname,t.search=r.util.queryParamsToString(o)}r.Signers.Presign=o({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",a),e.removeListener("afterBuild",r.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",r.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return r.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,r.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=r.Signers.Presign},{"../core":18}],63:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.RequestSigner=o({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),r.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return r.Signers.V2;case"v3":return r.Signers.V3;case"s3v4":case"v4":return r.Signers.V4;case"s3":return r.Signers.S3;case"v3https":return r.Signers.V3Https}throw new Error("Unknown signing version "+e)},e("./v2"),e("./v3"),e("./v3https"),e("./v4"),e("./s3"),e("./presign")},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(e,t,n){var r=e("../core"),o=r.util.inherit;r.Signers.S3=o(r.Signers.RequestSigner,{subResources:{acl:1,accelerate:1,analytics:1,cors:1,lifecycle:1,delete:1,inventory:1,location:1,logging:1,metrics:1,notification:1,partNumber:1,policy:1,requestPayment:1,replication:1,restore:1,tagging:1,torrent:1,uploadId:1,uploads:1,versionId:1,versioning:1,versions:1,website:1},responseHeaders:{"response-content-type":1,"response-content-language":1,"response-expires":1,"response-cache-control":1,"response-content-disposition":1,"response-content-encoding":1},addAuthorization:function(e,t){this.request.headers["presigned-expires"]||(this.request.headers["X-Amz-Date"]=r.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),o="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=o},stringToSign:function(){var e=this.request,t=[];t.push(e.method),t.push(e.headers["Content-MD5"]||""),t.push(e.headers["Content-Type"]||""),t.push(e.headers["presigned-expires"]||"");var n=this.canonicalizedAmzHeaders();return n&&t.push(n),t.push(this.canonicalizedResource()),t.join("\n")},canonicalizedAmzHeaders:function(){var e=[];r.util.each(this.request.headers,(function(t){t.match(/^x-amz-/i)&&e.push(t)})),e.sort((function(e,t){return e.toLowerCase()=0?"&":"?";this.request.path+=i+r.util.queryParamsToString(o)},authorization:function(e,t){var n=[],r=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+r),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=o.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return r.util.crypto.hmac(n,this.stringToSign(t),"hex")},stringToSign:function(e){var t=[];return t.push("AWS4-HMAC-SHA256"),t.push(e),t.push(this.credentialString(e)),t.push(this.hexEncodedHash(this.canonicalString())),t.join("\n")},canonicalString:function(){var e=[],t=this.request.pathname();return"s3"!==this.serviceName&&"s3v4"!==this.signatureVersion&&(t=r.util.uriEscapePath(t)),e.push(this.request.method),e.push(t),e.push(this.request.search()),e.push(this.canonicalHeaders()+"\n"),e.push(this.signedHeaders()),e.push(this.hexEncodedBodyHash()),e.join("\n")},canonicalHeaders:function(){var e=[];r.util.each.call(this,this.request.headers,(function(t,n){e.push([t,n])})),e.sort((function(e,t){return e[0].toLowerCase()50&&delete o[i.shift()]),h},emptyCache:function(){o={},i=[]}}},{"../core":18}],70:[function(e,t,n){function r(e,t){this.currentState=t||null,this.states=e||{}}r.prototype.runTo=function(e,t,n,r){"function"==typeof e&&(r=n,n=t,t=e,e=null);var o=this,i=o.states[o.currentState];i.fn.call(n||o,r,(function(r){if(r){if(!i.fail)return t?t.call(n,r):null;o.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;o.currentState=i.accept}if(o.currentState===e)return t?t.call(n,r):null;o.runTo(e,t,n,r)}))},r.prototype.addState=function(e,t,n,r){return"function"==typeof t?(r=t,t=null,n=null):"function"==typeof n&&(r=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:r},this},t.exports=r},{}],71:[function(e,t,n){(function(n,r){(function(){var o,i={environment:"nodejs",engine:function(){if(i.isBrowser()&&"undefined"!=typeof navigator)return navigator.userAgent;var e=n.platform+"/"+n.version;return n.env.AWS_EXECUTION_ENV&&(e+=" exec-env/"+n.env.AWS_EXECUTION_ENV),e},userAgent:function(){var t=i.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+i.engine()),n},uriEscape:function(e){var t=encodeURIComponent(e);return t=(t=t.replace(/[^A-Za-z0-9_.~\-%]+/g,escape)).replace(/[*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))},uriEscapePath:function(e){var t=[];return i.arrayEach(e.split("/"),(function(e){t.push(i.uriEscape(e))})),t.join("/")},urlParse:function(e){return i.url.parse(e)},urlFormat:function(e){return i.url.format(e)},queryStringParse:function(e){return i.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=i.uriEscape,r=Object.keys(e).sort();return i.arrayEach(r,(function(r){var o=e[r],s=n(r),a=s+"=";if(Array.isArray(o)){var c=[];i.arrayEach(o,(function(e){c.push(n(e))})),a=s+"="+c.sort().join("&"+s+"=")}else null!=o&&(a=s+"="+n(o));t.push(a)})),t.join("&")},readFileSync:function(t){return i.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 encode number "+e));return null==e?e:i.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw i.error(new Error("Cannot base64 decode number "+e));return null==e?e:i.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof i.Buffer.from&&i.Buffer.from!==Uint8Array.from?i.Buffer.from(e,t):new i.Buffer(e,t)},alloc:function(e,t,n){if("number"!=typeof e)throw new Error("size passed to alloc must be a number.");if("function"==typeof i.Buffer.alloc)return i.Buffer.alloc(e,t,n);var r=new i.Buffer(e);return void 0!==t&&"function"==typeof r.fill&&r.fill(t,void 0,void 0,n),r},toStream:function(e){i.Buffer.isBuffer(e)||(e=i.buffer.toBuffer(e));var t=new i.stream.Readable,n=0;return t._read=function(r){if(n>=e.length)return t.push(null);var o=n+r;o>e.length&&(o=e.length),t.push(e.slice(n,o)),n=o},t},concat:function(e){var t,n,r=0,o=0;for(n=0;n>>8^t[255&(n^e.readUInt8(r))];return(-1^n)>>>0},hmac:function(e,t,n,r){return n||(n="binary"),"buffer"===n&&(n=void 0),r||(r="sha256"),"string"==typeof t&&(t=i.buffer.toBuffer(t)),i.crypto.lib.createHmac(r,e).update(t).digest(n)},md5:function(e,t,n){return i.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return i.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,r){var o=i.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=i.buffer.toBuffer(t));var s=i.arraySliceFn(t),a=i.Buffer.isBuffer(t);if(i.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),r&&"object"==typeof t&&"function"==typeof t.on&&!a)t.on("data",(function(e){o.update(e)})),t.on("error",(function(e){r(e)})),t.on("end",(function(){r(null,o.digest(n))}));else{if(!r||!s||a||"undefined"==typeof FileReader){i.isBrowser()&&"object"==typeof t&&!a&&(t=new i.Buffer(new Uint8Array(t)));var c=o.update(t).digest(n);return r&&r(null,c),c}var u=0,l=new FileReader;l.onerror=function(){r(new Error("Failed to read data."))},l.onload=function(){var e=new i.Buffer(new Uint8Array(l.result));o.update(e),u+=e.length,l._continueReading()},l._continueReading=function(){if(u>=t.size)r(null,o.digest(n));else{var e=u+524288;e>t.size&&(e=t.size),l.readAsArrayBuffer(s.call(t,u,e))}},l._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),o.config.isClockSkewed},applyClockOffset:function(e){e&&(o.config.systemClockOffset=e-(new Date).getTime())},extractRequestId:function(e){var t=e.httpResponse.headers["x-amz-request-id"]||e.httpResponse.headers["x-amzn-requestid"];!t&&e.data&&e.data.ResponseMetadata&&(t=e.data.ResponseMetadata.RequestId),t&&(e.requestId=t),e.error&&(e.error.requestId=t)},addPromises:function(e,t){var n=!1;void 0===t&&o&&o.config&&(t=o.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var r=0;r=500||429===r});o&&s.retryable&&(s.retryAfter=o),c(s)}}))}),c)};o.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,r=t.service.api.operations[n].output||{};r.payload&&e.data[r.payload]&&(e.data[r.payload]=e.data[r.payload].toString())},defer:function(e){"object"==typeof n&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof r?r(e):setTimeout(e,0)},getRequestPayloadShape:function(e){var t=e.service.api.operations;if(t){var n=(t||{})[e.operation];if(n&&n.input&&n.input.payload)return n.input.members[n.input.payload]}},getProfilesFromSharedConfig:function(e,t){var r={},o={};n.env[i.configOptInEnv]&&(o=e.loadFrom({isConfig:!0,filename:n.env[i.sharedConfigFileEnv]}));for(var s=e.loadFrom({filename:t||n.env[i.configOptInEnv]&&n.env[i.sharedCredentialsFileEnv]}),a=0,c=Object.keys(o);a0||r?i.toString():""},t.exports=s},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(e,t,n){t.exports={escapeAttribute:function(e){return e.replace(/&/g,"&").replace(/'/g,"'").replace(//g,">").replace(/"/g,""")}}},{}],75:[function(e,t,n){t.exports={escapeElement:function(e){return e.replace(/&/g,"&").replace(//g,">")}}},{}],76:[function(e,t,n){var r=e("./escape-attribute").escapeAttribute;function o(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}o.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},o.prototype.addChildNode=function(e){return this.children.push(e),this},o.prototype.removeAttribute=function(e){return delete this.attributes[e],this},o.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,o=0,i=Object.keys(n);o"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:o}},{"./escape-attribute":74}],77:[function(e,t,n){var r=e("./escape-element").escapeElement;function o(e){this.value=e}o.prototype.toString=function(){return r(""+this.value)},t.exports={XmlText:o}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=u(e),n=t[0],r=t[1];return 3*(n+r)/4-r},n.toByteArray=function(e){var t,n,r=u(e),s=r[0],a=r[1],c=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),l=0,p=a>0?s-4:s;for(n=0;n>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===a&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[l++]=255&t),1===a&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},n.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],s=16383,a=0,c=n-o;ac?c:a+s));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var o,i,s=[],a=t;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],79:[function(e,t,n){},{}],80:[function(e,t,o){(function(e){(function(){!function(i){"object"==typeof o&&o&&o.nodeType,"object"==typeof t&&t&&t.nodeType;var s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self;var a,c=2147483647,u=36,l=/^xn--/,p=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,h={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function m(e){throw RangeError(h[e])}function v(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function y(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+v((e=e.replace(d,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=g((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=g(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function C(e,t,n){var r=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;r+=u)e=f(e/35);return f(r+36*e/(e+38))}function T(e){var t,n,r,o,i,s,a,l,p,d,h,g=[],v=e.length,y=0,E=128,b=72;for((n=e.lastIndexOf("-"))<0&&(n=0),r=0;r=128&&m("not-basic"),g.push(e.charCodeAt(r));for(o=n>0?n+1:0;o=v&&m("invalid-input"),((l=(h=e.charCodeAt(o++))-48<10?h-22:h-65<26?h-65:h-97<26?h-97:u)>=u||l>f((c-y)/s))&&m("overflow"),y+=l*s,!(l<(p=a<=b?1:a>=b+26?26:a-b));a+=u)s>f(c/(d=u-p))&&m("overflow"),s*=d;b=C(y-i,t=g.length+1,0==i),f(y/t)>c-E&&m("overflow"),E+=f(y/t),y%=t,g.splice(y++,0,E)}return S(g)}function I(e){var t,n,r,o,i,s,a,l,p,d,h,v,y,S,T,I=[];for(v=(e=E(e)).length,t=128,n=0,i=72,s=0;s=t&&hf((c-n)/(y=r+1))&&m("overflow"),n+=(a-t)*y,t=a,s=0;sc&&m("overflow"),h==t){for(l=n,p=u;!(l<(d=p<=i?1:p>=i+26?26:p-i));p+=u)T=l-d,S=u-d,I.push(g(b(d+T%S,0))),l=f(T/S);I.push(g(b(l,0))),i=C(n,y,r==o),n=0,++r}++n,++t}return I.join("")}a={version:"1.3.2",ucs2:{decode:E,encode:S},decode:T,encode:I,toASCII:function(e){return y(e,(function(e){return p.test(e)?"xn--"+I(e):e}))},toUnicode:function(e){return y(e,(function(e){return l.test(e)?T(e.slice(4).toLowerCase()):e}))}},void 0===(r=function(){return a}.call(o,n,o,t))||(t.exports=r)}()}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(e,t,r){(function(t,n){(function(){"use strict";var n=e("base64-js"),o=e("ieee754"),i=e("isarray");function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;ia&&(n=a-c),i=n;i>=0;i--){for(var p=!0,d=0;do&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:u>223?3:u>191?2:1;if(o+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",r=0;r0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,r,o){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),a=Math.min(i,s),u=this.slice(r,o),l=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;oo)&&(n=o);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function P(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function x(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function M(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||M(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,i){return i||M(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||D(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function j(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"base64-js":78,buffer:81,ieee754:83,isarray:84}],82:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function o(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,a,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(s(n=this._events[e]))return!1;if(o(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),r=(u=n.slice()).length,c=0;c0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){if(!o(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,s,a;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(o(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],83:[function(e,t,n){n.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<>1,l=-7,p=n?o-1:0,d=n?-1:1,h=e[t+p];for(p+=d,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+e[t+p],p+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+p],p+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=u}return(h?-1:1)*s*Math.pow(2,i-r)},n.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?d/c:d*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=l?(a=0,s=l):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+h]=255&a,h+=f,a/=256,o-=8);for(s=s<0;e[n+h]=255&s,h+=f,s/=256,u-=8);e[n+h-f]|=128*g}},{}],84:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],85:[function(e,t,n){!function(e){"use strict";function t(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e,o){if(e===o)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(o))return!1;if(!0===t(e)){if(e.length!==o.length)return!1;for(var i=0;i":!0,"=":!0,"!":!0},q={" ":!0,"\t":!0,"\n":!0};function B(e){return e>="0"&&e<="9"||"-"===e}function j(){}j.prototype={tokenize:function(e){var t,n,r,o,i=[];for(this._current=0;this._current="a"&&o<="z"||o>="A"&&o<="Z"||"_"===o)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:u,value:n,start:t});else if(void 0!==U[e[this._current]])i.push({type:U[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(B(e[this._current]))r=this._consumeNumber(e),i.push(r);else if("["===e[this._current])r=this._consumeLBracket(e),i.push(r);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:l,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:M,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:M,value:s,start:t})}else if(void 0!==F[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==q[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:b,value:"&&",start:t})):i.push({type:y,value:"&",start:t});else{if("|"!==e[this._current]){var a=new Error("Unknown character:"+e[this._current]);throw a.name="LexerError",a}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:S,value:"||",start:t})):i.push({type:E,value:"|",start:t})}return i},_consumeUnquotedIdentifier:function(e){var t,n=this._current;for(this._current++;this._current="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t);)this._current++;return e.slice(n,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var n=e.length;'"'!==e[this._current]&&this._current"===n?"="===e[this._current]?(this._current++,{type:_,value:">=",start:t}):{type:T,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:C,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,r=e.length;"`"!==e[this._current]&&this._current=0)return!0;if(["true","false","null"].indexOf(e)>=0)return!0;if(!("-0123456789".indexOf(e[0])>=0))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var V={};function H(){}function W(e){this.runtime=e}function G(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[8]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,3]},{types:[1]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,3,4]}]},map:{_func:this._functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this._functionMax,_signature:[{types:[8,9]}]},merge:{_func:this._functionMerge,_signature:[{types:[4],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[3]},{types:[6]}]},sum:{_func:this._functionSum,_signature:[{types:[8]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[3]},{types:[6]}]},type:{_func:this._functionType,_signature:[{types:[1]}]},keys:{_func:this._functionKeys,_signature:[{types:[4]}]},values:{_func:this._functionValues,_signature:[{types:[4]}]},sort:{_func:this._functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[3]},{types:[6]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[9]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,3]}]},to_array:{_func:this._functionToArray,_signature:[{types:[1]}]},to_string:{_func:this._functionToString,_signature:[{types:[1]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[1]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[1],variadic:!0}]}}}V.EOF=0,V.UnquotedIdentifier=0,V.QuotedIdentifier=0,V.Rbracket=0,V.Rparen=0,V.Comma=0,V.Rbrace=0,V.Number=0,V.Current=0,V.Expref=0,V.Pipe=1,V.Or=2,V.And=3,V.EQ=5,V.GT=5,V.LT=5,V.GTE=5,V.LTE=5,V.NE=5,V.Flatten=9,V.Star=20,V.Filter=21,V.Dot=40,V.Not=45,V.Lbrace=50,V.Lbracket=55,V.Lparen=60,H.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==c){var n=this._lookaheadToken(0),r=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw r.name="ParserError",r}return t},_loadTokens:function(e){var t=(new j).tokenize(e);t.push({type:c,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),r=this._lookahead(0);e=0?this.expression(e):t===P?(this._match(P),this._parseMultiselectList()):t===D?(this._match(D),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(V[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===P)t=this.expression(e);else if(this._lookahead(0)===k)t=this.expression(e);else{if(this._lookahead(0)!==O){var n=this._lookaheadToken(0),r=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw r.name="ParserError",r}this._match(O),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==p;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===h&&(this._match(h),this._lookahead(0)===p))throw new Error("Unexpected token Rbracket")}return this._match(p),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,r=[],o=[u,l];;){if(e=this._lookaheadToken(0),o.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(f),n={type:"KeyValuePair",name:t,value:this.expression(0)},r.push(n),this._lookahead(0)===h)this._match(h);else if(this._lookahead(0)===g){this._match(g);break}}return{type:"MultiSelectHash",children:r}}},W.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,a,c,u,l,p,d,h,f;switch(e.type){case"Field":return null===i?null:n(i)?void 0===(p=i[e.name])?null:p:null;case"Subexpression":for(c=this.visit(e.children[0],i),f=1;f0)for(f=b;fN;f+=k)c.push(i[f]);return c;case"Projection":var O=this.visit(e.children[0],i);if(!t(O))return null;for(h=[],f=0;fl;break;case _:c=u>=l;break;case I:c=u=e&&(t=n<0?e-1:e),t}},G.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var r,o,i,s;if(n[n.length-1].variadic){if(t.length=0;r--)n+=t[r];return n}var o=e[0].slice(0);return o.reverse(),o},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],r=0;r=0},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return n(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],n=this._interpreter,r=e[0],o=e[1],i=0;i0){if(this._getTypeName(e[0][0])===s)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;r0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],r=1;ra?1:sc&&(c=n,t=o[u]);return t},_functionMinBy:function(e){for(var t,n,r=e[1],o=e[0],i=this.createKeyFunction(r,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>c&&(u=c);for(var l=0;l=0?(p=g.substr(0,m),d=g.substr(m+1)):(p=g,d=""),h=decodeURIComponent(p),f=decodeURIComponent(d),r(s,h)?o(s[h])?s[h].push(f):s[h]=[s[h],f]:s[h]=f}return s};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],88:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?i(s(e),(function(s){var a=encodeURIComponent(r(s))+n;return o(e[s])?i(e[s],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[s]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&c>a&&(c=a);for(var u=0;u=0?(l=f.substr(0,g),p=f.substr(g+1)):(l=f,p=""),d=decodeURIComponent(l),h=decodeURIComponent(p),r(i,d)?Array.isArray(i[d])?i[d].push(h):i[d]=[i[d],h]:i[d]=h}return i}},{}],91:[function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,o){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map((function(o){var i=encodeURIComponent(r(o))+n;return Array.isArray(e[o])?e[o].map((function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):o?encodeURIComponent(r(o))+n+encodeURIComponent(r(e)):""}},{}],92:[function(e,t,n){arguments[4][89][0].apply(n,arguments)},{"./decode":90,"./encode":91,dup:89}],93:[function(e,t,n){(function(t,r){(function(){var o=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function u(e,t){this._id=e,this._clearFn=t}n.setTimeout=function(){return new u(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new u(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n.setImmediate="function"==typeof t?t:function(e){var t=c++,r=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,o((function(){a[t]&&(r?e.apply(null,r):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof r?r:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":86,timers:93}],94:[function(e,t,n){var r=e("punycode");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=v,n.resolve=function(e,t){return v(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},n.format=function(e){return y(e)&&(e=v(e)),e instanceof o?e.format():o.prototype.format.call(e)},n.Url=o;var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(a),u=["%","/","?",";","#"].concat(c),l=["/","?","#"],p=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,h={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},m=e("querystring");function v(e,t,n){if(e&&E(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function y(e){return"string"==typeof e}function E(e){return"object"==typeof e&&null!==e}function S(e){return null===e}o.prototype.parse=function(e,t,n){if(!y(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e;o=o.trim();var s=i.exec(o);if(s){var a=(s=s[0]).toLowerCase();this.protocol=a,o=o.substr(s.length)}if(n||s||o.match(/^\/\/[^@\/]+@[^@\/]+/)){var v="//"===o.substr(0,2);!v||s&&f[s]||(o=o.substr(2),this.slashes=!0)}if(!f[s]&&(v||s&&!g[s])){for(var E,S,b=-1,C=0;C127?R+="x":R+=w[N];if(!R.match(p)){var O=_.slice(0,C),L=_.slice(C+1),D=w.match(d);D&&(O.push(D[1]),L.unshift(D[2])),L.length&&(o="/"+L.join(".")+o),this.hostname=O.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!I){var P=this.hostname.split("."),x=[];for(C=0;C0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),n.search=e.search,n.query=e.query,S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!p.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var h=p.slice(-1)[0],m=(n.host||e.host)&&("."===h||".."===h)||""===h,v=0,E=p.length;E>=0;E--)"."==(h=p[E])?p.splice(E,1):".."===h?(p.splice(E,1),v++):v&&(p.splice(E,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),m&&"/"!==p.join("/").substr(-1)&&p.push("");var b,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return d&&(n.hostname=n.host=C?"":p.length?p.shift():"",(b=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=b.shift(),n.host=n.hostname=b.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),S(n.pathname)&&S(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:80,querystring:89}],95:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],96:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],97:[function(e,t,r){(function(t,n){(function(){var o=/%[sdj%]/g;r.format=function(e){if(!v(e)){for(var t=[],n=0;n=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),c=r[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),f(t)?n.showHidden=t:t&&r._extend(n,t),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),l(n,e,n.depth)}function c(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function u(e,t){return e}function l(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var o=t.inspect(n,e);return v(o)||(o=l(e,o,n)),o}var i=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return m(t)?e.stylize(""+t,"number"):f(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),C(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(b(t))return e.stylize(Date.prototype.toString.call(t),"date");if(C(t))return p(t)}var u,S="",I=!1,_=["{","}"];return h(t)&&(I=!0,_=["[","]"]),T(t)&&(S=" [Function"+(t.name?": "+t.name:"")+"]"),E(t)&&(S=" "+RegExp.prototype.toString.call(t)),b(t)&&(S=" "+Date.prototype.toUTCString.call(t)),C(t)&&(S=" "+p(t)),0!==s.length||I&&0!=t.length?n<0?E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=I?function(e,t,n,r,o){for(var i=[],s=0,a=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,S,_)):_[0]+S+_[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,r,o,i){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),R(r,o)||(s="["+o+"]"),a||(e.seen.indexOf(c.value)<0?(a=g(n)?l(e,c.value,null):l(e,c.value,n-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),y(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function v(e){return"string"==typeof e}function y(e){return void 0===e}function E(e){return S(e)&&"[object RegExp]"===I(e)}function S(e){return"object"==typeof e&&null!==e}function b(e){return S(e)&&"[object Date]"===I(e)}function C(e){return S(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(y(i)&&(i=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!s[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var n=t.pid;s[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else s[e]=function(){};return s[e]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=h,r.isBoolean=f,r.isNull=g,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=v,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=y,r.isRegExp=E,r.isObject=S,r.isDate=b,r.isError=C,r.isFunction=T,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function w(){var e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){console.log("%s - %s",w(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!S(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this)}).call(this,e("_process"),void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":96,_process:86,inherits:95}],98:[function(e,t,n){var r=e("./v1"),o=e("./v4"),i=o;i.v1=r,i.v4=o,t.exports=i},{"./v1":101,"./v4":102}],99:[function(e,t,n){for(var r=[],o=0;o<256;++o)r[o]=(o+256).toString(16).substr(1);t.exports=function(e,t){var n=t||0,o=r;return[o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],"-",o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]],o[e[n++]]].join("")}},{}],100:[function(e,t,n){var r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(r){var o=new Uint8Array(16);t.exports=function(){return r(o),o}}else{var i=new Array(16);t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},{}],101:[function(e,t,n){var r,o,i=e("./lib/rng"),s=e("./lib/bytesToUuid"),a=0,c=0;t.exports=function(e,t,n){var u=t&&n||0,l=t||[],p=(e=e||{}).node||r,d=void 0!==e.clockseq?e.clockseq:o;if(null==p||null==d){var h=i();null==p&&(p=r=[1|h[0],h[1],h[2],h[3],h[4],h[5]]),null==d&&(d=o=16383&(h[6]<<8|h[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:c+1,m=f-a+(g-c)/1e4;if(m<0&&void 0===e.clockseq&&(d=d+1&16383),(m<0||f>a)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=f,c=g,o=d;var v=(1e4*(268435455&(f+=122192928e5))+g)%4294967296;l[u++]=v>>>24&255,l[u++]=v>>>16&255,l[u++]=v>>>8&255,l[u++]=255&v;var y=f/4294967296*1e4&268435455;l[u++]=y>>>8&255,l[u++]=255&y,l[u++]=y>>>24&15|16,l[u++]=y>>>16&255,l[u++]=d>>>8|128,l[u++]=255&d;for(var E=0;E<6;++E)l[u+E]=p[E];return t||s(l)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(e,t,n){var r=e("./lib/rng"),o=e("./lib/bytesToUuid");t.exports=function(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||o(s)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var r=e("./utils/LRU"),o=function(){function e(e){void 0===e&&(e=1e3),this.maxSize=e,this.cache=new r.LRUCache(e)}return Object.defineProperty(e.prototype,"size",{get:function(){return this.cache.length},enumerable:!0,configurable:!0}),e.prototype.put=function(t,n){var r="string"!=typeof t?e.getKeyString(t):t,o=this.populateValue(n);this.cache.put(r,o)},e.prototype.get=function(t){var n="string"!=typeof t?e.getKeyString(t):t,r=Date.now(),o=this.cache.get(n);if(o)for(var i=0;i{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.ClientMethods=t.makeEnum(["getAgentSnapshot","putAgentState","getAgentStates","getDialableCountryCodes","getRoutingProfileQueues","getAgentPermissions","getAgentConfiguration","updateAgentConfiguration","acceptContact","createOutboundContact","createTaskContact","clearContact","completeContact","destroyContact","rejectContact","notifyContactIssue","updateContactAttributes","createAdditionalConnection","destroyConnection","holdConnection","resumeConnection","toggleActiveConnections","conferenceConnections","sendClientLogs","sendDigits","sendSoftphoneCallReport","sendSoftphoneCallMetrics","getEndpoints","getNewAuthToken","createTransport","muteParticipant","unmuteParticipant"]),t.AgentAppClientMethods={GET_CONTACT:"AgentAppService.Lcms.getContact",DELETE_SPEAKER:"AgentAppService.VoiceId.deleteSpeaker",ENROLL_BY_SESSION:"AgentAppService.VoiceId.enrollBySession",EVALUATE_SESSION:"AgentAppService.VoiceId.evaluateSession",DESCRIBE_SPEAKER:"AgentAppService.VoiceId.describeSpeaker",OPT_OUT_SPEAKER:"AgentAppService.VoiceId.optOutSpeaker",UPDATE_VOICE_ID_DATA:"AgentAppService.Lcms.updateVoiceIdData",DESCRIBE_SESSION:"AgentAppService.VoiceId.describeSession",UPDATE_SESSION:"AgentAppService.VoiceId.updateSession",START_VOICE_ID_SESSION:"AgentAppService.Nasa.startVoiceIdSession",LIST_INTEGRATION_ASSOCIATIONS:"AgentAppService.Acs.listIntegrationAssociations",START_CONTACT_RECORDING:"AgentAppService.Acs.StartContactRecording",STOP_CONTACT_RECORDING:"AgentAppService.Acs.StopContactRecording",SUSPEND_CONTACT_RECORDING:"AgentAppService.Acs.SuspendContactRecording",RESUME_CONTACT_RECORDING:"AgentAppService.Acs.ResumeContactRecording"},t.MasterMethods=t.makeEnum(["becomeMaster","checkMaster"]),t.TaskTemplatesClientMethods=t.makeEnum(["listTaskTemplates","getTaskTemplate","createTemplatedTask","updateContact"]);var n=function(){};n.EMPTY_CALLBACKS={success:function(){},failure:function(){}},n.prototype.call=function(e,r,o){t.assertNotNull(e,"method");var i=r||{},s=o||n.EMPTY_CALLBACKS;this._callImpl(e,i,s)},n.prototype._callImpl=function(e,n,r){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){if(r&&r.failure){var o=t.sprintf("No such method exists on NULL client: %s",e);r.failure(new t.ValueError(o),{message:o})}};var o=function(e,r,o){n.call(this),this.conduit=e,this.requestEvent=r,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,t.hitch(this,this._handleResponse))};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._callImpl=function(e,n,r){var o=t.EventFactory.createRequest(this.requestEvent,e,n);this._requestIdCallbacksMap[o.requestId]=r,this.conduit.sendUpstream(o.event,o)},o.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},o.prototype._handleResponse=function(e){var t=this._getCallbacksForRequest(e.requestId);null!=t&&(e.err&&t.failure?t.failure(e.err,e.data):t.success&&t.success(e.data))};var i=function(e){o.call(this,e,t.EventType.API_REQUEST,t.EventType.API_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e){o.call(this,e,t.EventType.MASTER_REQUEST,t.EventType.MASTER_RESPONSE)};(s.prototype=Object.create(o.prototype)).constructor=s;var a=function(e,r,o){t.assertNotNull(e,"authCookieName"),t.assertNotNull(r,"authToken"),t.assertNotNull(o,"endpoint"),n.call(this),this.endpointUrl=t.getUrlWithProtocol(o),this.authToken=r,this.authCookieName=e};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype._callImpl=function(e,n,r){var o=this,i={};i[o.authCookieName]=o.authToken;var s={method:"post",body:JSON.stringify(n||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(i)}};t.fetch(o.endpointUrl,s).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))};var c=function(e,r,o){t.assertNotNull(e,"authToken"),t.assertNotNull(r,"region"),n.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=r,this.authToken=e;var i=t.getBaseUrl(),s=o||(i.includes(".awsapps.com")?i+"/connect/api":i+"/api"),a=new AWS.Endpoint(s);this.client=new AWS.Connect({endpoint:a})};(c.prototype=Object.create(n.prototype)).constructor=c,c.prototype._callImpl=function(e,n,r){var o=this,i=t.getLog();if(t.contains(this.client,e))n=this._translateParams(e,n),i.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](n).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(n,o){try{if(n){if(n.code===t.CTIExceptions.UNAUTHORIZED_EXCEPTION)r.authFailure();else if(!r.accessDenied||n.code!==t.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==n.statusCode){var s={};if(s.type=n.code,s.message=n.message,s.stack=[],n.stack)try{Array.isArray(n.stack)?s.stack=n.stack:"object"==typeof n.stack?s.stack=[JSON.stringify(n.stack)]:"string"==typeof n.stack&&(s.stack=n.stack.split("\n"))}catch{}r.failure(s,o)}else r.accessDenied();i.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(n)).sendInternalLogToServer()}else i.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),r.success(o)}catch(n){t.getLog().error("Failed to handle AWS API request for method %s",e).withException(n).sendInternalLogToServer()}}));else{var s=t.sprintf("No such method exists on AWS client: %s",e);r.failure(new t.ValueError(s),{message:s})}},c.prototype._requiresAuthenticationParam=function(e){return e!==t.ClientMethods.COMPLETE_CONTACT&&e!==t.ClientMethods.CLEAR_CONTACT&&e!==t.ClientMethods.REJECT_CONTACT&&e!==t.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,n){switch(e){case t.ClientMethods.UPDATE_AGENT_CONFIGURATION:n.configuration=this._translateAgentConfiguration(n.configuration);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:n.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(n.softphoneStreamStatistics);break;case t.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:n.report=this._translateSoftphoneCallReport(n.report)}return this._requiresAuthenticationParam(e)&&(n.authentication={authToken:this.authToken}),n},c.prototype._translateAgentConfiguration=function(e){return{name:e.name,softphoneEnabled:e.softphoneEnabled,softphoneAutoAccept:e.softphoneAutoAccept,extension:e.extension,routingProfile:this._translateRoutingProfile(e.routingProfile),agentPreferences:e.agentPreferences}},c.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},c.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},c.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach((function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)})),e},c.prototype._translateSoftphoneCallReport=function(e){return"handshakingTimeMillis"in e&&(e.handshakeTimeMillis=e.handshakingTimeMillis,delete e.handshakingTimeMillis),"preTalkingTimeMillis"in e&&(e.preTalkTimeMillis=e.preTalkingTimeMillis,delete e.preTalkingTimeMillis),"handshakingFailure"in e&&(e.handshakeFailure=e.handshakingFailure,delete e.handshakingFailure),"talkingTimeMillis"in e&&(e.talkTimeMillis=e.talkingTimeMillis,delete e.talkingTimeMillis),e.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics),e};var u=function(e){if(t.assertNotNull(e,"endpoint"),n.call(this),e.includes("/task-templates"))this.endpointUrl=t.getUrlWithProtocol(e);else{var r=new AWS.Endpoint(e),o=e.includes(".awsapps.com")?"/connect":"";this.endpointUrl=t.getUrlWithProtocol(`${r.host}${o}/task-templates/api/ccp`)}};(u.prototype=Object.create(n.prototype)).constructor=u,u.prototype._callImpl=function(e,n,r){t.assertNotNull(e,"method"),t.assertNotNull(n,"params");var o={credentials:"include",method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","x-csrf-token":"csrf"}},i=n.instanceId,s=this.endpointUrl,a=t.TaskTemplatesClientMethods;switch(e){case a.LIST_TASK_TEMPLATES:if(s+=`/proxy/instance/${i}/task/template`,n.queryParams){const e=new URLSearchParams(n.queryParams).toString();e&&(s+=`?${e}`)}break;case a.GET_TASK_TEMPLATE:t.assertNotNull(n.templateParams,"params.templateParams");const r=t.assertNotNull(n.templateParams.id,"params.templateParams.id"),c=n.templateParams.version;s+=`/proxy/instance/${i}/task/template/${r}`,c&&(s+=`?snapshotVersion=${c}`);break;case a.CREATE_TEMPLATED_TASK:s+=`/${e}`,o.body=JSON.stringify(n),o.method="PUT";break;case a.UPDATE_CONTACT:s+=`/${e}`,o.body=JSON.stringify(n),o.method="POST"}t.fetch(s,o).then((function(e){r.success(e)})).catch((function(e){const t=e.body.getReader();let n="";const o=new TextDecoder;t.read().then((function i({done:s,value:a}){if(s){var c=JSON.parse(n);return c.status=e.status,void r.failure(c)}return n+=o.decode(a),t.read().then(i)}))}))},t.ClientBase=n,t.NullClient=r,t.UpstreamConduitClient=i,t.UpstreamConduitMasterClient=s,t.AWSClient=c,t.AgentAppClient=a,t.TaskTemplatesClient=u}()},895:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.core={},t.core.initialized=!1,t.version="2.2.0",t.DEFAULT_BATCH_SIZE=500;var n="Amazon Connect CCP",r="https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}",o="06919f4fd8ed324e",i="/auth/authorize",s="/connect/auth/authorize",a="IframeRefreshAttempts",c="IframeInitializationSuccess";function u(e){var t=e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gi);return t.length?t[0]:""}t.numberOfConnectedCCPs=0,t.numberOfConnectedCCPsInThisTab=0,t.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION=3,t.core.MAX_CTI_AUTH_RETRY_COUNT=10,t.core.ctiAuthRetryCount=0,t.core.authorizeTimeoutId=null,t.core.ctiTimeoutId=null,t.SessionStorageKeys=t.makeEnum(["tab_id","authorize_retry_count"]),t.core.checkNotInitialized=function(){t.core.initialized&&t.getLog().warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer()},t.core.init=function(e){t.core.eventBus=new t.EventBus,t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.initClient(e),t.core.initAgentAppClient(e),t.core.initTaskTemplatesClient(e),t.core.initialized=!0},t.core.initClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.region,"params.region"),o=e.endpoint||null;t.core.client=new t.AWSClient(n,r,o)},t.core.initAgentAppClient=function(e){t.assertNotNull(e,"params");var n=t.assertNotNull(e.authToken,"params.authToken"),r=t.assertNotNull(e.authCookieName,"params.authCookieName"),o=t.assertNotNull(e.agentAppEndpoint,"params.agentAppEndpoint");t.core.agentAppClient=new t.AgentAppClient(r,n,o)},t.core.initTaskTemplatesClient=function(e){t.assertNotNull(e,"params");var n=e.taskTemplatesEndpoint||e.endpoint;t.assertNotNull(n,"taskTemplatesEndpoint"),t.core.taskTemplatesClient=new t.TaskTemplatesClient(n)},t.core.terminate=function(){t.core.client=new t.NullClient,t.core.agentAppClient=new t.NullClient,t.core.taskTemplatesClient=new t.NullClient,t.core.masterClient=new t.NullClient;var e=t.core.getEventBus();e&&e.unsubscribeAll(),t.core.bus=new t.EventBus,t.core.agentDataProvider=null,t.core.softphoneManager=null,t.core.upstream=null,t.core.keepaliveManager=null,t.agent.initialized=!1,t.core.initialized=!1},t.core.softphoneUserMediaStream=null,t.core.getSoftphoneUserMediaStream=function(){return t.core.softphoneUserMediaStream},t.core.setSoftphoneUserMediaStream=function(e){t.core.softphoneUserMediaStream=e},t.core.initRingtoneEngines=function(e){t.assertNotNull(e,"params");var n=function(e){t.assertNotNull(e,"ringtoneSettings"),t.assertNotNull(e.voice,"ringtoneSettings.voice"),t.assertTrue(e.voice.ringtoneUrl||e.voice.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"),t.assertNotNull(e.queue_callback,"ringtoneSettings.queue_callback"),t.assertTrue(e.queue_callback.ringtoneUrl||e.queue_callback.disabled,"ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"),t.core.ringtoneEngines={},t.agent((function(n){n.onRefresh((function(){t.ifMaster(t.MasterTopics.RINGTONE,(function(){e.voice.disabled||t.core.ringtoneEngines.voice||(t.core.ringtoneEngines.voice=new t.VoiceRingtoneEngine(e.voice),t.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer()),e.chat.disabled||t.core.ringtoneEngines.chat||(t.core.ringtoneEngines.chat=new t.ChatRingtoneEngine(e.chat),t.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer()),e.task.disabled||t.core.ringtoneEngines.task||(t.core.ringtoneEngines.task=new t.TaskRingtoneEngine(e.task),t.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer()),e.queue_callback.disabled||t.core.ringtoneEngines.queue_callback||(t.core.ringtoneEngines.queue_callback=new t.QueueCallbackRingtoneEngine(e.queue_callback),t.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer())}))}))})),l()},r=function(e,n){e.ringtone=e.ringtone||{},e.ringtone.voice=e.ringtone.voice||{},e.ringtone.queue_callback=e.ringtone.queue_callback||{},e.ringtone.chat=e.ringtone.chat||{disabled:!0},e.ringtone.task=e.ringtone.task||{disabled:!0},n.softphone&&(n.softphone.disableRingtone&&(e.ringtone.voice.disabled=!0,e.ringtone.queue_callback.disabled=!0),n.softphone.ringtoneUrl&&(e.ringtone.voice.ringtoneUrl=n.softphone.ringtoneUrl,e.ringtone.queue_callback.ringtoneUrl=n.softphone.ringtoneUrl)),n.chat&&(n.chat.disableRingtone&&(e.ringtone.chat.disabled=!0),n.chat.ringtoneUrl&&(e.ringtone.chat.ringtoneUrl=n.chat.ringtoneUrl)),n.ringtone&&(e.ringtone.voice=t.merge(e.ringtone.voice,n.ringtone.voice||{}),e.ringtone.queue_callback=t.merge(e.ringtone.queue_callback,n.ringtone.voice||{}),e.ringtone.chat=t.merge(e.ringtone.chat,n.ringtone.chat||{}))};r(e,e),t.isFramed()?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(t){this.unsubscribe(),r(e,t),n(e.ringtone)})):n(e.ringtone)};var l=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_RINGER_DEVICE,p)},p=function(e){if(0!==t.keys(t.core.ringtoneEngines).length&&e&&e.deviceId){var n=e.deviceId;for(var r in t.core.ringtoneEngines)t.core.ringtoneEngines[r].setOutputDevice(n);t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.RINGER_DEVICE_CHANGED,data:{deviceId:n}})}};t.core.initSoftphoneManager=function(e){t.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer();var n=e||{},r=function(e){var r=t.merge(n.softphone||{},e);t.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(),t.agent((function(e){e.getChannelConcurrency(t.ChannelType.VOICE)&&e.onRefresh((function(){var n=this;t.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(),t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(),!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),n.unsubscribe())}))}))}))};function o(e){var r=t.merge(n.softphone||{},e);t.core.softphoneParams=r,t.isFirefoxBrowser()&&(t.core.getUpstream().onUpstream(t.EventType.MASTER_RESPONSE,(function(e){if(e.data&&e.data.topic===t.MasterTopics.SOFTPHONE&&e.data.takeOver&&e.data.masterId!==t.core.portStreamId){t.core.softphoneManager&&(t.core.softphoneManager.onInitContactSub.unsubscribe(),delete t.core.softphoneManager);var n=t.core.getSoftphoneUserMediaStream();n&&(n.getTracks().forEach((function(e){e.stop()})),t.core.setSoftphoneUserMediaStream(null))}})),t.core.getEventBus().subscribe(t.ConnectionEvents.READY_TO_START_SESSION,(function(){t.ifMaster(t.MasterTopics.SOFTPHONE,(function(){t.core.softphoneManager&&t.core.softphoneManager.startSession()}),(function(){t.becomeMaster(t.MasterTopics.SOFTPHONE,(function(){t.agent((function(e){!t.core.softphoneManager&&e.isSoftphoneEnabled()&&(t.becomeMaster(t.MasterTopics.SEND_LOGS),t.core.softphoneManager=new t.SoftphoneManager(r),t.core.softphoneManager.startSession())}))}))}))})),t.contact((function(e){t.agent((function(n){e.onRefresh((function(e){if(t.hasOtherConnectedCCPs()&&"visible"===document.visibilityState&&(e.getStatus().type===t.ContactStatusType.CONNECTING||e.getStatus().type===t.ContactStatusType.INCOMING)){var r=e.isSoftphoneCall()&&!e.isInbound(),o=e.isSoftphoneCall()&&n.getConfiguration().softphoneAutoAccept,i=e.getType()===t.ContactType.QUEUE_CALLBACK;(r||o||i)&&t.core.triggerReadyToStartSessionEvent()}}))}))})))}t.isFramed()&&!n.allowFramedSoftphone?t.core.getEventBus().subscribe(t.EventType.CONFIGURE,(function(e){t.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(),e.softphone&&e.softphone.allowFramedSoftphone&&(this.unsubscribe(),r(e.softphone)),o(e.softphone)})):(r(n),o(n)),t.agent((function(e){e.isSoftphoneEnabled()&&e.getChannelConcurrency(t.ChannelType.VOICE)&&t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.MUTE})}))},t.core.triggerReadyToStartSessionEvent=function(){var e=t.core.softphoneParams&&t.core.softphoneParams.allowFramedSoftphone;t.isCCP()?e?t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):t.isFramed()?t.core.getUpstream().sendDownstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION):e?t.core.getUpstream().sendUpstream(t.ConnectionEvents.READY_TO_START_SESSION):t.core.getEventBus().trigger(t.ConnectionEvents.READY_TO_START_SESSION)},t.core.initPageOptions=function(e){if(t.assertNotNull(e,"params"),t.isFramed()){var n=t.core.getEventBus();n.subscribe(t.EventType.CONFIGURE,(function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.CONFIGURE,data:e})})),n.subscribe(t.EventType.MEDIA_DEVICE_REQUEST,(function(){function e(e){t.core.getUpstream().sendDownstream(t.EventType.MEDIA_DEVICE_RESPONSE,e)}navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})).catch((function(t){e({error:t.message})})):e({error:"No navigator or navigator.mediaDevices object found"})}))}},t.core.getFrameMediaDevices=function(e){var n=null,r=e||1e3,o=new Promise((function(e,t){setTimeout((function(){t(new Error("Timeout exceeded"))}),r)})),i=new Promise((function(e,r){if(t.isFramed()||t.isCCP())navigator&&navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(t){devices=t||[],devices=devices.map((function(e){return e.toJSON()})),e(devices)})):r(new Error("No navigator or navigator.mediaDevices object found"));else{var o=t.core.getEventBus();n=o.subscribe(t.EventType.MEDIA_DEVICE_RESPONSE,(function(t){t.error?r(new Error(t.error)):e(t)})),t.core.getUpstream().sendUpstream(t.EventType.MEDIA_DEVICE_REQUEST)}}));return Promise.race([i,o]).finally((function(){n&&n.unsubscribe()}))},t.core.authorize=function(e){var n=e;return n||(n=t.core.isLegacyDomain()?s:i),t.fetch(n,{credentials:"include"},2e3,5)},t.core.verifyDomainAccess=function(e,n){if(t.getLog().warn("This API will be deprecated in the next major version release"),!t.isFramed())return Promise.resolve();var r={headers:{"X-Amz-Bearer":e}},o=null;return o=n||(t.core.isLegacyDomain()?"/connect/whitelisted-origins":"/whitelisted-origins"),t.fetch(o,r,2e3,5).then((function(e){var t=u(window.document.referrer);return e.whitelistedOrigins.some((function(e){return t===u(e)}))?Promise.resolve():Promise.reject()}))},t.core.isLegacyDomain=function(e){return(e=e||window.location.href).includes(".awsapps.com")},t.core.initSharedWorker=function(n){if(t.core.checkNotInitialized(),!t.core.initialized){t.assertNotNull(n,"params");var r=t.assertNotNull(n.sharedWorkerUrl,"params.sharedWorkerUrl"),o=t.assertNotNull(n.authToken,"params.authToken"),a=t.assertNotNull(n.refreshToken,"params.refreshToken"),c=t.assertNotNull(n.authTokenExpiration,"params.authTokenExpiration"),u=t.assertNotNull(n.region,"params.region"),l=n.endpoint||null,p=n.authorizeEndpoint;p||(p=t.core.isLegacyDomain()?s:i);var d=n.agentAppEndpoint||null,g=n.taskTemplatesEndpoint||null,m=n.authCookieName||null;try{t.core.eventBus=new t.EventBus({logEvents:!0}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(n);var v=new SharedWorker(r,"ConnectSharedWorker"),y=new t.Conduit("ConnectSharedWorkerConduit",new t.PortStream(v.port),new t.WindowIOStream(window,parent));t.core.upstream=y,t.core.webSocketProvider=new h,e.onunload=function(){y.sendUpstream(t.EventType.CLOSE),v.port.close()},t.getLog().scheduleUpstreamLogPush(y),t.getLog().scheduleDownstreamClientSideLogsPush(),y.onAllUpstream(t.core.getEventBus().bridge()),y.onAllUpstream(y.passDownstream()),t.isFramed()&&(y.onAllDownstream(t.core.getEventBus().bridge()),y.onAllDownstream(y.passUpstream())),y.sendUpstream(t.EventType.CONFIGURE,{authToken:o,authTokenExpiration:c,endpoint:l,refreshToken:a,region:u,authorizeEndpoint:p,agentAppEndpoint:d,taskTemplatesEndpoint:g,authCookieName:m,longPollingOptions:n.longPollingOptions||void 0}),y.onUpstream(t.EventType.ACKNOWLEDGE,(function(e){t.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(),t.core.initialized=!0,t.core._setTabId(),t.core.portStreamId=e.id,this.unsubscribe()})),y.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),y.onUpstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))})),y.onDownstream(t.EventType.SERVER_BOUND_INTERNAL_LOG,(function(e){t.isFramed()&&Array.isArray(e)&&e.forEach((function(e){t.getLog().sendInternalLogEntryToServer(t.LogEntry.fromObject(e))}))})),y.onDownstream(t.EventType.LOG,(function(e){t.isFramed()&&e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.onAuthFail(t.hitch(t.core,t.core._handleAuthFail,n.loginEndpoint||null,p)),t.core.onAuthorizeSuccess(t.hitch(t.core,t.core._handleAuthorizeSuccess)),t.getLog().info("User Agent: "+navigator.userAgent).sendInternalLogToServer(),t.getLog().info("isCCPv2: "+!0).sendInternalLogToServer(),t.getLog().info("isFramed: "+t.isFramed()).sendInternalLogToServer(),t.core.upstream.onDownstream(t.EventType.OUTER_CONTEXT_INFO,(function(e){var n=e.streamsVersion;t.getLog().info("StreamsJS Version: "+n).sendInternalLogToServer()})),y.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.getLog().info("Number of connected CCPs updated: "+e.length).sendInternalLogToServer(),t.numberOfConnectedCCPs=e.length,e[t.core.tabId]&&!isNaN(e[t.core.tabId].length)&&t.numberOfConnectedCCPsInThisTab!==e[t.core.tabId].length&&(t.numberOfConnectedCCPsInThisTab=e[t.core.tabId].length,t.numberOfConnectedCCPsInThisTab>1&&t.getLog().warn("There are "+t.numberOfConnectedCCPsInThisTab+" connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(),t.publishMetric({name:"ConnectedCCPSingleTabCount",data:{count:t.numberOfConnectedCCPsInThisTab}})),e.tabId&&e.streamsTabsAcrossBrowser&&t.ifMaster(t.MasterTopics.METRICS,(()=>t.agent((()=>t.publishMetric({name:"CCPTabsAcrossBrowserCount",data:{tabId:e.tabId,count:e.streamsTabsAcrossBrowser}})))))})),t.core.client=new t.UpstreamConduitClient(y),t.core.masterClient=new t.UpstreamConduitMasterClient(y),t.core.getEventBus().subscribe(t.EventType.TERMINATE,y.passUpstream()),t.core.getEventBus().subscribe(t.EventType.TERMINATED,(function(){window.location.reload(!0)})),v.port.start(),y.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.agent((function(){(new t.VoiceId).getDomainId().then((function(e){t.getLog().info("voiceId domainId successfully fetched at agent initialization: "+e).sendInternalLogToServer()})).catch((function(e){t.getLog().info("voiceId domainId not fetched at agent initialization").withObject({err:e}).sendInternalLogToServer()}))})),t.core.getNotificationManager().requestPermission()}catch(e){t.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer()}}},t.core._setTabId=function(){try{t.core.tabId=window.sessionStorage.getItem(t.SessionStorageKeys.TAB_ID),t.core.tabId||(t.core.tabId=t.randomId(),window.sessionStorage.setItem(t.SessionStorageKeys.TAB_ID,t.core.tabId)),t.core.upstream.sendUpstream(t.EventType.TAB_ID,{tabId:t.core.tabId})}catch(e){t.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer()}},t.core.initCCP=function(n,i){if(t.core.checkNotInitialized(),!t.core.initialized){t.getLog().info("Iframe initialization started").sendInternalLogToServer();var s=Date.now();try{if(t.core._getCCPIframe())return void t.getLog().error("Attempted to call initCCP when an iframe generated by initCCP already exists").sendInternalLogToServer()}catch(e){t.getLog().error("Error while checking if initCCP has already been called").withException(e).sendInternalLogToServer()}var u={};"string"==typeof i?u.ccpUrl=i:u=i,t.assertNotNull(n,"containerDiv"),t.assertNotNull(u.ccpUrl,"params.ccpUrl");var l=t.core._createCCPIframe(n,u);t.core.eventBus=new t.EventBus({logEvents:!1}),t.core.agentDataProvider=new f(t.core.getEventBus()),t.core.mediaFactory=new t.MediaFactory(u);var p=new t.IFrameConduit(u.ccpUrl,window,l);t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(l,p),t.core.upstream=p,t.core.webSocketProvider=new h,p.onAllUpstream(t.core.getEventBus().bridge()),t.core.keepaliveManager=new d(p,t.core.getEventBus(),u.ccpSynTimeout||1e3,u.ccpAckTimeout||3e3),t.core.iframeRefreshTimeout=null,t.core.ccpLoadTimeoutInstance=e.setTimeout((function(){t.core.ccpLoadTimeoutInstance=null,t.core.getEventBus().trigger(t.EventType.ACK_TIMEOUT)}),u.ccpLoadTimeout||5e3),t.getLog().scheduleUpstreamOuterContextCCPLogsPush(p),t.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(p),p.onUpstream(t.EventType.ACKNOWLEDGE,(function(n){if(t.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(),t.core.client=new t.UpstreamConduitClient(p),t.core.masterClient=new t.UpstreamConduitMasterClient(p),t.core.portStreamId=n.id,(u.softphone||u.chat||u.pageOptions||u.shouldAddNamespaceToLogs)&&p.sendUpstream(t.EventType.CONFIGURE,{softphone:u.softphone,chat:u.chat,pageOptions:u.pageOptions,shouldAddNamespaceToLogs:u.shouldAddNamespaceToLogs}),t.core.ccpLoadTimeoutInstance&&(e.clearTimeout(t.core.ccpLoadTimeoutInstance),t.core.ccpLoadTimeoutInstance=null),p.sendUpstream(t.EventType.OUTER_CONTEXT_INFO,{streamsVersion:t.version}),t.core.keepaliveManager.start(),this.unsubscribe(),t.core.initialized=!0,t.core.getEventBus().trigger(t.EventType.INIT),s){var r=Date.now()-s,o=t.core.iframeRefreshAttempt||0;t.getLog().info("Iframe initialization succeeded").sendInternalLogToServer(),t.getLog().info(`Iframe initialization time ${r}`).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${o}`).sendInternalLogToServer(),setTimeout((()=>{t.publishMetric({name:a,data:{count:o}}),t.publishMetric({name:c,data:{count:1}}),t.publishMetric({name:"IframeInitializationTime",data:{count:r}}),s=null}),1e3)}})),p.onUpstream(t.EventType.LOG,(function(e){e.loggerId!==t.getLog().getLoggerId()&&t.getLog().addLogEntry(t.LogEntry.fromObject(e))})),t.core.getEventBus().subscribe(t.EventType.ACK_TIMEOUT,(function(){if(!1!==u.loginPopup)try{var i=function(n){var i="https://lily.us-east-1.amazonaws.com/taw/auth/code";return t.assertNotNull(i),n.loginUrl?n.loginUrl:n.alias?(log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."),r.replace("{alias}",n.alias).replace("{client_id}",o).replace("{redirect}",e.encodeURIComponent(i))):n.ccpUrl}(u);t.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(),u.loginUrl&&t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),t.core.loginWindow=t.core.getPopupManager().open(i,t.MasterTopics.LOGIN_POPUP,u.loginOptions)}catch(e){t.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer()}if(null==t.core.iframeRefreshTimeout)try{p.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=null,t.core.getPopupManager().clear(t.MasterTopics.LOGIN_POPUP),(u.loginPopupAutoClose||u.loginOptions&&u.loginOptions.autoClose)&&t.core.loginWindow&&(t.core.loginWindow.close(),t.core.loginWindow=null)})),t.core._refreshIframeOnTimeout(u,n)}catch(e){t.getLog().error("Error occurred while refreshing iframe").withException(e).sendInternalLogToServer()}})),u.onViewContact&&t.core.onViewContact(u.onViewContact),p.onUpstream(t.EventType.UPDATE_CONNECTED_CCPS,(function(e){t.numberOfConnectedCCPs=e.length})),p.onUpstream(t.VoiceIdEvents.UPDATE_DOMAIN_ID,(function(e){e&&e.domainId&&(t.core.voiceIdDomainId=e.domainId)})),t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,(function(){if(s){var e=t.core.iframeRefreshAttempt-1;t.getLog().info("Iframe initialization failed").sendInternalLogToServer(),t.getLog().info("Time after iframe initialization started "+(Date.now()-s)).sendInternalLogToServer(),t.getLog().info(`Iframe refresh attempts ${e}`).sendInternalLogToServer(),t.publishMetric({name:a,data:{count:e}}),t.publishMetric({name:c,data:{count:0}}),s=null}})),t.core.softphoneParams=u.softphone}},t.core.onIframeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.IFRAME_RETRIES_EXHAUSTED,e)},t.core._refreshIframeOnTimeout=function(n,r){t.assertNotNull(n,"initCCPParams"),t.assertNotNull(r,"containerDiv");var o=(n.disasterRecoveryOn?1e4:5e3)+AWS.util.calculateRetryDelay(t.core.iframeRefreshAttempt||0,{base:2e3});e.clearTimeout(t.core.iframeRefreshTimeout),t.core.iframeRefreshTimeout=e.setTimeout((function(){if(t.core.iframeRefreshAttempt=(t.core.iframeRefreshAttempt||0)+1,t.core.iframeRefreshAttempt<=6){try{var o=t.core._getCCPIframe();o&&o.parentNode.removeChild(o);var i=t.core._createCCPIframe(r,n);t.core.upstream.upstream.output=i.contentWindow,t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(i,t.core.upstream)}catch(e){t.getLog().error("Error while checking for, and recreating, the CCP IFrame").withException(e).sendInternalLogToServer()}t.core._refreshIframeOnTimeout(n,r)}else t.core.getEventBus().trigger(t.EventType.IFRAME_RETRIES_EXHAUSTED),e.clearTimeout(t.core.iframeRefreshTimeout)}),o)},t.core._getCCPIframe=function(){for(var e of window.document.getElementsByTagName("iframe"))if(e.name===n)return e;return null},t.core._createCCPIframe=function(e,r){t.assertNotNull(r,"initCCPParams"),t.assertNotNull(e,"containerDiv");var o=document.createElement("iframe");return o.src=r.ccpUrl,o.allow="microphone; autoplay",o.style=r.style||"width: 100%; height: 100%",o.title=r.iframeTitle||n,o.name=n,e.appendChild(o),o},t.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime=function(e,n){t.assertNotNull(e,"iframe"),t.assertNotNull(n,"conduit"),setTimeout((function(){var r={display:window.getComputedStyle(e,null).display,offsetWidth:e.offsetWidth,offsetHeight:e.offsetHeight,clientRectsLength:e.getClientRects().length};n.sendUpstream(t.EventType.IFRAME_STYLE,r)}),1e4)};var d=function(e,t,n,r){this.conduit=e,this.eventBus=t,this.synTimeout=n,this.ackTimeout=r,this.ackTimer=null,this.synTimer=null,this.ackSub=null};d.prototype.start=function(){var n=this;this.conduit.sendUpstream(t.EventType.SYNCHRONIZE),this.ackSub=this.conduit.onUpstream(t.EventType.ACKNOWLEDGE,(function(){this.unsubscribe(),e.clearTimeout(n.ackTimer),n._deferStart()})),this.ackTimer=e.setTimeout((function(){n.ackSub.unsubscribe(),n.eventBus.trigger(t.EventType.ACK_TIMEOUT),n._deferStart()}),this.ackTimeout)},d.prototype._deferStart=function(){this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout)},d.prototype.deferStart=function(){null==this.synTimer&&(this.synTimer=e.setTimeout(t.hitch(this,this.start),this.synTimeout))};var h=function(){var e={initFailure:new Set,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},n=function(e,t){e.forEach((function(e){e(t)}))};t.core.getUpstream().onUpstream(t.WebSocketEvents.INIT_FAILURE,(function(){n(e.initFailure)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_OPEN,(function(t){n(e.connectionOpen,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_CLOSE,(function(t){n(e.connectionClose,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_GAIN,(function(){n(e.connectionGain)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.CONNECTION_LOST,(function(t){n(e.connectionLost,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,(function(t){n(e.subscriptionUpdate,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,(function(t){n(e.subscriptionFailure,t)})),t.core.getUpstream().onUpstream(t.WebSocketEvents.ALL_MESSAGE,(function(t){n(e.allMessage,t),e.topic.has(t.topic)&&n(e.topic.get(t.topic),t)})),this.sendMessage=function(e){t.core.getUpstream().sendUpstream(t.WebSocketEvents.SEND,e)},this.onInitFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.initFailure.add(n),function(){return e.initFailure.delete(n)}},this.onConnectionOpen=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionOpen.add(n),function(){return e.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionClose.add(n),function(){return e.connectionClose.delete(n)}},this.onConnectionGain=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionGain.add(n),function(){return e.connectionGain.delete(n)}},this.onConnectionLost=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.connectionLost.add(n),function(){return e.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionUpdate.add(n),function(){return e.subscriptionUpdate.delete(n)}},this.onSubscriptionFailure=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.subscriptionFailure.add(n),function(){return e.subscriptionFailure.delete(n)}},this.subscribeTopics=function(e){t.assertNotNull(e,"topics"),t.assertTrue(t.isArray(e),"topics must be a array"),t.core.getUpstream().sendUpstream(t.WebSocketEvents.SUBSCRIBE,e)},this.onMessage=function(n,r){return t.assertNotNull(n,"topicName"),t.assertTrue(t.isFunction(r),"method must be a function"),e.topic.has(n)?e.topic.get(n).add(r):e.topic.set(n,new Set([r])),function(){return e.topic.get(n).delete(r)}},this.onAllMessage=function(n){return t.assertTrue(t.isFunction(n),"method must be a function"),e.allMessage.add(n),function(){return e.allMessage.delete(n)}}},f=function(e){this.bus=e,this.bus.subscribe(t.AgentEvents.UPDATE,t.hitch(this,this.updateAgentData))};f.prototype.updateAgentData=function(e){var n=this.agentData;this.agentData=e,null==n&&(t.agent.initialized=!0,this.bus.trigger(t.AgentEvents.INIT,new t.Agent)),this.bus.trigger(t.AgentEvents.REFRESH,new t.Agent),this._fireAgentUpdateEvents(n)},f.prototype.getAgentData=function(){if(null==this.agentData)throw new t.StateError("No agent data is available yet!");return this.agentData},f.prototype.getContactData=function(e){var n=this.getAgentData(),r=t.find(n.snapshot.contacts,(function(t){return t.contactId===e}));if(null==r)throw new t.StateError("Contact %s no longer exists.",e);return r},f.prototype.getConnectionData=function(e,n){var r=this.getContactData(e),o=t.find(r.connections,(function(e){return e.connectionId===n}));if(null==o)throw new t.StateError("Connection %s for contact %s no longer exists.",n,e);return o},f.prototype.getInstanceId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]},f.prototype.getAWSAccountId=function(){return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]},f.prototype._diffContacts=function(e){var n={added:{},removed:{},common:{},oldMap:t.index(null==e?[]:e.snapshot.contacts,(function(e){return e.contactId})),newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))};return t.keys(n.oldMap).forEach((function(e){t.contains(n.newMap,e)?n.common[e]=n.newMap[e]:n.removed[e]=n.oldMap[e]})),t.keys(n.newMap).forEach((function(e){t.contains(n.oldMap,e)||(n.added[e]=n.newMap[e])})),n},f.prototype._fireAgentUpdateEvents=function(e){var n=this,r=null,o=null==e?t.AgentAvailStates.INIT:e.snapshot.state.name,i=this.agentData.snapshot.state.name,s=null==e?t.AgentStateType.INIT:e.snapshot.state.type,a=this.agentData.snapshot.state.type;s!==a&&t.core.getAgentRoutingEventGraph().getAssociations(this,s,a).forEach((function(e){n.bus.trigger(e,new t.Agent)})),o!==i&&(this.bus.trigger(t.AgentEvents.STATE_CHANGE,{agent:new t.Agent,oldState:o,newState:i}),t.core.getAgentStateEventGraph().getAssociations(this,o,i).forEach((function(e){n.bus.trigger(e,new t.Agent)})));var c=e&&e.snapshot.nextState?e.snapshot.nextState.name:null,u=this.agentData.snapshot.nextState?this.agentData.snapshot.nextState.name:null;c!==u&&u&&n.bus.trigger(t.AgentEvents.ENQUEUED_NEXT_STATE,new t.Agent),r=null!==e?this._diffContacts(e):{added:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId})),removed:{},common:{},oldMap:{},newMap:t.index(this.agentData.snapshot.contacts,(function(e){return e.contactId}))},t.values(r.added).forEach((function(e){n.bus.trigger(t.ContactEvents.INIT,new t.Contact(e.contactId)),n._fireContactUpdateEvents(e.contactId,t.ContactStateType.INIT,e.state.type)})),t.values(r.removed).forEach((function(e){n.bus.trigger(t.ContactEvents.DESTROYED,new t.ContactSnapshot(e)),n.bus.trigger(t.core.getContactEventName(t.ContactEvents.DESTROYED,e.contactId),new t.ContactSnapshot(e)),n._unsubAllContactEventsForContact(e.contactId)})),t.keys(r.common).forEach((function(e){n._fireContactUpdateEvents(e,r.oldMap[e].state.type,r.newMap[e].state.type)}))},f.prototype._fireContactUpdateEvents=function(e,n,r){var o=this;n!==r&&t.core.getContactEventGraph().getAssociations(this,n,r).forEach((function(n){o.bus.trigger(n,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(n,e),new t.Contact(e))})),o.bus.trigger(t.ContactEvents.REFRESH,new t.Contact(e)),o.bus.trigger(t.core.getContactEventName(t.ContactEvents.REFRESH,e),new t.Contact(e))},f.prototype._unsubAllContactEventsForContact=function(e){var n=this;t.values(t.ContactEvents).forEach((function(r){n.bus.getSubscriptions(t.core.getContactEventName(r,e)).map((function(e){e.unsubscribe()}))}))},t.core.onViewContact=function(e){t.core.getUpstream().onUpstream(t.ContactEvents.VIEW,e)},t.core.viewContact=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.VIEW,data:{contactId:e}})},t.core.onActivateChannelWithViewType=function(e){t.core.getUpstream().onUpstream(t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,e)},t.core.activateChannelWithViewType=function(e,n,r){const o={viewType:e,mediaType:n};r&&(o.source=r),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE,data:o})},t.core.triggerTaskCreated=function(e){t.core.getUpstream().upstreamBus.trigger(t.TaskEvents.CREATED,e)},t.core.onAccessDenied=function(e){t.core.getUpstream().onUpstream(t.EventType.ACCESS_DENIED,e)},t.core.onAuthFail=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTH_FAIL,e)},t.core.onAuthorizeSuccess=function(e){t.core.getUpstream().onUpstream(t.EventType.AUTHORIZE_SUCCESS,e)},t.core._handleAuthorizeSuccess=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0)},t.core._handleAuthFail=function(e,n,r){r&&r.authorize?t.core._handleAuthorizeFail(e):t.core._handleCTIAuthFail(n)},t.core._handleAuthorizeFail=function(e){let n=t.core._getAuthRetryCount();if(!t.core.authorizeTimeoutId)if(n{t.core._redirectToLogin(e)}),r)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED)},t.core._redirectToLogin=function(e){"string"==typeof e?location.assign(e):location.reload()},t.core._handleCTIAuthFail=function(e){if(!t.core.ctiTimeoutId)if(t.core.ctiAuthRetryCount{t.core.authorize(e).then(t.core._triggerAuthorizeSuccess.bind(t.core)).catch(t.core._triggerAuthFail.bind(t.core,{authorize:!0})),t.core.ctiTimeoutId=null}),n)}else t.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(),t.core.getEventBus().trigger(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED)},t.core._triggerAuthorizeSuccess=function(){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTHORIZE_SUCCESS)},t.core._triggerAuthFail=function(e){t.core.getUpstream().upstreamBus.trigger(t.EventType.AUTH_FAIL,e)},t.core._getAuthRetryCount=function(){let e=window.sessionStorage.getItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT);if(null!==e){if(isNaN(parseInt(e)))throw new t.StateError("The session storage value for auth retry count was NaN");return parseInt(e)}return window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,0),0},t.core._incrementAuthRetryCount=function(){window.sessionStorage.setItem(t.SessionStorageKeys.AUTHORIZE_RETRY_COUNT,(t.core._getAuthRetryCount()+1).toString())},t.core.onAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onCTIAuthorizeRetriesExhausted=function(e){t.core.getEventBus().subscribe(t.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED,e)},t.core.onSoftphoneSessionInit=function(e){t.core.getUpstream().onUpstream(t.ConnectionEvents.SESSION_INIT,e)},t.core.onConfigure=function(e){t.core.getUpstream().onUpstream(t.ConfigurationEvents.CONFIGURE,e)},t.core.onInitialized=function(e){t.core.getEventBus().subscribe(t.EventType.INIT,e)},t.core.getContactEventName=function(e,n){if(t.assertNotNull(e,"eventName"),t.assertNotNull(n,"contactId"),!t.contains(t.values(t.ContactEvents),e))throw new t.ValueError("%s is not a valid contact event.",e);return t.sprintf("%s::%s",e,n)},t.core.getEventBus=function(){return t.core.eventBus},t.core.getWebSocketManager=function(){return t.core.webSocketProvider},t.core.getAgentDataProvider=function(){return t.core.agentDataProvider},t.core.getLocalTimestamp=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp},t.core.getSkew=function(){return t.core.getAgentDataProvider().getAgentData().snapshot.skew},t.core.getAgentRoutingEventGraph=function(){return t.core.agentRoutingEventGraph},t.core.agentRoutingEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.AgentStateType.ROUTABLE,t.AgentEvents.ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.NOT_ROUTABLE,t.AgentEvents.NOT_ROUTABLE).assoc(t.EventGraph.ANY,t.AgentStateType.OFFLINE,t.AgentEvents.OFFLINE),t.core.getAgentStateEventGraph=function(){return t.core.agentStateEventGraph},t.core.agentStateEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.values(t.AgentErrorStates),t.AgentEvents.ERROR).assoc(t.EventGraph.ANY,t.AgentAvailStates.AFTER_CALL_WORK,t.AgentEvents.ACW),t.core.getContactEventGraph=function(){return t.core.contactEventGraph},t.core.contactEventGraph=(new t.EventGraph).assoc(t.EventGraph.ANY,t.ContactStateType.INCOMING,t.ContactEvents.INCOMING).assoc(t.EventGraph.ANY,t.ContactStateType.PENDING,t.ContactEvents.PENDING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTING,t.ContactEvents.CONNECTING).assoc(t.EventGraph.ANY,t.ContactStateType.CONNECTED,t.ContactEvents.CONNECTED).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.ContactStateType.INCOMING,t.ContactStateType.ERROR,t.ContactEvents.MISSED).assoc(t.EventGraph.ANY,t.ContactStateType.ENDED,t.ContactEvents.ACW).assoc(t.values(t.CONTACT_ACTIVE_STATES),t.values(t.relativeComplement(t.CONTACT_ACTIVE_STATES,t.ContactStateType)),t.ContactEvents.ENDED).assoc(t.EventGraph.ANY,t.ContactStateType.ERROR,t.ContactEvents.ERROR).assoc(t.ContactStateType.CONNECTING,t.ContactStateType.MISSED,t.ContactEvents.MISSED),t.core.getClient=function(){if(!t.core.client)throw new t.StateError("The connect core has not been initialized!");return t.core.client},t.core.client=null,t.core.getAgentAppClient=function(){if(!t.core.agentAppClient)throw new t.StateError("The connect AgentApp Client has not been initialized!");return t.core.agentAppClient},t.core.agentAppClient=null,t.core.getTaskTemplatesClient=function(){if(!t.core.taskTemplatesClient)throw new t.StateError("The connect TaskTemplates Client has not been initialized!");return t.core.taskTemplatesClient},t.core.taskTemplatesClient=null,t.core.getMasterClient=function(){if(!t.core.masterClient)throw new t.StateError("The connect master client has not been initialized!");return t.core.masterClient},t.core.masterClient=null,t.core.getSoftphoneManager=function(){return t.core.softphoneManager},t.core.softphoneManager=null,t.core.getNotificationManager=function(){return t.core.notificationManager||(t.core.notificationManager=new t.NotificationManager),t.core.notificationManager},t.core.notificationManager=null,t.core.getPopupManager=function(){return t.core.popupManager},t.core.popupManager=new t.PopupManager,t.core.getUpstream=function(){if(!t.core.upstream)throw new t.StateError("There is no upstream conduit!");return t.core.upstream},t.core.upstream=null,t.core.AgentDataProvider=f}()},592:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t;var n="<>",r=t.makeEnum(["acknowledge","ack_timeout","init","api_request","api_response","auth_fail","access_denied","close","configure","log","master_request","master_response","synchronize","terminate","terminated","send_logs","reload_agent_configuration","broadcast","api_metric","client_metric","softphone_stats","softphone_report","client_side_logs","server_bound_internal_log","mute","iframe_style","iframe_retries_exhausted","update_connected_ccps","outer_context_info","media_device_request","media_device_response","tab_id","authorize_success","authorize_retries_exhausted","cti_authorize_retries_exhausted"]),o=t.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),i=t.makeNamespacedEnum("agent",["init","update","refresh","routable","not_routable","pending","contact_pending","offline","error","softphone_error","websocket_connection_lost","websocket_connection_gained","state_change","acw","mute_toggle","local_media_stream_created","enqueued_next_state"]),s=t.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),a=t.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),c=t.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),u=t.makeNamespacedEnum("task",["created"]),l=t.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),p=t.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),d=t.makeNamespacedEnum("voiceId",["update_domain_id"]),h=function(){};h.createRequest=function(e,n,r){return{event:e,requestId:t.randomId(),method:n,params:r}},h.createResponse=function(e,t,n,r){return{event:e,requestId:t.requestId,data:n,err:r||null}};var f=function(e,n,r){this.subMap=e,this.id=t.randomId(),this.eventName=n,this.f=r};f.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var g=function(){this.subIdMap={},this.subEventNameMap={}};g.prototype.subscribe=function(e,t){var n=new f(this,e,t);this.subIdMap[n.id]=n;var r=this.subEventNameMap[e]||[];return r.push(n),this.subEventNameMap[e]=r,n},g.prototype.unsubscribe=function(e,n){t.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==n})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),t.contains(this.subIdMap,n)&&delete this.subIdMap[n]},g.prototype.getAllSubscriptions=function(){return t.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},g.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var m=function(e){var t=e||{};this.subMap=new g,this.logEvents=t.logEvents||!1};m.prototype.subscribe=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.subMap.subscribe(e,n)},m.prototype.subscribeAll=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.subMap.subscribe(n,e)},m.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},m.prototype.trigger=function(e,r){t.assertNotNull(e,"eventName");var o=this,i=this.subMap.getSubscriptions(n),s=this.subMap.getSubscriptions(e);this.logEvents&&e!==t.EventType.LOG&&e!==t.EventType.MASTER_RESPONSE&&e!==t.EventType.API_METRIC&&e!==t.EventType.SERVER_BOUND_INTERNAL_LOG&&t.getLog().trace("Publishing event: %s",e).sendInternalLogToServer(),e.startsWith(t.ContactEvents.ACCEPTED)&&r&&r.contactId&&!(r instanceof t.Contact)&&(r=new t.Contact(r.contactId)),i.concat(s).forEach((function(n){try{n.f(r||null,e,o)}catch(n){t.getLog().error("'%s' event handler failed.",e).withException(n).sendInternalLogToServer()}}))},m.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},m.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},t.EventBus=m,t.EventFactory=h,t.EventType=r,t.AgentEvents=i,t.ConfigurationEvents=p,t.ConnectionEvents=l,t.ConnnectionEvents=l,t.ContactEvents=a,t.ChannelViewEvents=c,t.TaskEvents=u,t.VoiceIdEvents=d,t.WebSocketEvents=s,t.MasterTopics=o}()},286:()=>{!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";var r=n(1),o="DEBUG",i="aws/subscribe",s="aws/heartbeat",a="disconnected";function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var u={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return u.assertTrue(null!==e&&void 0!==c(e),Object(r.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==c(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},l=new RegExp("^(wss://)\\w*");u.validWSUrl=function(e){return l.test(e)},u.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},u.assertIsObject=function(e,t){if(!u.isObject(e))throw new Error(t+" is not an object!")},u.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)},u.isNetworkOnline=function(){return navigator.onLine},u.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var p=u;function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var n=0;n=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var t=e.prefix||"";return this._logsDestination===o?this.consoleLoggerWrapper:new C(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||E.DEBUG,this._clientLogger=t.logger||null,this._logsDestination="NULL",t.debug&&(this._logsDestination=o),t.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),e}(),b=function(){function e(){g(this,e)}return v(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),C=function(e){function t(e){var n;return g(this,t),(n=function(e,t){return!t||"object"!==d(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}(this,h(t).call(this))).prefix=e||"",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}(t,b),v(t,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:2e3;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}var t,n;return t=e,(n=[{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}}])&&_(t.prototype,n),e}();n.d(t,"a",(function(){return R}));var w=function(){var e=I.getLogger({}),t=p.isNetworkOnline(),n={primary:null,secondary:null},r={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},o={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},c={pendingResponse:!1,intervalHandle:null},u={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},l={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},h={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},f=new A((function(){B()})),g=new Set([i,"aws/unsubscribe",s]),m=setInterval((function(){if(t!==p.isNetworkOnline()){if(!(t=p.isNetworkOnline()))return void H(e.info("Network offline"));var n=T();t&&(!n||S(n,WebSocket.CLOSING)||S(n,WebSocket.CLOSED))&&(H(e.info("Network online, connecting to WebSocket server")),B())}}),250),v=function(t,n){t.forEach((function(t){try{t(n)}catch(t){H(e.error("Error executing callback",t))}}))},y=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"}},E=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";H(e.debug("["+t+"] Primary WebSocket: "+y(n.primary)+" | Secondary WebSocket: "+y(n.secondary)))},S=function(e,t){return e&&e.readyState===t},b=function(e){return S(e,WebSocket.OPEN)},C=function(e){return null===e||void 0===e.readyState||S(e,WebSocket.CLOSED)},T=function(){return null!==n.secondary?n.secondary:n.primary},_=function(){return b(T())},w=function(){if(c.pendingResponse)return H(e.warn("Heartbeat response not received")),clearInterval(c.intervalHandle),c.pendingResponse=!1,void B();_()?(H(e.debug("Sending heartbeat")),T().send(F(s)),c.pendingResponse=!0):(H(e.warn("Failed to send heartbeat since WebSocket is not open")),E("sendHeartBeat"),B())},R=function(){r.exponentialBackOffTime=1e3,c.pendingResponse=!1,r.reconnectWebSocket=!0,clearTimeout(r.lifeTimeTimeoutHandle),clearInterval(c.intervalHandle),clearTimeout(r.exponentialTimeoutHandle),clearTimeout(r.webSocketInitCheckerTimeoutId)},N=function(){h.consecutiveFailedSubscribeAttempts=0,h.consecutiveNoResponseRequest=0,clearInterval(h.responseCheckIntervalId),clearInterval(h.reSubscribeIntervalId)},k=function(){o.connectWebSocketRetryCount=0,o.connectionAttemptStartTime=null,o.noOpenConnectionsTimestamp=null},O=function(){try{H(e.info("WebSocket connection established!")),E("webSocketOnOpen"),null!==r.connState&&r.connState!==a||v(u.connectionGain),r.connState="connected";var t=Date.now();v(u.connectionOpen,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,noOpenConnectionsTimestamp:o.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-o.connectionAttemptStartTime,timeWithoutConnection:o.noOpenConnectionsTimestamp?t-o.noOpenConnectionsTimestamp:null}),k(),R(),T().openTimestamp=Date.now(),0===d.subscribed.size&&b(n.secondary)&&x(n.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(b(n.secondary)&&H(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach((function(e){d.subscriptionHistory.add(e),d.pending.add(e)})),d.subscribed.clear(),P()),w(),c.intervalHandle=setInterval(w,1e4);var i=1e3*l.connConfig.webSocketTransport.transportLifeTimeInSeconds;H(e.debug("Scheduling WebSocket manager reconnection, after delay "+i+" ms")),r.lifeTimeTimeoutHandle=setTimeout((function(){H(e.debug("Starting scheduled WebSocket manager reconnection")),B()}),i)}catch(t){H(e.error("Error after establishing WebSocket connection",t))}},L=function(t){E("webSocketOnError"),H(e.error("WebSocketManager Error, error_event: ",JSON.stringify(t))),B()},D=function(t){var r=JSON.parse(t.data);switch(r.topic){case i:if(H(e.debug("Subscription Message received from webSocket server",t.data)),h.requestCompleted=!0,h.consecutiveNoResponseRequest=0,"success"===r.content.status)h.consecutiveFailedSubscribeAttempts=0,r.content.topics.forEach((function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)})),0===d.subscriptionHistory.size?b(n.secondary)&&(H(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),x(n.primary,"[Primary WebSocket] Closing WebSocket")):P(),v(u.subscriptionUpdate,r);else{if(clearInterval(h.reSubscribeIntervalId),++h.consecutiveFailedSubscribeAttempts,5===h.consecutiveFailedSubscribeAttempts)return v(u.subscriptionFailure,r),void(h.consecutiveFailedSubscribeAttempts=0);h.reSubscribeIntervalId=setInterval((function(){P()}),500)}break;case s:H(e.debug("Heartbeat response received")),c.pendingResponse=!1;break;default:if(r.topic){if(H(e.debug("Message received for topic "+r.topic)),b(n.primary)&&b(n.secondary)&&0===d.subscriptionHistory.size&&this===n.primary)return void H(e.warn("Ignoring Message for Topic "+r.topic+", to avoid duplicates"));if(0===u.allMessage.size&&0===u.topic.size)return void H(e.warn("No registered callback listener for Topic",r.topic));v(u.allMessage,r),u.topic.has(r.topic)&&v(u.topic.get(r.topic),r)}else r.message?H(e.warn("WebSocketManager Message Error",r)):H(e.warn("Invalid incoming message",r))}},P=function t(){if(h.consecutiveNoResponseRequest>3)return H(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void v(u.subscriptionFailure,p.getSubscriptionResponse(i,!1,Array.from(d.pending)));_()?0!==Array.from(d.pending).length&&(clearInterval(h.responseCheckIntervalId),T().send(F(i,{topics:Array.from(d.pending)})),h.requestCompleted=!1,h.responseCheckIntervalId=setInterval((function(){h.requestCompleted||(++h.consecutiveNoResponseRequest,t())}),1e3)):H(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},x=function(t,n){S(t,WebSocket.CONNECTING)||S(t,WebSocket.OPEN)?t.close(1e3,n):H(e.warn("Ignoring WebSocket Close request, WebSocket State: "+y(t)))},M=function(e){x(n.primary,"[Primary] WebSocket "+e),x(n.secondary,"[Secondary] WebSocket "+e)},U=function(t){R(),N(),H(e.error("WebSocket Initialization failed")),r.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(m),v(u.initFailure,{connectWebSocketRetryCount:o.connectWebSocketRetryCount,connectionAttemptStartTime:o.connectionAttemptStartTime,reason:t}),k()},F=function(e,t){return JSON.stringify({topic:e,content:t})},q=function(t){return!!(p.isObject(t)&&p.isObject(t.webSocketTransport)&&p.isNonEmptyString(t.webSocketTransport.url)&&p.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(H(e.error("Invalid WebSocket Connection Configuration",t)),!1)},B=function(){if(p.isNetworkOnline())if(r.websocketInitFailed)H(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(l.promiseCompleted)return R(),H(e.info("Fetching new WebSocket connection configuration")),o.connectionAttemptStartTime=o.connectionAttemptStartTime||Date.now(),l.promiseCompleted=!1,l.promiseHandle=u.getWebSocketTransport(),l.promiseHandle.then((function(t){return l.promiseCompleted=!0,H(e.debug("Successfully fetched webSocket connection configuration",t)),q(t)?(l.connConfig=t,l.connConfig.urlConnValidTime=Date.now()+85e3,f.connected(),j()):(U("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return l.promiseCompleted=!0,H(e.error("Failed to fetch webSocket connection configuration",t)),p.isNetworkFailure(t)?(H(e.info("Retrying fetching new WebSocket connection configuration")),f.retry()):U("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));H(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else H(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},j=function(){if(r.websocketInitFailed)return H(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!p.isNetworkOnline())return H(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};H(e.info("Initializing Websocket Manager")),E("initWebSocket");try{if(q(l.connConfig)){var t=null;return b(n.primary)?(H(e.debug("Primary Socket connection is already open")),S(n.secondary,WebSocket.CONNECTING)||(H(e.debug("Establishing a secondary web-socket connection")),n.secondary=V()),t=n.secondary):(S(n.primary,WebSocket.CONNECTING)||(H(e.debug("Establishing a primary web-socket connection")),n.primary=V()),t=n.primary),r.webSocketInitCheckerTimeoutId=setTimeout((function(){b(t)||function(){o.connectWebSocketRetryCount++;var t=p.addJitter(r.exponentialBackOffTime,.3);Date.now()+t<=l.connConfig.urlConnValidTime?(H(e.debug("Scheduling WebSocket reinitialization, after delay "+t+" ms")),r.exponentialTimeoutHandle=setTimeout((function(){return j()}),t),r.exponentialBackOffTime*=2):(H(e.warn("WebSocket URL cannot be used to establish connection")),B())}()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return H(e.error("Error Initializing web-socket-manager",t)),U("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},V=function(){var t=new WebSocket(l.connConfig.webSocketTransport.url);return t.addEventListener("open",O),t.addEventListener("message",D),t.addEventListener("error",L),t.addEventListener("close",(function(i){return function(t,i){H(e.info("Socket connection is closed",JSON.stringify(t))),E("webSocketOnClose before-cleanup"),v(u.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),C(n.primary)&&(n.primary=null),C(n.secondary)&&(n.secondary=null),r.reconnectWebSocket&&(b(n.primary)||b(n.secondary)?C(n.primary)&&b(n.secondary)&&(H(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(H(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),r.connState===a?H(e.info("Ignoring connectionLost callback invocation")):(v(u.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),o.noOpenConnectionsTimestamp=Date.now()),r.connState=a,B()),E("webSocketOnClose after-cleanup"))}(i,t)})),t},H=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(p.assertTrue(p.isFunction(t),"transportHandle must be a function"),null===u.getWebSocketTransport)return u.getWebSocketTransport=t,B();H(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.initFailure.add(e),r.websocketInitFailed&&e(),function(){return u.initFailure.delete(e)}},this.onConnectionOpen=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionOpen.add(e),function(){return u.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionClose.add(e),function(){return u.connectionClose.delete(e)}},this.onConnectionGain=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionGain.add(e),_()&&e(),function(){return u.connectionGain.delete(e)}},this.onConnectionLost=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.connectionLost.add(e),r.connState===a&&e(),function(){return u.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionUpdate.add(e),function(){return u.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.subscriptionFailure.add(e),function(){return u.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return p.assertNotNull(e,"topicName"),p.assertTrue(p.isFunction(t),"cb must be a function"),u.topic.has(e)?u.topic.get(e).add(t):u.topic.set(e,new Set([t])),function(){return u.topic.get(e).delete(t)}},this.onAllMessage=function(e){return p.assertTrue(p.isFunction(e),"cb must be a function"),u.allMessage.add(e),function(){return u.allMessage.delete(e)}},this.subscribeTopics=function(e){p.assertNotNull(e,"topics"),p.assertIsList(e),e.forEach((function(e){d.subscribed.has(e)||d.pending.add(e)})),h.consecutiveNoResponseRequest=0,P()},this.sendMessage=function(t){if(p.assertIsObject(t,"payload"),void 0===t.topic||g.has(t.topic))H(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void H(e.warn("Error stringify message",t))}_()?T().send(t):H(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){R(),N(),r.reconnectWebSocket=!1,clearInterval(m),M("User request to close WebSocket")},this.terminateWebSocketManager=U},R={create:function(){return new w},setGlobalConfig:function(e){var t=e.loggerConfig;I.updateLoggerConfig(t)},LogLevel:E,Logger:y}},function(e,t,n){var r;!function(){"use strict";var o={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,t){var n,r,s,a,c,u,l,p,d,h=1,f=e.length,g="";for(r=0;r=0),a.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,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}o.json.test(a.type)?g+=n:(!o.number.test(a.type)||p&&!a.sign?d="":(d=p?"+":"-",n=n.toString().replace(o.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(d+n).length,c=a.width&&l>0?u.repeat(l):"",g+=a.align?d+n+c:"0"===u?d+c+n:c+d+n)}return g}(function(e){if(a[e])return a[e];for(var t,n=e,r=[],i=0;n;){if(null!==(t=o.text.exec(n)))r.push(t[0]);else if(null!==(t=o.modulo.exec(n)))r.push("%");else{if(null===(t=o.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var s=[],c=t[2],u=[];if(null===(u=o.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=o.key_access.exec(c)))s.push(u[1]);else{if(null===(u=o.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");r.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 a[e]=r}(e),arguments)}function s(e,t){return i.apply(null,[e].concat(t||[]))}var a=Object.create(null);t.sprintf=i,t.vsprintf=s,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=s,void 0===(r=function(){return{sprintf:i,vsprintf:s}}.call(t,n,t,e))||(e.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return o}));var r=n(0);e.connect=e.connect||{},connect.WebSocketManager=r.a;var o=r.a}.call(this,n(3))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n}])},151:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},r={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},o={TEST:0,TRACE:10,DEBUG:20,INFO:30,LOG:40,WARN:50,ERROR:100,CRITICAL:200},i={TRACE:function(e){console.info(e)},DEBUG:function(e){console.info(e)},INFO:function(e){console.info(e)},LOG:function(e){console.log(e)},TEST:function(e){console.log(e)},WARN:function(e){console.warn(e)},ERROR:function(e){console.error(e)},CRITICAL:function(e){console.error(e)}},s=function(e){var t,n,o=Array.prototype.slice.call(e,0),i=o.shift();return function(e){return-1!==Object.values(r).indexOf(e)}(i)?(n=i,t=o.shift()):(t=i,n=r.CCP),{format:t,component:n,args:o}},a=function(e,n,r,o){this.component=e,this.level=n,this.text=r,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{t.agent.initialized&&(this.agentResourceId=(new t.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};a.fromObject=function(e){var t=new a(r.CCP,e.level,e.text,e.loggerId);return"[object Date]"===Object.prototype.toString.call(e.time)?t.time=new Date(e.time.getTime()):"number"==typeof e.time?t.time=new Date(e.time):"string"==typeof e.time?t.time=Date.parse(e.time):t.time=new Date,t.exception=e.exception,t.objects=e.objects,t};var c=function(e){var t=/AuthToken.*\=/g;e&&"object"==typeof e&&Object.keys(e).forEach((function(n){"object"==typeof e[n]?c(e[n]):"string"==typeof e[n]&&("url"===n||"text"===n?e[n]=e[n].replace(t,"[redacted]"):"quickConnectName"===n&&(e[n]="[redacted]"))}))},u=function(e){if(this.type=e instanceof Error?e.name:e.code||Object.prototype.toString.call(e),this.message=e.message,this.stack=[],e.stack)try{Array.isArray(e.stack)?this.stack=e.stack:"object"==typeof e.stack?this.stack=[JSON.stringify(e.stack)]:"string"==typeof e.stack&&(this.stack=e.stack.split("\n"))}catch{}};a.prototype.toString=function(){return t.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},a.prototype.getTime=function(){return this.time},a.prototype.getAgentResourceId=function(){return this.agentResourceId},a.prototype.getLevel=function(){return this.level},a.prototype.getText=function(){return this.text},a.prototype.getComponent=function(){return this.component},a.prototype.withException=function(e){return this.exception=new u(e),this},a.prototype.withObject=function(e){var n=t.deepcopy(e);return c(n),this.objects.push(n),this},a.prototype.withCrossOriginEventObject=function(e){var n=t.deepcopyCrossOriginEvent(e);return c(n),this.objects.push(n),this},a.prototype.sendInternalLogToServer=function(){return t.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=o.INFO,this._logLevel=o.INFO,this._lineCount=0,this._logRollInterval=0,this._logRollTimer=null,this._loggerId=(new Date).getTime()+"-"+Math.random().toString(36).slice(2),this.setLogRollInterval(18e5),this._startLogIndexToPush=0};l.prototype.setLogRollInterval=function(t){var n=this;this._logRollTimer&&t===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&e.clearInterval(this._logRollTimer),this._logRollInterval=t,this._logRollTimer=e.setInterval((function(){n._rolledLogs=n._logs,n._logs=[],n._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._logLevel=o[e]},l.prototype.setEchoLevel=function(e){if(!(e in o))throw new Error("Unknown logging level: "+e);this._echoLevel=o[e]},l.prototype.write=function(e,t,n){var r=new a(e,t,n,this.getLoggerId());return c(r),this.addLogEntry(r),r},l.prototype.addLogEntry=function(e){c(e),this._logs.push(e),r.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in o&&o[e.level]>=this._logLevel&&(o[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=i._logLevel})));var a=new e.Blob([JSON.stringify(s,void 0,4)],["text/plain"]),c=document.createElement("a");n=n||"agent-log",c.href=e.URL.createObjectURL(a),c.download=n+".txt",document.body.appendChild(c),c.click(),document.body.removeChild(c)},l.prototype.scheduleUpstreamLogPush=function(n){t.upstreamLogPushScheduled||(t.upstreamLogPushScheduled=!0,e.setInterval(t.hitch(this,this.reportMasterLogsUpStream,n),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var n=this._logsToPush.slice();this._logsToPush=[],t.ifMaster(t.MasterTopics.SEND_LOGS,(function(){n.length>0&&e.sendUpstream(t.EventType.SEND_LOGS,n)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,n),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(n){e.setInterval(t.hitch(this,this.pushOuterContextCCPLogsUpstream,n),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var n=0;n500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),t.publishClientSideLogs(e))};var p=function(n){l.call(this),this.conduit=n,e.setInterval(t.hitch(this,this._pushLogsDownstream),p.LOG_PUSH_INTERVAL),e.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,p.prototype=Object.create(l.prototype),p.prototype.constructor=p,p.prototype.pushLogsDownstream=function(e){var n=this;e.forEach((function(e){n.conduit.sendDownstream(t.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(n){e.conduit.sendDownstream(t.EventType.LOG,n)})),this._logs=[];for(var n=0;n{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.ChatMediaController=function(e,n){var r=t.getLog(),o=t.LogComponent.CHAT,i=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},s=function(e){e.onConnectionBroken((function(e){r.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),i("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){r.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),i("Chat Session connection established",e)}))};return{get:function(){return function(){i("Chat media controller init",e.contactId),r.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),t.ChatSession.setGlobalConfig({loggerConfig:{logger:r},region:n.region});var a=t.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:t.core.getWebSocketManager()});return s(a),a.connect().then((function(t){return r.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),i("Chat Session Successfully established",e.contactId),a})).catch((function(t){throw r.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),i("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},279:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.MediaFactory=function(e){var n={},r=new Set,o=t.getLog(),i=t.LogComponent.CHAT,s=t.merge({},e)||{};s.region=s.region||"us-west-2";var a=function(e){n[e]&&!r.has(e)&&(o.info(i,"Destroying mediaController for %s",e),r.add(e),n[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete n[e],r.delete(e)})).catch((function(){delete n[e],r.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var r=e.getConnectionId();if(!e.getMediaInfo())return o.error(i,"Media info does not exist for a media type %s",e.getMediaType()).withObject(e).sendInternalLogToServer(),Promise.reject("Media info does not exist for this connection");if(n[r])return n[r];switch(o.info(i,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case t.MediaType.CHAT:return n[r]=new t.ChatMediaController(e.getMediaInfo(),s).get();case t.MediaType.SOFTPHONE:return n[r]=new t.SoftphoneMediaController(e.getMediaInfo()).get();case t.MediaType.TASK:return n[r]=new t.TaskMediaController(e.getMediaInfo()).get();default:return o.error(i,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(a(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:a}}}()},418:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},187:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,t.TaskMediaController=function(e){var n=t.getLog(),r=t.LogComponent.TASK,o=function(n,r){t.publishMetric({name:n,contactId:e.contactId,data:r||e})},i=function(e){e.onConnectionBroken((function(e){n.error(r,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(r,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),n.info(r,"Task media controller init").withObject(e);var s=t.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:t.core.getWebSocketManager()});return i(s),s.connect().then((function(){return n.info(r,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(r,"Task Session establishement failed for contact %s",e.contactId).withException(t),o("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},743:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var r=this;if(this._prevContactId=null,t.assertNotNull(n,"ringtoneConfig"),!n.ringtoneUrl)throw new Error("ringtoneUrl is required!");e.Audio&&void 0!==e.Promise?this._playableAudioPromise=new Promise((function(e,t){r._audio=new Audio(n.ringtoneUrl),r._audio.loop=!0,r._audio.addEventListener("canplay",(function(){r._audioPlayable=!0,e(r._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),r._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){var n=this;this._audio&&(this._audio.play().catch((function(r){n._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").withException(r).withObject({currentSrc:n._audio.currentSrc,sinkId:n._audio.sinkId,volume:n._audio.volume}).sendInternalLogToServer()})),n._publishTelemetryEvent("Ringtone Start",e),t.getLog().info("Ringtone Start").sendInternalLogToServer())},n.prototype._stopRingtone=function(e){this._audio&&(this._audio.pause(),this._audio.currentTime=0,this._publishTelemetryEvent("Ringtone Stop",e),t.getLog().info("Ringtone Stop").sendInternalLogToServer())},n.prototype.stopRingtone=function(){this._stopRingtone()},n.prototype._ringtoneSetup=function(e){var n=this;t.ifMaster(t.MasterTopics.RINGTONE,(function(){n._startRingtone(e),n._prevContactId=e.getContactId(),e.onConnected(lily.hitch(n,n._stopRingtone)),e.onAccepted(lily.hitch(n,n._stopRingtone)),e.onEnded(lily.hitch(n,n._stopRingtone)),e.onRefresh((function(e){e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING&&n._stopRingtone()}))}))},n.prototype._publishTelemetryEvent=function(e,n){n&&n.getContactId()&&t.publishMetric({name:e,contactId:n.getContactId()})},n.prototype.setOutputDevice=function(t){return this._playableAudioPromise?Promise.race([this._playableAudioPromise,new Promise((function(t,n){e.setTimeout((function(){n("Timed out waiting for playable audio")}),3e3)}))]).then((function(e){return e?e.setSinkId?Promise.resolve(e.setSinkId(t)):Promise.reject("Not supported"):Promise.reject("No audio found")})):e.Promise?Promise.reject("Not eligible ringtone owner"):void 0};var r=function(e){n.call(this,e)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.VOICE&&n.isSoftphoneCall()&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Ringtone Connecting",n),t.getLog().info("Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)})),(new t.Agent).getContacts().forEach((function(e){e.getStatus().type===t.ContactStatusType.CONNECTING&&n(e)}))};var o=function(e){n.call(this,e)};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.CHAT&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Chat Ringtone Connecting",n),t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var i=function(e){n.call(this,e)};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.TASK&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Task Ringtone Connecting",n),t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var s=function(e){n.call(this,e)};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype._driveRingtone=function(){var e=this;t.contact((function(n){n.onIncoming((function(){n.getType()===lily.ContactType.QUEUE_CALLBACK&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Callback Ringtone Connecting",n),t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer())}))}))},t.VoiceRingtoneEngine=r,t.ChatRingtoneEngine=o,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},642:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,e.ccpVersion="V2";var n={};n[t.SoftphoneCallType.AUDIO_ONLY]="Audio",n[t.SoftphoneCallType.VIDEO_ONLY]="Video",n[t.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[t.SoftphoneCallType.NONE]="None";var r="audio_input",o="audio_output";({})[t.ContactType.VOICE]="Voice";var i=[],s={},a={},c=null,u=null,l=null,p=t.SoftphoneErrorTypes,d={},h=t.randomId(),f=function(e){return new Promise((function(n,r){t.core.getClient().call(t.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){n(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&w("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),r(Error("requestIceAccess failed"))},authFailure:function(){r(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){r(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var n=t.core.getUpstream(),r=e.getAgentConnection();if(r){var o=r.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),n.sendUpstream(t.EventType.BROADCAST,{event:t.ContactEvents.ACCEPTED,data:new t.Contact(e.contactId)}),n.sendUpstream(t.EventType.BROADCAST,{event:t.core.getContactEventName(t.ContactEvents.ACCEPTED,e.contactId),data:new t.Contact(e.contactId)})):l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer():l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer()}else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer()},m=function(){t.core.getEventBus().subscribe(t.EventType.MUTE,b)},v=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_SPEAKER_DEVICE,C)},y=function(){t.core.getEventBus().subscribe(t.ConfigurationEvents.SET_MICROPHONE_DEVICE,T)},E=function(){try{t.isChromeBrowser()&&t.getChromeBrowserVersion()>43&&navigator.permissions.query({name:"microphone"}).then((function(e){e.onchange=function(){l.info("Microphone Permission: "+e.state),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:e.state}),"denied"===e.state&&w(p.MICROPHONE_NOT_SHARED,"Your microphone is not enabled in your browser. ","")}}))}catch(e){l.error("Failed in detecting microphone permission status: "+e)}},S=function(e){delete d[e],t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},b=function(e){var n;if(0!==t.keys(d).length){for(var r in e&&void 0!==e.mute&&(n=e.mute),d)if(d.hasOwnProperty(r)){var o=d[r].stream;if(o){var i=o.getAudioTracks()[0];void 0!==n?(i.enabled=!n,d[r].muted=n,n?l.info("Agent has muted the contact, connectionId - "+r).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+r).sendInternalLogToServer()):n=d[r].muted||!1}}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.MUTE_TOGGLE,data:{muted:n}})}},C=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+n),r&&"function"==typeof r.setSinkId&&r.setSinkId(n)}catch(e){l.error("Failed to set speaker to device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:n}})}},T=function(e){if(0!==t.keys(d).length&&e&&e.deviceId){var n=e.deviceId,r=t.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:n}}}).then((function(e){var t=e.getAudioTracks()[0];for(var n in d)d.hasOwnProperty(n)&&(d[n].stream,r.getSession(n)._pc.getSenders()[0].replaceTrack(t).then((function(){r.replaceLocalMediaTrack(n,t)})))}))}catch(e){l.error("Failed to set microphone device "+n)}t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:n}})}},I=function(e,n){if(n===t.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var r="\n",o=0;o0?t.success(e):t.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){t.failure(p.MICROPHONE_NOT_SHARED)})),r}t.failure(p.UNSUPPORTED_BROWSER)},w=function(e,n,r){l.error("Softphone error occurred : ",e,n||"").sendInternalLogToServer(),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.SOFTPHONE_ERROR,data:new t.SoftphoneError(e,n,r)})},R=function(e,t){N("Softphone Session Failed",e,{failedReason:t})},N=function(e,n,r){t.publishMetric({name:e,contactId:n,data:r})},k=function(e,t,n){N(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},O=function(){return!!(t.isOperaBrowser()&&t.getOperaBrowserVersion()>17)||!!(t.isChromeBrowser()&&t.getChromeBrowserVersion()>22)||!!(t.isFirefoxBrowser()&&t.getFirefoxBrowserVersion()>21)},L=function(e){var t=i.slice();i=[],t.length>0&&e.sendSoftphoneMetrics(t,{success:function(){l.info("sendSoftphoneMetrics success"+JSON.stringify(t)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer()}})},D=function(e){c=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(M(s,t,r))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=a;a=e,i.push(M(a,t,o))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},P=function(e){u=window.setInterval((function(){L(e)}),3e4)},x=function(){s=null,a=null,i=[],c=null,u=null},M=function(e,t,n){if(t&&e){var r=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,o=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,r,o,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},U=function(e){return null!==e&&window.clearInterval(e),null},F=function(e,t){c=U(c),u=U(u),function(e,t,n,i){t.streamStats=[B(n,r),B(i,o)];var s={callStartTime:t.sessionStartTime,callEndTime:t.sessionEndTime,gumTimeMillis:t.gumTimeMillis,initializationTimeMillis:t.initializationTimeMillis,iceCollectionTimeMillis:t.iceCollectionTimeMillis,signallingConnectTimeMillis:t.signallingConnectTimeMillis,handshakingTimeMillis:t.handshakingTimeMillis,preTalkingTimeMillis:t.preTalkingTimeMillis,talkingTimeMillis:t.talkingTimeMillis,cleanupTimeMillis:t.cleanupTimeMillis,iceCollectionFailure:t.iceCollectionFailure,signallingConnectionFailure:t.signallingConnectionFailure,handshakingFailure:t.handshakingFailure,gumOtherFailure:t.gumOtherFailure,gumTimeoutFailure:t.gumTimeoutFailure,createOfferFailure:t.createOfferFailure,setLocalDescriptionFailure:t.setLocalDescriptionFailure,userBusyFailure:t.userBusyFailure,invalidRemoteSDPFailure:t.invalidRemoteSDPFailure,noRemoteIceCandidateFailure:t.noRemoteIceCandidateFailure,setRemoteDescriptionFailure:t.setRemoteDescriptionFailure,softphoneStreamStatistics:t.streamStats};e.sendSoftphoneReport(s,{success:function(){l.info("sendSoftphoneReport success"+JSON.stringify(s)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer()}})}(e,t,B(s,r),B(a,o)),L(e)},q=function(e,t,n,r,o,i,s){this.softphoneStreamType=r,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=o,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},B=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var n=this;this._tee=function(e,r){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),r.apply(n._originalLogger,[t.LogComponent.SOFTPHONE,o].concat(e))}}};j.prototype.debug=function(){return this._tee(1,this._originalLogger.debug)(arguments)},j.prototype.info=function(){return this._tee(2,this._originalLogger.info)(arguments)},j.prototype.log=function(){return this._tee(3,this._originalLogger.log)(arguments)},j.prototype.warn=function(){return this._tee(4,this._originalLogger.warn)(arguments)},j.prototype.error=function(){return this._tee(5,this._originalLogger.error)(arguments)},t.SoftphoneManager=function(e){var n,r=this;(l=new j(t.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),t.RtcPeerConnectionFactory&&(n=new t.RtcPeerConnectionFactory(l,t.core.getWebSocketManager(),h,t.hitch(r,f,{transportType:"softphone",softphoneClientId:h}),t.hitch(r,w))),O()||w(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"granted"})},failure:function(e){w(e,"Your microphone is not enabled in your browser. ",""),N("ConnectivityCheckResult",null,{connectivityCheckType:"MicrophonePermission",status:"denied"})}}),m(),v(),y(),E(),this.ringtoneEngine=null;var o={},i={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var s=!1,a=null,c=null,u=function(){s=!1,a=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=d[e].stream;if(n){var r=n.getAudioTracks()[0];t.enabled=r.enabled,r.enabled=!1,n.removeTrack(r),n.addTrack(t)}};var b=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,r){delete o[e],delete i[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,r){var p=s?a:e,h=s?c:r;if(p&&h){u(),i[h]=!0,l.info("Softphone call detected:","contactId "+p.getContactId(),"agent connectionId "+h).sendInternalLogToServer(),function(e){if(Object.keys(e).length>0){for(var t in e)e.hasOwnProperty(t)&&(k("MultiSessionHangUp",e[t].callId,t),b(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===t.ContactStatusType.CONNECTING&&N("Softphone Connecting",p.getContactId()),x();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=_(m.callConfigJson);v.useWebSocketProvider&&(f=t.core.getWebSocketManager());var y=new t.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),h,f);o[h]=y,t.core.getSoftphoneUserMediaStream()&&(y.mediaStream=t.core.getSoftphoneUserMediaStream()),t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.ConnectionEvents.SESSION_INIT,data:{connectionId:h}}),y.onSessionFailed=function(e,t){delete o[h],delete i[h],I(e,t),R(p.getContactId(),t),F(p,e.sessionReport)},y.onSessionConnected=function(e){N("Softphone Session Connected",p.getContactId()),t.becomeMaster(t.MasterTopics.SEND_LOGS),D(e),P(p),g(p)},y.onSessionCompleted=function(e){N("Softphone Session Completed",p.getContactId()),delete o[h],delete i[h],F(p,e.sessionReport),S(h)},y.onLocalStreamAdded=function(e,n){d[h]={stream:n},t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:h}})},y.remoteAudioElement=document.getElementById("remote-audio"),n?y.connect(n.get(v.iceServers)):y.connect()}};var C=function(e,n){o[n]&&function(e){return e.getStatus().type===t.ContactStatusType.ENDED||e.getStatus().type===t.ContactStatusType.ERROR||e.getStatus().type===t.ContactStatusType.MISSED}(e)&&(b(n),u()),!e.isSoftphoneCall()||i[n]||e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING||(t.isFirefoxBrowser()&&t.hasOtherConnectedCCPs()?function(e,t){s=!0,a=e,c=t}(e,n):r.startSession(e,n))},T=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),i[t]||e.onRefresh((function(){C(e,t)}))};r.onInitContactSub=t.contact(T),(new t.Agent).getContacts().forEach((function(e){var t=e.getAgentConnection().connectionId;l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId"+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),T(e),C(e,t)}))}}()},944:()=>{!function(){var e=this||window,t=function(){return t.cache.hasOwnProperty(arguments[0])||(t.cache[arguments[0]]=t.parse(arguments[0])),t.format.call(null,t.cache[arguments[0]],arguments)};function n(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}t.format=function(e,o){var i,s,a,c,u,l,p,d=1,h=e.length,f="",g=[];for(s=0;s>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}i=/[def]/.test(c[8])&&c[3]&&i>=0?"+"+i:i,l=c[4]?"0"==c[4]?"0":c[4].charAt(1):" ",p=c[6]-String(i).length,u=c[6]?r(l,p):"",g.push(c[5]?i+u:u+i)}return g.join("")},t.cache={},t.parse=function(e){for(var t=e,n=[],r=[],o=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))r.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))r.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){o|=1;var i=[],s=n[2],a=[];if(null===(a=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(a[1]);""!==(s=s.substring(a[0].length));)if(null!==(a=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(a[1]);else{if(null===(a=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(a[1])}n[2]=i}else o|=2;if(3===o)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";r.push(n)}t=t.substring(n[0].length)}return r},e.sprintf=t,e.vsprintf=function(e,n,r){return(r=n.slice(0)).splice(0,0,e),t.apply(null,r)}}()},82:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(){};n.prototype.send=function(e){throw new t.NotImplementedError},n.prototype.onMessage=function(e){throw new t.NotImplementedError};var r=function(){n.call(this)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.onMessage=function(e){},r.prototype.send=function(e){};var o=function(e,t){n.call(this),this.window=e,this.domain=t||"*"};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.send=function(e){this.window.postMessage(e,this.domain)},o.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var i=function(e,t,r){n.call(this),this.input=e,this.output=t,this.domain=r||"*"};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype.send=function(e){this.output.postMessage(e,this.domain)},i.prototype.onMessage=function(e){this.input.addEventListener("message",(t=>{t.source===this.output&&e(t)}))};var s=function(e){n.call(this),this.port=e,this.id=t.randomId()};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype.send=function(e){this.port.postMessage(e)},s.prototype.onMessage=function(e){this.port.addEventListener("message",e)},s.prototype.getId=function(){return this.id};var a=function(e){n.call(this),this.streamMap=e?t.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(a.prototype=Object.create(n.prototype)).constructor=a,a.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},a.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},a.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},a.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},a.prototype.getStreams=function(e){return t.values(this.streamMap)},a.prototype.getStreamForPort=function(e){return t.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,n,o){this.name=e,this.upstream=n||new r,this.downstream=o||new r,this.downstreamBus=new t.EventBus,this.upstreamBus=new t.EventBus,this.upstream.onMessage(t.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(t.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.upstreamBus.subscribe(e,n)},c.prototype.onAllUpstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,n){return t.assertNotNull(e,"eventName"),t.assertNotNull(n,"f"),t.assertTrue(t.isFunction(n),"f must be a function"),this.downstreamBus.subscribe(e,n)},c.prototype.onAllDownstream=function(e){return t.assertNotNull(e,"f"),t.assertTrue(t.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,n){t.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:n})},c.prototype.sendDownstream=function(e,n){t.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:n})},c.prototype._dispatchEvent=function(e,t){var n=t.data;n.event&&e.trigger(n.event,n.data)},c.prototype.passUpstream=function(){var e=this;return function(t,n){e.upstream.send({event:n,data:t})}},c.prototype.passDownstream=function(){var e=this;return function(t,n){e.downstream.send({event:n,data:t})}},c.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};var u=function(e,t,n,r){c.call(this,e,new i(t,n.contentWindow,r||"*"),null)};(u.prototype=Object.create(c.prototype)).constructor=u,t.Stream=n,t.NullStream=r,t.WindowStream=o,t.WindowIOStream=i,t.PortStream=s,t.StreamMultiplexer=a,t.Conduit=c,t.IFrameConduit=u}()},833:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=function(e,n){t.assertNotNull(e,"fromState"),t.assertNotNull(n,"toState"),this.fromState=e,this.toState=n};n.prototype.getAssociations=function(e){throw t.NotImplementedError()},n.prototype.getFromState=function(){return this.fromState},n.prototype.getToState=function(){return this.toState};var r=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"associations"),n.call(this,e,r),this.associations=o};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype.getAssociations=function(e){return this.associations};var o=function(e,r,o){t.assertNotNull(e,"fromState"),t.assertNotNull(r,"toState"),t.assertNotNull(o,"closure"),t.assertTrue(t.isFunction(o),"closure must be a function"),n.call(this,e,r),this.closure=o};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var i=function(){this.fromMap={}};i.ANY="<>",i.prototype.assoc=function(e,t,n){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!n)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,n)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,n)})):"function"==typeof n?this._addAssociation(new o(e,t,n)):n instanceof Array?this._addAssociation(new r(e,t,n)):this._addAssociation(new r(e,t,[n])),this},i.prototype.getAssociations=function(e,n,r){t.assertNotNull(n,"fromState"),t.assertNotNull(r,"toState");var o=[],s=this.fromMap[i.ANY]||{},a=this.fromMap[n]||{};return o=(o=o.concat(this._getAssociationsFromMap(s,e,n,r))).concat(this._getAssociationsFromMap(a,e,n,r))},i.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];t||(t=this.fromMap[e.getFromState()]={});var n=t[e.getToState()];n||(n=t[e.getToState()]=[]),n.push(e)},i.prototype._getAssociationsFromMap=function(e,t,n,r){return(e[i.ANY]||[]).concat(e[r]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},t.EventGraph=i}()},891:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t;var n=navigator.userAgent,r=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];t.sprintf=e.sprintf,t.vsprintf=e.vsprintf,delete e.sprintf,delete e.vsprintf,t.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},t.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},t.hitch=function(){var e=Array.prototype.slice.call(arguments),n=e.shift(),r=e.shift();return t.assertNotNull(n,"scope"),t.assertNotNull(r,"method"),t.assertTrue(t.isFunction(r),"method must be a function"),function(){var t=Array.prototype.slice.call(arguments);return r.apply(n,e.concat(t))}},t.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.keys=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(r);return n},t.values=function(e){var n=[];for(var r in t.assertNotNull(e,"map"),e)n.push(e[r]);return n},t.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},t.merge=function(){var e=Array.prototype.slice.call(arguments,0),n={};return e.forEach((function(e){t.entries(e).forEach((function(e){n[e.key]=e.value}))})),n},t.now=function(){return(new Date).getTime()},t.find=function(e,t){for(var n=0;n{try{n[r]=e[r]}catch(e){t.getLog().info("deepcopyCrossOriginEvent failed on key: ",r).sendInternalLogToServer()}})),t.deepcopy(n)},t.getBaseUrl=function(){var n=e.location;return t.sprintf("%s//%s:%s",n.protocol,n.hostname,n.port)},t.getUrlWithProtocol=function(n){var r=e.location.protocol;return n.substr(0,r.length)!==r?t.sprintf("%s//%s",r,n):n},t.isFramed=function(){try{return window.self!==window.top}catch(e){return!0}},t.hasOtherConnectedCCPs=function(){return t.numberOfConnectedCCPs>1},t.fetch=function(e,n,r,o){return o=o||5,r=r||1e3,n=n||{},new Promise((function(i,s){!function o(a){fetch(e,n).then((function(e){e.status===t.HTTP_STATUS_CODES.SUCCESS?e.json().then((e=>i(e))).catch((()=>i({}))):1!==a&&(e.status>=t.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===t.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--a)}),r):s(e)})).catch((function(e){s(e)}))}(o)}))},t.backoff=function(n,r,o,i){t.assertTrue(t.isFunction(n),"func must be a Function");var s=this;n({success:function(e){i&&i.success&&i.success(e)},failure:function(t,a){if(o>0){var c=2*r*Math.random();e.setTimeout((function(){s.backoff(n,2*c,--o,i)}),c)}else i&&i.failure&&i.failure(t,a)}})},t.publishMetric=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.CLIENT_METRIC,data:e})},t.publishSoftphoneStats=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_STATS,data:e})},t.publishSoftphoneReport=function(e){t.core.getUpstream().sendUpstream(t.EventType.BROADCAST,{event:t.EventType.SOFTPHONE_REPORT,data:e})},t.publishClientSideLogs=function(e){t.core.getEventBus().trigger(t.EventType.CLIENT_SIDE_LOGS,e)},t.addNamespaceToLogs=function(e){["log","error","warn","info","debug"].forEach((t=>{const n=window.console[t];window.console[t]=function(){const t=Array.from(arguments);t.unshift(`[${e}]`),n.apply(window.console,t)}}))},t.PopupManager=function(){},t.PopupManager.prototype.open=function(e,t,n){var r=this._getLastOpenedTimestamp(t),o=(new Date).getTime(),i=null;if(o-r>864e5){if(n){var s=n.height||578,a=n.width||433,c=n.top||0,u=n.left||0;(i=window.open("",t,"width="+a+", height="+s+", top="+c+", left="+u)).location!==e&&(i=window.open(e,t,"width="+a+", height="+s+", top="+c+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,o)}return i},t.PopupManager.prototype.clear=function(t){var n=this._getLocalStorageKey(t);e.localStorage.removeItem(n)},t.PopupManager.prototype._getLastOpenedTimestamp=function(t){var n=this._getLocalStorageKey(t),r=e.localStorage.getItem(n);return r?parseInt(r,10):0},t.PopupManager.prototype._setLastOpenedTimestamp=function(t,n){var r=this._getLocalStorageKey(t);e.localStorage.setItem(r,""+n)},t.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var o=t.makeEnum(["granted","denied","default"]);t.NotificationManager=function(){this.queue=[],this.permission=o.DEFAULT},t.NotificationManager.prototype.requestPermission=function(){var n=this;"Notification"in e?e.Notification.permission===o.DENIED?(t.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=o.DENIED):this.permission!==o.GRANTED&&e.Notification.requestPermission().then((function(e){n.permission=e,e===o.GRANTED?n._showQueued():n.queue=[]})):(t.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=o.DENIED)},t.NotificationManager.prototype.show=function(e,n){if(this.permission===o.GRANTED)return this._showImpl({title:e,options:n});if(this.permission===o.DENIED)t.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:n});else{var r={title:e,options:n};t.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(r).sendInternalLogToServer(),this.queue.push(r)}},t.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},t.NotificationManager.prototype._showImpl=function(t){var n=new e.Notification(t.title,t.options);return t.options.clicked&&(n.onclick=function(){t.options.clicked.call(n)}),n},t.BaseError=function(n,r){e.Error.call(this,t.vsprintf(n,r))},t.BaseError.prototype=Object.create(Error.prototype),t.BaseError.prototype.constructor=t.BaseError,t.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.ValueError.prototype=Object.create(t.BaseError.prototype),t.ValueError.prototype.constructor=t.ValueError,t.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.NotImplementedError.prototype=Object.create(t.BaseError.prototype),t.NotImplementedError.prototype.constructor=t.NotImplementedError,t.StateError=function(){var e=Array.prototype.slice.call(arguments,0),n=e.shift();t.BaseError.call(this,n,e)},t.StateError.prototype=Object.create(t.BaseError.prototype),t.StateError.prototype.constructor=t.StateError,t.VoiceIdError=function(e,t,n){var r={};return r.type=e,r.message=t,r.stack=Error(t).stack,r.err=n,r},t.isCCP=function(){return"ConnectSharedWorkerConduit"===t.core.getUpstream().name}}()},736:()=>{!function(){var e=this||window,t=e.connect||{};e.connect=t,e.lily=t,t.worker={};var n=function(){this.topicMasterMap={}};n.prototype.getMaster=function(e){return t.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},n.prototype.setMaster=function(e,n){t.assertNotNull(e,"topic"),t.assertNotNull(n,"id"),this.topicMasterMap[e]=n},n.prototype.removeMaster=function(e){t.assertNotNull(e,"id");var n=this;t.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete n.topicMasterMap[e.key]}))};var r=function(e){t.ClientBase.call(this),this.conduit=e};(r.prototype=Object.create(t.ClientBase.prototype)).constructor=r,r.prototype._callImpl=function(e,n,r){var o=this,i=(new Date).getTime();t.containsValue(t.AgentAppClientMethods,e)?t.core.getAgentAppClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.containsValue(t.TaskTemplatesClientMethods,e)?t.core.getTaskTemplatesClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t){o._recordAPILatency(e,i,t),r.failure(t)}}):t.core.getClient()._callImpl(e,n,{success:function(t){o._recordAPILatency(e,i),r.success(t)},failure:function(t,n){o._recordAPILatency(e,i,t),r.failure(t,n)},authFailure:function(){o._recordAPILatency(e,i),r.authFailure()},accessDenied:function(){r.accessDenied&&r.accessDenied()}})},r.prototype._recordAPILatency=function(e,t,n){var r=(new Date).getTime()-t;this._sendAPIMetrics(e,r,n)},r.prototype._sendAPIMetrics=function(e,n,r){this.conduit.sendDownstream(t.EventType.API_METRIC,{name:e,time:n,dimensions:[{name:"Category",value:"API"}],error:r})};var o=function(){var o=this;this.multiplexer=new t.StreamMultiplexer,this.conduit=new t.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new r(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.streamMapByTabId={},this.masterCoord=new n,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1,this.longPollingOptions={allowLongPollingShadowMode:!1,allowLongPollingWebsocketOnlyMode:!1};var i=null;t.rootLogger=new t.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(t.EventType.SEND_LOGS,(function(e){t.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(t.EventType.CONFIGURE,(function(n){n.authToken&&n.authToken!==o.initData.authToken&&(o.initData=n,t.core.init(n),n.longPollingOptions&&("boolean"==typeof n.longPollingOptions.allowLongPollingShadowMode&&(o.longPollingOptions.allowLongPollingShadowMode=n.longPollingOptions.allowLongPollingShadowMode),"boolean"==typeof n.longPollingOptions.allowLongPollingWebsocketOnlyMode&&(o.longPollingOptions.allowLongPollingWebsocketOnlyMode=n.longPollingOptions.allowLongPollingWebsocketOnlyMode)),i?t.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(t.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),t.WebSocketManager.setGlobalConfig({loggerConfig:{logger:t.getLog()}}),(i=t.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(t.WebSocketEvents.INIT_FAILURE)})),i.onConnectionOpen((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_OPEN,e)})),i.onConnectionClose((function(e){o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_CLOSE,e)})),i.onConnectionGain((function(){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_GAIN)})),i.onConnectionLost((function(e){o.conduit.sendDownstream(t.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(t.WebSocketEvents.CONNECTION_LOST,e)})),i.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),i.onSubscriptionFailure((function(e){o.conduit.sendDownstream(t.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),i.onAllMessage((function(e){o.conduit.sendDownstream(t.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(t.WebSocketEvents.SEND,(function(e){i.sendMessage(e)})),o.conduit.onDownstream(t.WebSocketEvents.SUBSCRIBE,(function(e){i.subscribeTopics(e)})),i.init(t.hitch(o,o.getWebSocketUrl)).then((function(n){try{if(n&&!n.webSocketConnectionFailed)t.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),t.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),t.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(t.hitch(o,o.checkAuthToken),3e5);else if(!t.webSocketInitFailed){const e=t.WebSocketEvents.INIT_FAILURE;throw o.conduit.sendDownstream(e),t.webSocketInitFailed=!0,new Error(e)}}catch(e){t.getLog().error("WebSocket failed to initialize").withException(e).sendInternalLogToServer()}}))))})),this.conduit.onDownstream(t.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),t.core.terminate(),o.conduit.sendDownstream(t.EventType.TERMINATED)})),this.conduit.onDownstream(t.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(t.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(t.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var n=e.ports[0],r=new t.PortStream(n);o.multiplexer.addStream(r),n.start();var i=new t.Conduit(r.getId(),null,r);i.sendDownstream(t.EventType.ACKNOWLEDGE,{id:r.getId()}),o.portConduitMap[r.getId()]=i,o.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),i.onDownstream(t.EventType.API_REQUEST,t.hitch(o,o.handleAPIRequest,i)),i.onDownstream(t.EventType.MASTER_REQUEST,t.hitch(o,o.handleMasterRequest,i,r.getId())),i.onDownstream(t.EventType.RELOAD_AGENT_CONFIGURATION,t.hitch(o,o.pollForAgentConfiguration)),i.onDownstream(t.EventType.TAB_ID,t.hitch(o,o.handleTabIdEvent,r)),i.onDownstream(t.EventType.CLOSE,t.hitch(o,o.handleCloseEvent,r))}};o.prototype.pollForAgent=function(){var n=this,r=t.hitch(n,n.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:n.nextToken,timeout:3e4},{success:function(r){try{n.agent=n.agent||{},n.agent.snapshot=r.snapshot,n.agent.snapshot.localTimestamp=t.now(),n.agent.snapshot.skew=n.agent.snapshot.snapshotTimestamp-n.agent.snapshot.localTimestamp,n.nextToken=r.nextToken,t.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(r).sendInternalLogToServer(),n.updateAgent()}catch(e){t.getLog().error("Long poll failed to update agent.").withObject(r).withException(e).sendInternalLogToServer()}finally{e.setTimeout(t.hitch(n,n.pollForAgent),100)}},failure:function(r,o){try{t.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:r,data:o})}finally{e.setTimeout(t.hitch(n,n.pollForAgent),5e3)}},authFailure:function(){r()},accessDenied:t.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(n){var r=this,o=n||{},i=t.hitch(r,r.handleAuthFail);this.client.call(t.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(n){var i=n.configuration;r.pollForAgentPermissions(i),r.pollForAgentStates(i),r.pollForDialableCountryCodes(i),r.pollForRoutingProfileQueues(i),o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration,o),3e4)},failure:function(n,i){try{t.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:n,data:i})}finally{o.repeatForever&&e.setTimeout(t.hitch(r,r.pollForAgentConfiguration),3e4,o)}},authFailure:function(){i()},accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,n){var r=this,o=n||{};o.maxResults=o.maxResults||t.DEFAULT_BATCH_SIZE,this.client.call(t.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?r.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),r.updateAgentConfiguration(e))},failure:function(e,n){t.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:n})},authFailure:t.hitch(r,r.handleAuthFail),accessDenied:t.hitch(r,r.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,n){var r=this;this.client.call(n.method,n.params,{success:function(r){var o=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,r);e.sendDownstream(o.event,o)},failure:function(o,i){var s=t.EventFactory.createResponse(t.EventType.API_RESPONSE,n,i,JSON.stringify(o));e.sendDownstream(s.event,s),t.getLog().error("'%s' API request failed",n.method).withObject({request:r.filterAuthToken(n),response:s}).withException(o).sendInternalLogToServer()},authFailure:t.hitch(r,r.handleAuthFail,{authorize:!0})})},o.prototype.handleMasterRequest=function(e,n,r){var o=this.conduit,i=null;switch(r.method){case t.MasterMethods.BECOME_MASTER:var s=this.masterCoord.getMaster(r.params.topic),a=Boolean(s)&&s!==n;this.masterCoord.setMaster(r.params.topic,n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:n,takeOver:a,topic:r.params.topic}),a&&o.sendDownstream(i.event,i);break;case t.MasterMethods.CHECK_MASTER:(s=this.masterCoord.getMaster(r.params.topic))||r.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(r.params.topic,n),s=n),i=t.EventFactory.createResponse(t.EventType.MASTER_RESPONSE,r,{masterId:s,isMaster:n===s,topic:r.params.topic});break;default:throw new Error("Unknown master method: "+r.method)}e.sendDownstream(i.event,i)},o.prototype.handleTabIdEvent=function(e,n){var r=this;try{let o=n.tabId,i=r.streamMapByTabId[o],s=e.getId(),a=Object.keys(r.streamMapByTabId).filter((e=>r.streamMapByTabId[e].length>0)).length;if(i&&i.length>0){if(!i.includes(s)){r.streamMapByTabId[o].push(s);let e={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a};e[o]={length:i.length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,e)}}else{r.streamMapByTabId[o]=[e.getId()];let n={length:Object.keys(r.portConduitMap).length,tabId:o,streamsTabsAcrossBrowser:a+1};n[o]={length:r.streamMapByTabId[o].length},r.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,n)}}catch(e){t.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer()}},o.prototype.handleCloseEvent=function(e){var n=this;n.multiplexer.removeStream(e),delete n.portConduitMap[e.getId()],n.masterCoord.removeMaster(e.getId());let r={length:Object.keys(n.portConduitMap).length},o=Object.keys(n.streamMapByTabId);try{let t=o.find((t=>n.streamMapByTabId[t].includes(e.getId())));if(t){let o=n.streamMapByTabId[t].findIndex((t=>e.getId()===t));n.streamMapByTabId[t].splice(o,1);let i=n.streamMapByTabId[t]?n.streamMapByTabId[t].length:0;r[t]={length:i},r.tabId=t}let i=o.filter((e=>n.streamMapByTabId[e].length>0)).length;r.streamsTabsAcrossBrowser=i}catch(e){t.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer()}n.conduit.sendDownstream(t.EventType.UPDATE_CONNECTED_CCPS,r)},o.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):t.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},o.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&this.agent.snapshot.contacts.length>1&&this.agent.snapshot.contacts.sort((function(e,t){return e.state.timestamp.getTime()-t.state.timestamp.getTime()})),this.agent.snapshot.contacts.forEach((function(e){e.status=e.state,e.connections.forEach((function(e){e.address=e.endpoint}))})),this.agent.configuration.routingProfile.defaultOutboundQueue.queueId=this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN,this.agent.configuration.routingProfile.queues.forEach((function(e){e.queueId=e.queueARN})),this.agent.snapshot.contacts.forEach((function(e){void 0!==e.queue&&(e.queue.queueId=e.queue.queueARN)})),this.agent.configuration.routingProfile.routingProfileId=this.agent.configuration.routingProfile.routingProfileARN,this.conduit.sendDownstream(t.AgentEvents.UPDATE,this.agent)):t.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():t.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,n=t.core.getClient(),r=t.hitch(e,e.handleAuthFail),o=t.hitch(e,e.handleAccessDenied);return new Promise((function(e,i){n.call(t.ClientMethods.CREATE_TRANSPORT,{transportType:t.TRANSPORT_TYPES.WEB_SOCKET},{success:function(n){t.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(n)},failure:function(e,n){t.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:n}),i({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){t.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),i(Error("Authentication failed while getting getWebSocketUrl")),r()},accessDenied:function(){t.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),i(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,n=[],r=e.logsBuffer.slice();e.logsBuffer=[],r.forEach((function(e){n.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(t.ClientMethods.SEND_CLIENT_LOGS,{logEvents:n},{success:function(e){t.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,n){t.getLog().error("SendLogs request failed.").withObject(n).withException(e).sendInternalLogToServer()},authFailure:t.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(e){e?this.conduit.sendDownstream(t.EventType.AUTH_FAIL,e):this.conduit.sendDownstream(t.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(t.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,n=new Date(e.initData.authTokenExpiration),r=(new Date).getTime();n.getTime() 2; + if(isConferenceCall){ + throw new connect.NotImplementedError("VoiceId and Contact Recording are not supported for conference calls"); + } + } /** * @class ChatConnection @@ -2428,6 +2618,7 @@ connect.Address = Endpoint; connect.SoftphoneError = SoftphoneError; connect.VoiceId = VoiceId; + connect.ContactRecording = ContactRecording; })(); @@ -3549,6 +3740,18 @@ module.exports={ "type": "boolean" } } + }, + "channelContext": { + "type": "structure", + "members": { + "scheduledTime": { + "type": "long" + }, + "taskTemplateId": {}, + "taskTemplateVersion": { + "type": "integer" + } + } } } } @@ -3909,7 +4112,7 @@ module.exports={ "contactId": {}, "ccpVersion": {}, "softphoneStreamStatistics": { - "shape": "S3r" + "shape": "S3t" } } }, @@ -3942,7 +4145,7 @@ module.exports={ "type": "timestamp" }, "softphoneStreamStatistics": { - "shape": "S3r" + "shape": "S3t" }, "gumTimeMillis": { "type": "long" @@ -4178,7 +4381,7 @@ module.exports={ } } }, - "S3r": { + "S3t": { "type": "list", "member": { "type": "structure", @@ -23604,7 +23807,11 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", - LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" + LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations", + START_CONTACT_RECORDING: "AgentAppService.Acs.StartContactRecording", + STOP_CONTACT_RECORDING: "AgentAppService.Acs.StopContactRecording", + SUSPEND_CONTACT_RECORDING: "AgentAppService.Acs.SuspendContactRecording", + RESUME_CONTACT_RECORDING: "AgentAppService.Acs.ResumeContactRecording" }; /**--------------------------------------------------------------- @@ -23615,6 +23822,16 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi 'checkMaster' ]); + /**--------------------------------------------------------------- + * enum TaskTemplatesClientMethods + */ + connect.TaskTemplatesClientMethods = connect.makeEnum([ + 'listTaskTemplates', + 'getTaskTemplate', + 'createTemplatedTask', + 'updateContact' + ]); + /**--------------------------------------------------------------- * abstract class ClientBase */ @@ -23786,6 +24003,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi AWSClient.prototype.constructor = AWSClient; AWSClient.prototype._callImpl = function(method, params, callbacks) { + var self = this; var log = connect.getLog(); @@ -23816,7 +24034,19 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var error = {}; error.type = err.code; error.message = err.message; - error.stack = err.stack ? err.stack.split('\n') : []; + error.stack = []; + if (err.stack){ + try { + if (Array.isArray(err.stack)) { + error.stack = err.stack; + } else if (typeof err.stack === 'object') { + error.stack = [JSON.stringify(err.stack)]; + } else if (typeof err.stack === 'string') { + error.stack = err.stack.split('\n'); + } + } catch {} + } + callbacks.failure(error, data); } @@ -23933,13 +24163,95 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi return report; }; + /**--------------------------------------------------------------- + * class TaskTemplatesClient extends ClientBase + */ + var TaskTemplatesClient = function(endpoint) { + connect.assertNotNull(endpoint, 'endpoint'); + ClientBase.call(this); + if (endpoint.includes('/task-templates')) { + this.endpointUrl = connect.getUrlWithProtocol(endpoint); + } else { + var AWSEndpoint = new AWS.Endpoint(endpoint); + var CFPrefix = endpoint.includes('.awsapps.com') ? '/connect' : ''; + this.endpointUrl = connect.getUrlWithProtocol(`${AWSEndpoint.host}${CFPrefix}/task-templates/api/ccp`); + } + }; + + TaskTemplatesClient.prototype = Object.create(ClientBase.prototype); + TaskTemplatesClient.prototype.constructor = TaskTemplatesClient; + + TaskTemplatesClient.prototype._callImpl = function(method, params, callbacks) { + connect.assertNotNull(method, 'method'); + connect.assertNotNull(params, 'params'); + var options = { + credentials: 'include', + method: 'GET', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'x-csrf-token': 'csrf' + } + }; + var instanceId = params.instanceId; + var url = this.endpointUrl; + var methods = connect.TaskTemplatesClientMethods; + switch (method) { + case methods.LIST_TASK_TEMPLATES: + url += `/proxy/instance/${instanceId}/task/template`; + if (params.queryParams) { + const queryString = new URLSearchParams(params.queryParams).toString(); + if (queryString) { + url += `?${queryString}`; + } + } + break; + case methods.GET_TASK_TEMPLATE: + connect.assertNotNull(params.templateParams, 'params.templateParams'); + const id = connect.assertNotNull(params.templateParams.id, 'params.templateParams.id'); + const version = params.templateParams.version; + url += `/proxy/instance/${instanceId}/task/template/${id}`; + if (version) { + url += `?snapshotVersion=${version}`; + } + break; + case methods.CREATE_TEMPLATED_TASK: + url += `/${method}`; + options.body = JSON.stringify(params); + options.method = 'PUT'; + break; + case methods.UPDATE_CONTACT: + url += `/${method}`; + options.body = JSON.stringify(params); + options.method = 'POST'; + } + connect.fetch(url, options) + .then(function(res){ + callbacks.success(res); + }).catch(function(err){ + const reader = err.body.getReader(); + let body = ''; + const decoder = new TextDecoder(); + reader.read().then(function processText({ done, value }) { + if (done) { + var error = JSON.parse(body); + error.status = err.status; + callbacks.failure(error); + return; + } + body += decoder.decode(value); + return reader.read().then(processText); + }); + }) + }; + connect.ClientBase = ClientBase; connect.NullClient = NullClient; connect.UpstreamConduitClient = UpstreamConduitClient; connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; connect.AWSClient = AWSClient; connect.AgentAppClient = AgentAppClient; - + connect.TaskTemplatesClient = TaskTemplatesClient; })(); @@ -23961,7 +24273,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core = {}; connect.core.initialized = false; - connect.version = "2.1.1"; + connect.version = "2.2.0"; connect.DEFAULT_BATCH_SIZE = 500; var CCP_SYN_TIMEOUT = 1000; // 1 sec @@ -23991,7 +24303,25 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var CSM_IFRAME_INITIALIZATION_SUCCESS = 'IframeInitializationSuccess'; var CSM_IFRAME_INITIALIZATION_TIME = 'IframeInitializationTime'; + var CONNECTED_CCPS_SINGLE_TAB = 'ConnectedCCPSingleTabCount'; + var CCP_TABS_ACROSS_BROWSER_COUNT = 'CCPTabsAcrossBrowserCount'; + connect.numberOfConnectedCCPs = 0; + connect.numberOfConnectedCCPsInThisTab = 0; + + connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION = 3; + connect.core.MAX_CTI_AUTH_RETRY_COUNT = 10; + connect.core.ctiAuthRetryCount = 0; + connect.core.authorizeTimeoutId = null; + connect.core.ctiTimeoutId = null; + + /*---------------------------------------------------------------- + * enum SessionStorageKeys + */ + connect.SessionStorageKeys = connect.makeEnum([ + 'tab_id', + 'authorize_retry_count', + ]); /** * @deprecated @@ -24065,6 +24395,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.initClient(params); connect.core.initAgentAppClient(params); + connect.core.initTaskTemplatesClient(params); connect.core.initialized = true; }; @@ -24096,6 +24427,16 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); }; + + /**------------------------------------------------------------------------- + * Initialized TaskTemplates client + */ + connect.core.initTaskTemplatesClient = function (params) { + connect.assertNotNull(params, 'params'); + var endpoint = params.taskTemplatesEndpoint || params.endpoint; + connect.assertNotNull(endpoint, 'taskTemplatesEndpoint'); + connect.core.taskTemplatesClient = new connect.TaskTemplatesClient(endpoint); + }; /**------------------------------------------------------------------------- * Uninitialize Connect. @@ -24103,6 +24444,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core.terminate = function () { connect.core.client = new connect.NullClient(); connect.core.agentAppClient = new connect.NullClient(); + connect.core.taskTemplatesClient = new connect.NullClient(); connect.core.masterClient = new connect.NullClient(); var bus = connect.core.getEventBus(); if (bus) bus.unsubscribeAll(); @@ -24569,6 +24911,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi : AUTHORIZE_ENDPOINT; } var agentAppEndpoint = params.agentAppEndpoint || null; + var taskTemplatesEndpoint = params.taskTemplatesEndpoint || null; var authCookieName = params.authCookieName || null; try { @@ -24606,6 +24949,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi // Pass all downstream messages (from CCP consumer) upstream (to shared worker). conduit.onAllDownstream(conduit.passUpstream()); } + // Send configuration up to the shared worker. conduit.sendUpstream(connect.EventType.CONFIGURE, { authToken: authToken, @@ -24615,12 +24959,15 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi region: region, authorizeEndpoint: authorizeEndpoint, agentAppEndpoint: agentAppEndpoint, - authCookieName: authCookieName + taskTemplatesEndpoint: taskTemplatesEndpoint, + authCookieName: authCookieName, + longPollingOptions: params.longPollingOptions || undefined }); conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); connect.core.initialized = true; + connect.core._setTabId(); connect.core.portStreamId = data.id; this.unsubscribe(); }); @@ -24648,10 +24995,9 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); } }); - // Reload the page if the shared worker detects an API auth failure. - conduit.onUpstream(connect.EventType.AUTH_FAIL, function (logEntry) { - location.reload(); - }); + + connect.core.onAuthFail(connect.hitch(connect.core, connect.core._handleAuthFail, params.loginEndpoint || null, authorizeEndpoint)); // For auth retry logic on 401s. + connect.core.onAuthorizeSuccess(connect.hitch(connect.core, connect.core._handleAuthorizeSuccess)); // For auth retry logic on 401s. connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); @@ -24664,6 +25010,26 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); connect.numberOfConnectedCCPs = data.length; + if (data[connect.core.tabId] && !isNaN(data[connect.core.tabId].length)){ + if (connect.numberOfConnectedCCPsInThisTab !== data[connect.core.tabId].length) { + connect.numberOfConnectedCCPsInThisTab = data[connect.core.tabId].length; + if (connect.numberOfConnectedCCPsInThisTab > 1) { + connect.getLog().warn("There are " + connect.numberOfConnectedCCPsInThisTab + " connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(); + } + connect.publishMetric({ + name: CONNECTED_CCPS_SINGLE_TAB, + data: { count: connect.numberOfConnectedCCPsInThisTab} + }); + } + } + if (data.tabId && data.streamsTabsAcrossBrowser) { + connect.ifMaster(connect.MasterTopics.METRICS, () => + connect.agent(() => connect.publishMetric({ + name: CCP_TABS_ACROSS_BROWSER_COUNT, + data: { tabId: data.tabId, count: data.streamsTabsAcrossBrowser } + })) + ); + } }); connect.core.client = new connect.UpstreamConduitClient(conduit); @@ -24708,6 +25074,19 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi .withException(e).sendInternalLogToServer(); } }; + + connect.core._setTabId = function() { + try { + connect.core.tabId = window.sessionStorage.getItem(connect.SessionStorageKeys.TAB_ID); + if (!connect.core.tabId){ + connect.core.tabId = connect.randomId(); + window.sessionStorage.setItem(connect.SessionStorageKeys.TAB_ID, connect.core.tabId); + } + connect.core.upstream.sendUpstream(connect.EventType.TAB_ID, {tabId: connect.core.tabId}); + } catch(e) { + connect.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer(); + } + } /**------------------------------------------------------------------------- * Initializes Connect by creating or connecting to the API Shared Worker. @@ -24791,13 +25170,14 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); connect.core.portStreamId = data.id; - if (params.softphone || params.chat || params.pageOptions) { + if (params.softphone || params.chat || params.pageOptions || params.shouldAddNamespaceToLogs) { // Send configuration up to the CCP. //set it to false if secondary conduit.sendUpstream(connect.EventType.CONFIGURE, { softphone: params.softphone, chat: params.chat, - pageOptions: params.pageOptions + pageOptions: params.pageOptions, + shouldAddNamespaceToLogs: params.shouldAddNamespaceToLogs, }); } @@ -24819,20 +25199,22 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.getLog().info('Iframe initialization succeeded').sendInternalLogToServer(); connect.getLog().info(`Iframe initialization time ${initTime}`).sendInternalLogToServer(); connect.getLog().info(`Iframe refresh attempts ${refreshAttempts}`).sendInternalLogToServer(); - connect.publishMetric({ - name: CSM_IFRAME_REFRESH_ATTEMPTS, - data: refreshAttempts - }); - connect.publishMetric({ - name: CSM_IFRAME_INITIALIZATION_SUCCESS, - data: 1 - }); - connect.publishMetric({ - name: CSM_IFRAME_INITIALIZATION_TIME, - data: initTime - }); - //to avoid metric emission after initialization - initStartTime = null; + setTimeout(() => { + connect.publishMetric({ + name: CSM_IFRAME_REFRESH_ATTEMPTS, + data: { count: refreshAttempts} + }); + connect.publishMetric({ + name: CSM_IFRAME_INITIALIZATION_SUCCESS, + data: { count: 1} + }); + connect.publishMetric({ + name: CSM_IFRAME_INITIALIZATION_TIME, + data: { count: initTime} + }); + //to avoid metric emission after initialization + initStartTime = null; + },1000) } }); @@ -24901,11 +25283,11 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.getLog().info(`Iframe refresh attempts ${refreshAttempts}`).sendInternalLogToServer(); connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, - data: refreshAttempts + data: { count: refreshAttempts} }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, - data: 0 + data: { count: 0} }); initStartTime = null; } @@ -24964,7 +25346,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var iframe = document.createElement('iframe'); iframe.src = initCCPParams.ccpUrl; iframe.allow = "microphone; autoplay"; - iframe.style = "width: 100%; height: 100%"; + iframe.style = initCCPParams.style || "width: 100%; height: 100%"; iframe.title = initCCPParams.iframeTitle || CCP_IFRAME_NAME; iframe.name = CCP_IFRAME_NAME; containerDiv.appendChild(iframe); @@ -25409,6 +25791,99 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.core.onAuthFail = function (f) { connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); }; + + connect.core.onAuthorizeSuccess = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.AUTHORIZE_SUCCESS, f); + } + + connect.core._handleAuthorizeSuccess = function() { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); + } + + connect.core._handleAuthFail = function(loginUrl, authorizeEndpoint, authFailData) { + if (authFailData && authFailData.authorize) { + connect.core._handleAuthorizeFail(loginUrl); + } + else { + connect.core._handleCTIAuthFail(authorizeEndpoint); + } + } + + connect.core._handleAuthorizeFail = function(loginUrl) { + let authRetryCount = connect.core._getAuthRetryCount() + if (!connect.core.authorizeTimeoutId) { + if (authRetryCount < connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION) { + connect.core._incrementAuthRetryCount(); + let retryDelay = AWS.util.calculateRetryDelay(authRetryCount + 1 || 0, { base: 2000 }); + connect.core.authorizeTimeoutId = setTimeout(() => { + connect.core._redirectToLogin(loginUrl); + }, retryDelay); //We don't have to clear the timeoutId because we are redirecting away from this origin once the timeout completes. + } + else { + connect.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(); + connect.core.getEventBus().trigger(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED); + } + } + } + + connect.core._redirectToLogin = function(loginUrl) { + if (typeof(loginUrl) === 'string') { + location.assign(loginUrl); + } else { + location.reload(); + } + } + + connect.core._handleCTIAuthFail = function(authorizeEndpoint) { + if (!connect.core.ctiTimeoutId) { + if (connect.core.ctiAuthRetryCount < connect.core.MAX_CTI_AUTH_RETRY_COUNT) { + connect.core.ctiAuthRetryCount++; + let retryDelay = AWS.util.calculateRetryDelay(connect.core.ctiAuthRetryCount || 0, { base: 500 }); + connect.core.ctiTimeoutId = setTimeout(() => { + connect.core.authorize(authorizeEndpoint).then(connect.core._triggerAuthorizeSuccess.bind(connect.core)).catch(connect.core._triggerAuthFail.bind(connect.core, {authorize: true})); + connect.core.ctiTimeoutId = null; + }, retryDelay); + } + else { + connect.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(); + connect.core.getEventBus().trigger(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED); + } + } + } + + connect.core._triggerAuthorizeSuccess = function() { + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTHORIZE_SUCCESS); + } + + connect.core._triggerAuthFail = function(data) { + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTH_FAIL, data); + } + + connect.core._getAuthRetryCount = function() { + let item = window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT); + if (item !== null) { + if (!isNaN(parseInt(item))) { + return parseInt(item); + } else { + throw new connect.StateError("The session storage value for auth retry count was NaN"); + } + } else { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); + return 0; + } + } + + connect.core._incrementAuthRetryCount = function() { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, (connect.core._getAuthRetryCount()+1).toString()); + } + + connect.core.onAuthorizeRetriesExhausted = function(f) { + connect.core.getEventBus().subscribe(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED, f); + } + + connect.core.onCTIAuthorizeRetriesExhausted = function(f) { + connect.core.getEventBus().subscribe(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED, f); + } /** ------------------------------------------------- */ @@ -25552,6 +26027,15 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi }; connect.core.agentAppClient = null; + /**-----------------------------------------------------------------------*/ + connect.core.getTaskTemplatesClient = function () { + if (!connect.core.taskTemplatesClient) { + throw new connect.StateError('The connect TaskTemplates Client has not been initialized!'); + } + return connect.core.taskTemplatesClient; + }; + connect.core.taskTemplatesClient = null; + /**-----------------------------------------------------------------------*/ connect.core.getMasterClient = function () { if (!connect.core.masterClient) { @@ -25647,7 +26131,11 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi "update_connected_ccps", "outer_context_info", "media_device_request", - "media_device_response" + "media_device_response", + "tab_id", + 'authorize_success', + 'authorize_retries_exhausted', + 'cti_authorize_retries_exhausted', ]); /**--------------------------------------------------------------- @@ -25973,7 +26461,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi /***/ 286: /***/ (() => { -!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function k(e){return(k=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function h(e,n){return(h=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,k(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&h(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{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}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={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},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),k=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},h=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"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+h(t.primary)+" | Secondary WebSocket: "+h(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||k(c.connectionGain),o.connState=f;var n=Date.now();k(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),k(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return k(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));k(c.allMessage,o),c.topic.has(o.topic)&&k(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void k(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+h(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),k(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",n)),v("webSocketOnClose before-cleanup"),k(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(k(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); +!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,n){return(k=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,h(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{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}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={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},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),h=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},k=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"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+k(t.primary)+" | Secondary WebSocket: "+k(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||h(c.connectionGain),o.connState=f;var n=Date.now();h(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),h(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return h(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));h(c.allMessage,o),c.topic.has(o.topic)&&h(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void h(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?0!==Array.from(d.pending).length&&(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+k(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),h(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",JSON.stringify(n))),v("webSocketOnClose before-cleanup"),h(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(h(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); //# sourceMappingURL=amazon-connect-websocket-manager.js.map @@ -26165,7 +26653,18 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var LoggedException = function (e) { this.type = (e instanceof Error) ? e.name : e.code || Object.prototype.toString.call(e); this.message = e.message; - this.stack = e.stack ? e.stack.split('\n') : []; + this.stack = []; + if (e.stack){ + try { + if (Array.isArray(e.stack)) { + this.stack = e.stack; + } else if (typeof e.stack === 'object') { + this.stack = [JSON.stringify(e.stack)]; + } else if (typeof e.stack === 'string') { + this.stack = e.stack.split('\n'); + } + } catch {} + } }; /** @@ -26489,7 +26988,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi Logger.prototype.scheduleUpstreamLogPush = function (conduit) { if (!connect.upstreamLogPushScheduled) { connect.upstreamLogPushScheduled = true; - /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ + /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to the CTI backend*/ global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); } }; @@ -27323,7 +27822,6 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi } var gumPromise = fetchUserMedia({ success: function (stream) { - connect.core.setSoftphoneUserMediaStream(stream); publishTelemetryEvent("ConnectivityCheckResult", null, { connectivityCheckType: "MicrophonePermission", @@ -29211,6 +29709,19 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); }; + connect.addNamespaceToLogs = function(namespace) { + const methods = ['log', 'error', 'warn', 'info', 'debug']; + + methods.forEach((method) => { + const consoleMethod = window.console[method]; + window.console[method] = function () { + const args = Array.from(arguments); + args.unshift(`[${namespace}]`); + consoleMethod.apply(window.console, args); + }; + }); + }; + /** * A wrapper around Window.open() for managing single instance popups. */ @@ -29393,6 +29904,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi var conduit = connect.core.getUpstream(); return conduit.name === 'ConnectSharedWorkerConduit'; } + })(); @@ -29476,6 +29988,17 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi callbacks.failure(error); } }) + } else if(connect.containsValue(connect.TaskTemplatesClientMethods, method)) { + connect.core.getTaskTemplatesClient()._callImpl(method, params, { + success: function (data) { + self._recordAPILatency(method, request_start); + callbacks.success(data); + }, + failure: function (error) { + self._recordAPILatency(method, request_start, error); + callbacks.failure(error); + } + }) } else { connect.core.getClient()._callImpl(method, params, { success: function (data) { @@ -29533,10 +30056,15 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi this.nextToken = null; this.initData = {}; this.portConduitMap = {}; + this.streamMapByTabId = {}; this.masterCoord = new MasterTopicCoordinator(); this.logsBuffer = []; this.suppress = false; this.forceOffline = false; + this.longPollingOptions = { + allowLongPollingShadowMode: false, + allowLongPollingWebsocketOnlyMode: false, + } var webSocketManager = null; @@ -29557,6 +30085,14 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi if (data.authToken && data.authToken !== self.initData.authToken) { self.initData = data; connect.core.init(data); + if (data.longPollingOptions) { + if (typeof data.longPollingOptions.allowLongPollingShadowMode == "boolean") { + self.longPollingOptions.allowLongPollingShadowMode = data.longPollingOptions.allowLongPollingShadowMode; + } + if (typeof data.longPollingOptions.allowLongPollingWebsocketOnlyMode == "boolean") { + self.longPollingOptions.allowLongPollingWebsocketOnlyMode = data.longPollingOptions.allowLongPollingWebsocketOnlyMode; + } + } // init only once. if (!webSocketManager) { @@ -29685,12 +30221,10 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(self, self.pollForAgentConfiguration)); - portConduit.onDownstream(connect.EventType.CLOSE, function () { - self.multiplexer.removeStream(stream); - delete self.portConduitMap[stream.getId()]; - self.masterCoord.removeMaster(stream.getId()); - self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length }); - }); + portConduit.onDownstream(connect.EventType.TAB_ID, + connect.hitch(self, self.handleTabIdEvent, stream)); + portConduit.onDownstream(connect.EventType.CLOSE, + connect.hitch(self, self.handleCloseEvent, stream)); }; }; @@ -29942,7 +30476,7 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi .withException(err) .sendInternalLogToServer(); }, - authFailure: connect.hitch(self, self.handleAuthFail) + authFailure: connect.hitch(self, self.handleAuthFail, {authorize: true}) }); }; @@ -29988,6 +30522,57 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi portConduit.sendDownstream(response.event, response); }; + ClientEngine.prototype.handleTabIdEvent = function (stream, data) { + var self = this; + try { + let tabId = data.tabId; + let streamsInThisTab = self.streamMapByTabId[tabId]; + let currentStreamId = stream.getId(); + let tabIds = Object.keys(self.streamMapByTabId); + let streamsTabsAcrossBrowser = tabIds.filter(tabId => self.streamMapByTabId[tabId].length > 0).length; + if (streamsInThisTab && streamsInThisTab.length > 0){ + if (!streamsInThisTab.includes(currentStreamId)) { + self.streamMapByTabId[tabId].push(currentStreamId); + let updateObject = { length: Object.keys(self.portConduitMap).length, tabId, streamsTabsAcrossBrowser }; + updateObject[tabId] = { length: streamsInThisTab.length }; + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + } + } + else { + self.streamMapByTabId[tabId] = [stream.getId()]; + let updateObject = { length: Object.keys(self.portConduitMap).length, tabId, streamsTabsAcrossBrowser: streamsTabsAcrossBrowser + 1 }; + updateObject[tabId] = { length: self.streamMapByTabId[tabId].length }; + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + } + } catch(e) { + connect.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer(); + } + }; + + ClientEngine.prototype.handleCloseEvent = function(stream) { + var self = this; + self.multiplexer.removeStream(stream); + delete self.portConduitMap[stream.getId()]; + self.masterCoord.removeMaster(stream.getId()); + let updateObject = { length: Object.keys(self.portConduitMap).length }; + let tabIds = Object.keys(self.streamMapByTabId); + try { + let tabId = tabIds.find(key => self.streamMapByTabId[key].includes(stream.getId())); + if (tabId) { + let streamIndexInMap = self.streamMapByTabId[tabId].findIndex((value) => stream.getId() === value); + self.streamMapByTabId[tabId].splice(streamIndexInMap, 1); + let tabLength = self.streamMapByTabId[tabId] ? self.streamMapByTabId[tabId].length : 0; + updateObject[tabId] = { length: tabLength }; + updateObject.tabId = tabId; + } + let streamsTabsAcrossBrowser = tabIds.filter(tabId => self.streamMapByTabId[tabId].length > 0).length; + updateObject.streamsTabsAcrossBrowser = streamsTabsAcrossBrowser; + } catch(e) { + connect.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer(); + } + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + }; + ClientEngine.prototype.updateAgentConfiguration = function (configuration) { if (configuration.permissions && configuration.dialableCountries && @@ -30125,9 +30710,14 @@ AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.mi }); }; - ClientEngine.prototype.handleAuthFail = function () { + ClientEngine.prototype.handleAuthFail = function (data) { var self = this; - self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); + if (data) { + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL, data); + } + else { + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); + } }; ClientEngine.prototype.handleAccessDenied = function () { diff --git a/src/agent-app/agent-app.js b/src/agent-app/agent-app.js index 02bee74b..52e2eb49 100644 --- a/src/agent-app/agent-app.js +++ b/src/agent-app/agent-app.js @@ -81,7 +81,11 @@ var containerDOM = moduleData.containerDOM; return { init: function () { - if (name === APP.CCP) return signInThroughinitCCP(endpoint, containerDOM, config); + if (name === APP.CCP) { + config.ccpParams = config.ccpParams ? config.ccpParams : {}; + if (config.style) config.ccpParams.style = config.style; + return signInThroughinitCCP(endpoint, containerDOM, config); + } return connect.agentApp.initAppCommunication(name, endpoint); }, destroy: function () { diff --git a/src/api.js b/src/api.js index aa9b3cc2..e6dd9415 100644 --- a/src/api.js +++ b/src/api.js @@ -136,6 +136,7 @@ 'api', 'disconnect' ]); + /*---------------------------------------------------------------- * enum ChannelType @@ -515,6 +516,11 @@ Agent.prototype.setConfiguration = function (configuration, callbacks) { var client = connect.core.getClient(); + if (configuration && configuration.agentPreferences && configuration.agentPreferences.LANGUAGE && !configuration.agentPreferences.locale) { + // workaround for the inconsistency issue that getAgentConfiguration returns agentPreferences.LANGUAGE but updateAgentConfiguration expects agentPreferences.locale to be set. + configuration.agentPreferences.locale = configuration.agentPreferences.LANGUAGE; + } + if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { if (callbacks && callbacks.failure) { callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); @@ -843,6 +849,10 @@ return this._getData().contactFeatures; }; + Contact.prototype.getChannelContext = function () { + return this._getData().channelContext; + }; + Contact.prototype.isSoftphoneCall = function () { return connect.find(this.getConnections(), function (conn) { return conn.getSoftphoneMediaInfo() != null; @@ -1179,7 +1189,7 @@ return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; } - + /*---------------------------------------------------------------- * Voice authenticator VoiceId */ @@ -1583,9 +1593,10 @@ }); }; - VoiceId.prototype.checkEnrollmentStatus = function () { + VoiceId.prototype.checkEnrollmentStatus = function (callbackOnAudioCollectionComplete) { var self = this; var pollingTimes = 0; + var callbackOnAudioCollectionCompleteHasBeenInvoked = false; return new Promise(function (resolve, reject) { function describe () { @@ -1596,6 +1607,10 @@ resolve(data); break; case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: + if (!callbackOnAudioCollectionCompleteHasBeenInvoked && typeof callbackOnAudioCollectionComplete === 'function') { + callbackOnAudioCollectionComplete(data); + callbackOnAudioCollectionCompleteHasBeenInvoked = true; + } setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); break; case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: @@ -1628,7 +1643,7 @@ }); }; - VoiceId.prototype.enrollSpeaker = function () { + VoiceId.prototype.enrollSpeaker = function (callbackOnAudioCollectionComplete) { var self = this; self.checkConferenceCall(); return new Promise(function(resolve, reject) { @@ -1636,12 +1651,12 @@ self.getSpeakerStatus().then(function(data) { if(data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { self.deleteSpeaker().then(function() { - self.enrollSpeakerHelper(resolve, reject); + self.enrollSpeakerHelper(resolve, reject, callbackOnAudioCollectionComplete); }).catch(function(err) { reject(err); }); } else { - self.enrollSpeakerHelper(resolve, reject); + self.enrollSpeakerHelper(resolve, reject, callbackOnAudioCollectionComplete); } }).catch(function(err) { reject(err); @@ -1652,7 +1667,7 @@ }) } - VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject) { + VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject, callbackOnAudioCollectionComplete) { var self = this; var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); @@ -1666,7 +1681,7 @@ connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); } else { - self.checkEnrollmentStatus().then(function(data){ + self.checkEnrollmentStatus(callbackOnAudioCollectionComplete).then(function(data){ connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }).catch(function(err){ @@ -1914,8 +1929,8 @@ return this._speakerAuthenticator.evaluateSpeaker(startNew); } - VoiceConnection.prototype.enrollSpeakerInVoiceId = function() { - return this._speakerAuthenticator.enrollSpeaker(); + VoiceConnection.prototype.enrollSpeakerInVoiceId = function(callbackOnAudioCollectionComplete) { + return this._speakerAuthenticator.enrollSpeaker(callbackOnAudioCollectionComplete); } VoiceConnection.prototype.updateVoiceIdSpeakerId = function(speakerId) { @@ -1946,7 +1961,6 @@ }, callbacks); }; - /** * @class ChatConnection * @param {*} contactId diff --git a/src/aws-client.js b/src/aws-client.js index d674ab7b..0ef89e2c 100644 --- a/src/aws-client.js +++ b/src/aws-client.js @@ -1110,6 +1110,18 @@ module.exports={ "type": "boolean" } } + }, + "channelContext": { + "type": "structure", + "members": { + "scheduledTime": { + "type": "long" + }, + "taskTemplateId": {}, + "taskTemplateVersion": { + "type": "integer" + } + } } } } @@ -1470,7 +1482,7 @@ module.exports={ "contactId": {}, "ccpVersion": {}, "softphoneStreamStatistics": { - "shape": "S3r" + "shape": "S3t" } } }, @@ -1503,7 +1515,7 @@ module.exports={ "type": "timestamp" }, "softphoneStreamStatistics": { - "shape": "S3r" + "shape": "S3t" }, "gumTimeMillis": { "type": "long" @@ -1739,7 +1751,7 @@ module.exports={ } } }, - "S3r": { + "S3t": { "type": "list", "member": { "type": "structure", diff --git a/src/client.js b/src/client.js index 7234b202..68034ab5 100644 --- a/src/client.js +++ b/src/client.js @@ -72,6 +72,16 @@ 'checkMaster' ]); + /**--------------------------------------------------------------- + * enum TaskTemplatesClientMethods + */ + connect.TaskTemplatesClientMethods = connect.makeEnum([ + 'listTaskTemplates', + 'getTaskTemplate', + 'createTemplatedTask', + 'updateContact' + ]); + /**--------------------------------------------------------------- * abstract class ClientBase */ @@ -243,6 +253,7 @@ AWSClient.prototype.constructor = AWSClient; AWSClient.prototype._callImpl = function(method, params, callbacks) { + var self = this; var log = connect.getLog(); @@ -273,7 +284,19 @@ var error = {}; error.type = err.code; error.message = err.message; - error.stack = err.stack ? err.stack.split('\n') : []; + error.stack = []; + if (err.stack){ + try { + if (Array.isArray(err.stack)) { + error.stack = err.stack; + } else if (typeof err.stack === 'object') { + error.stack = [JSON.stringify(err.stack)]; + } else if (typeof err.stack === 'string') { + error.stack = err.stack.split('\n'); + } + } catch {} + } + callbacks.failure(error, data); } @@ -390,11 +413,93 @@ return report; }; + /**--------------------------------------------------------------- + * class TaskTemplatesClient extends ClientBase + */ + var TaskTemplatesClient = function(endpoint) { + connect.assertNotNull(endpoint, 'endpoint'); + ClientBase.call(this); + if (endpoint.includes('/task-templates')) { + this.endpointUrl = connect.getUrlWithProtocol(endpoint); + } else { + var AWSEndpoint = new AWS.Endpoint(endpoint); + var CFPrefix = endpoint.includes('.awsapps.com') ? '/connect' : ''; + this.endpointUrl = connect.getUrlWithProtocol(`${AWSEndpoint.host}${CFPrefix}/task-templates/api/ccp`); + } + }; + + TaskTemplatesClient.prototype = Object.create(ClientBase.prototype); + TaskTemplatesClient.prototype.constructor = TaskTemplatesClient; + + TaskTemplatesClient.prototype._callImpl = function(method, params, callbacks) { + connect.assertNotNull(method, 'method'); + connect.assertNotNull(params, 'params'); + var options = { + credentials: 'include', + method: 'GET', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'x-csrf-token': 'csrf' + } + }; + var instanceId = params.instanceId; + var url = this.endpointUrl; + var methods = connect.TaskTemplatesClientMethods; + switch (method) { + case methods.LIST_TASK_TEMPLATES: + url += `/proxy/instance/${instanceId}/task/template`; + if (params.queryParams) { + const queryString = new URLSearchParams(params.queryParams).toString(); + if (queryString) { + url += `?${queryString}`; + } + } + break; + case methods.GET_TASK_TEMPLATE: + connect.assertNotNull(params.templateParams, 'params.templateParams'); + const id = connect.assertNotNull(params.templateParams.id, 'params.templateParams.id'); + const version = params.templateParams.version; + url += `/proxy/instance/${instanceId}/task/template/${id}`; + if (version) { + url += `?snapshotVersion=${version}`; + } + break; + case methods.CREATE_TEMPLATED_TASK: + url += `/${method}`; + options.body = JSON.stringify(params); + options.method = 'PUT'; + break; + case methods.UPDATE_CONTACT: + url += `/${method}`; + options.body = JSON.stringify(params); + options.method = 'POST'; + } + connect.fetch(url, options) + .then(function(res){ + callbacks.success(res); + }).catch(function(err){ + const reader = err.body.getReader(); + let body = ''; + const decoder = new TextDecoder(); + reader.read().then(function processText({ done, value }) { + if (done) { + var error = JSON.parse(body); + error.status = err.status; + callbacks.failure(error); + return; + } + body += decoder.decode(value); + return reader.read().then(processText); + }); + }) + }; + connect.ClientBase = ClientBase; connect.NullClient = NullClient; connect.UpstreamConduitClient = UpstreamConduitClient; connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; connect.AWSClient = AWSClient; connect.AgentAppClient = AgentAppClient; - + connect.TaskTemplatesClient = TaskTemplatesClient; })(); diff --git a/src/core.js b/src/core.js index 5d479c2a..8b71bc57 100644 --- a/src/core.js +++ b/src/core.js @@ -41,7 +41,25 @@ var CSM_IFRAME_INITIALIZATION_SUCCESS = 'IframeInitializationSuccess'; var CSM_IFRAME_INITIALIZATION_TIME = 'IframeInitializationTime'; + var CONNECTED_CCPS_SINGLE_TAB = 'ConnectedCCPSingleTabCount'; + var CCP_TABS_ACROSS_BROWSER_COUNT = 'CCPTabsAcrossBrowserCount'; + connect.numberOfConnectedCCPs = 0; + connect.numberOfConnectedCCPsInThisTab = 0; + + connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION = 3; + connect.core.MAX_CTI_AUTH_RETRY_COUNT = 10; + connect.core.ctiAuthRetryCount = 0; + connect.core.authorizeTimeoutId = null; + connect.core.ctiTimeoutId = null; + + /*---------------------------------------------------------------- + * enum SessionStorageKeys + */ + connect.SessionStorageKeys = connect.makeEnum([ + 'tab_id', + 'authorize_retry_count', + ]); /** * @deprecated @@ -115,6 +133,7 @@ connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.initClient(params); connect.core.initAgentAppClient(params); + connect.core.initTaskTemplatesClient(params); connect.core.initialized = true; }; @@ -146,6 +165,16 @@ connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); }; + + /**------------------------------------------------------------------------- + * Initialized TaskTemplates client + */ + connect.core.initTaskTemplatesClient = function (params) { + connect.assertNotNull(params, 'params'); + var endpoint = params.taskTemplatesEndpoint || params.endpoint; + connect.assertNotNull(endpoint, 'taskTemplatesEndpoint'); + connect.core.taskTemplatesClient = new connect.TaskTemplatesClient(endpoint); + }; /**------------------------------------------------------------------------- * Uninitialize Connect. @@ -153,6 +182,7 @@ connect.core.terminate = function () { connect.core.client = new connect.NullClient(); connect.core.agentAppClient = new connect.NullClient(); + connect.core.taskTemplatesClient = new connect.NullClient(); connect.core.masterClient = new connect.NullClient(); var bus = connect.core.getEventBus(); if (bus) bus.unsubscribeAll(); @@ -619,6 +649,7 @@ : AUTHORIZE_ENDPOINT; } var agentAppEndpoint = params.agentAppEndpoint || null; + var taskTemplatesEndpoint = params.taskTemplatesEndpoint || null; var authCookieName = params.authCookieName || null; try { @@ -656,6 +687,7 @@ // Pass all downstream messages (from CCP consumer) upstream (to shared worker). conduit.onAllDownstream(conduit.passUpstream()); } + // Send configuration up to the shared worker. conduit.sendUpstream(connect.EventType.CONFIGURE, { authToken: authToken, @@ -665,12 +697,15 @@ region: region, authorizeEndpoint: authorizeEndpoint, agentAppEndpoint: agentAppEndpoint, - authCookieName: authCookieName + taskTemplatesEndpoint: taskTemplatesEndpoint, + authCookieName: authCookieName, + longPollingOptions: params.longPollingOptions || undefined }); conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); connect.core.initialized = true; + connect.core._setTabId(); connect.core.portStreamId = data.id; this.unsubscribe(); }); @@ -698,10 +733,9 @@ connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); } }); - // Reload the page if the shared worker detects an API auth failure. - conduit.onUpstream(connect.EventType.AUTH_FAIL, function (logEntry) { - location.reload(); - }); + + connect.core.onAuthFail(connect.hitch(connect.core, connect.core._handleAuthFail, params.loginEndpoint || null, authorizeEndpoint)); // For auth retry logic on 401s. + connect.core.onAuthorizeSuccess(connect.hitch(connect.core, connect.core._handleAuthorizeSuccess)); // For auth retry logic on 401s. connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); @@ -714,6 +748,26 @@ conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); connect.numberOfConnectedCCPs = data.length; + if (data[connect.core.tabId] && !isNaN(data[connect.core.tabId].length)){ + if (connect.numberOfConnectedCCPsInThisTab !== data[connect.core.tabId].length) { + connect.numberOfConnectedCCPsInThisTab = data[connect.core.tabId].length; + if (connect.numberOfConnectedCCPsInThisTab > 1) { + connect.getLog().warn("There are " + connect.numberOfConnectedCCPsInThisTab + " connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(); + } + connect.publishMetric({ + name: CONNECTED_CCPS_SINGLE_TAB, + data: { count: connect.numberOfConnectedCCPsInThisTab} + }); + } + } + if (data.tabId && data.streamsTabsAcrossBrowser) { + connect.ifMaster(connect.MasterTopics.METRICS, () => + connect.agent(() => connect.publishMetric({ + name: CCP_TABS_ACROSS_BROWSER_COUNT, + data: { tabId: data.tabId, count: data.streamsTabsAcrossBrowser } + })) + ); + } }); connect.core.client = new connect.UpstreamConduitClient(conduit); @@ -758,6 +812,19 @@ .withException(e).sendInternalLogToServer(); } }; + + connect.core._setTabId = function() { + try { + connect.core.tabId = window.sessionStorage.getItem(connect.SessionStorageKeys.TAB_ID); + if (!connect.core.tabId){ + connect.core.tabId = connect.randomId(); + window.sessionStorage.setItem(connect.SessionStorageKeys.TAB_ID, connect.core.tabId); + } + connect.core.upstream.sendUpstream(connect.EventType.TAB_ID, {tabId: connect.core.tabId}); + } catch(e) { + connect.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer(); + } + } /**------------------------------------------------------------------------- * Initializes Connect by creating or connecting to the API Shared Worker. @@ -841,13 +908,14 @@ connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); connect.core.portStreamId = data.id; - if (params.softphone || params.chat || params.pageOptions) { + if (params.softphone || params.chat || params.pageOptions || params.shouldAddNamespaceToLogs) { // Send configuration up to the CCP. //set it to false if secondary conduit.sendUpstream(connect.EventType.CONFIGURE, { softphone: params.softphone, chat: params.chat, - pageOptions: params.pageOptions + pageOptions: params.pageOptions, + shouldAddNamespaceToLogs: params.shouldAddNamespaceToLogs, }); } @@ -869,20 +937,22 @@ connect.getLog().info('Iframe initialization succeeded').sendInternalLogToServer(); connect.getLog().info(`Iframe initialization time ${initTime}`).sendInternalLogToServer(); connect.getLog().info(`Iframe refresh attempts ${refreshAttempts}`).sendInternalLogToServer(); - connect.publishMetric({ - name: CSM_IFRAME_REFRESH_ATTEMPTS, - data: refreshAttempts - }); - connect.publishMetric({ - name: CSM_IFRAME_INITIALIZATION_SUCCESS, - data: 1 - }); - connect.publishMetric({ - name: CSM_IFRAME_INITIALIZATION_TIME, - data: initTime - }); - //to avoid metric emission after initialization - initStartTime = null; + setTimeout(() => { + connect.publishMetric({ + name: CSM_IFRAME_REFRESH_ATTEMPTS, + data: { count: refreshAttempts} + }); + connect.publishMetric({ + name: CSM_IFRAME_INITIALIZATION_SUCCESS, + data: { count: 1} + }); + connect.publishMetric({ + name: CSM_IFRAME_INITIALIZATION_TIME, + data: { count: initTime} + }); + //to avoid metric emission after initialization + initStartTime = null; + },1000) } }); @@ -951,11 +1021,11 @@ connect.getLog().info(`Iframe refresh attempts ${refreshAttempts}`).sendInternalLogToServer(); connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, - data: refreshAttempts + data: { count: refreshAttempts} }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, - data: 0 + data: { count: 0} }); initStartTime = null; } @@ -1014,7 +1084,7 @@ var iframe = document.createElement('iframe'); iframe.src = initCCPParams.ccpUrl; iframe.allow = "microphone; autoplay"; - iframe.style = "width: 100%; height: 100%"; + iframe.style = initCCPParams.style || "width: 100%; height: 100%"; iframe.title = initCCPParams.iframeTitle || CCP_IFRAME_NAME; iframe.name = CCP_IFRAME_NAME; containerDiv.appendChild(iframe); @@ -1459,6 +1529,99 @@ connect.core.onAuthFail = function (f) { connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); }; + + connect.core.onAuthorizeSuccess = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.AUTHORIZE_SUCCESS, f); + } + + connect.core._handleAuthorizeSuccess = function() { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); + } + + connect.core._handleAuthFail = function(loginUrl, authorizeEndpoint, authFailData) { + if (authFailData && authFailData.authorize) { + connect.core._handleAuthorizeFail(loginUrl); + } + else { + connect.core._handleCTIAuthFail(authorizeEndpoint); + } + } + + connect.core._handleAuthorizeFail = function(loginUrl) { + let authRetryCount = connect.core._getAuthRetryCount() + if (!connect.core.authorizeTimeoutId) { + if (authRetryCount < connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION) { + connect.core._incrementAuthRetryCount(); + let retryDelay = AWS.util.calculateRetryDelay(authRetryCount + 1 || 0, { base: 2000 }); + connect.core.authorizeTimeoutId = setTimeout(() => { + connect.core._redirectToLogin(loginUrl); + }, retryDelay); //We don't have to clear the timeoutId because we are redirecting away from this origin once the timeout completes. + } + else { + connect.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(); + connect.core.getEventBus().trigger(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED); + } + } + } + + connect.core._redirectToLogin = function(loginUrl) { + if (typeof(loginUrl) === 'string') { + location.assign(loginUrl); + } else { + location.reload(); + } + } + + connect.core._handleCTIAuthFail = function(authorizeEndpoint) { + if (!connect.core.ctiTimeoutId) { + if (connect.core.ctiAuthRetryCount < connect.core.MAX_CTI_AUTH_RETRY_COUNT) { + connect.core.ctiAuthRetryCount++; + let retryDelay = AWS.util.calculateRetryDelay(connect.core.ctiAuthRetryCount || 0, { base: 500 }); + connect.core.ctiTimeoutId = setTimeout(() => { + connect.core.authorize(authorizeEndpoint).then(connect.core._triggerAuthorizeSuccess.bind(connect.core)).catch(connect.core._triggerAuthFail.bind(connect.core, {authorize: true})); + connect.core.ctiTimeoutId = null; + }, retryDelay); + } + else { + connect.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(); + connect.core.getEventBus().trigger(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED); + } + } + } + + connect.core._triggerAuthorizeSuccess = function() { + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTHORIZE_SUCCESS); + } + + connect.core._triggerAuthFail = function(data) { + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTH_FAIL, data); + } + + connect.core._getAuthRetryCount = function() { + let item = window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT); + if (item !== null) { + if (!isNaN(parseInt(item))) { + return parseInt(item); + } else { + throw new connect.StateError("The session storage value for auth retry count was NaN"); + } + } else { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); + return 0; + } + } + + connect.core._incrementAuthRetryCount = function() { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, (connect.core._getAuthRetryCount()+1).toString()); + } + + connect.core.onAuthorizeRetriesExhausted = function(f) { + connect.core.getEventBus().subscribe(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED, f); + } + + connect.core.onCTIAuthorizeRetriesExhausted = function(f) { + connect.core.getEventBus().subscribe(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED, f); + } /** ------------------------------------------------- */ @@ -1602,6 +1765,15 @@ }; connect.core.agentAppClient = null; + /**-----------------------------------------------------------------------*/ + connect.core.getTaskTemplatesClient = function () { + if (!connect.core.taskTemplatesClient) { + throw new connect.StateError('The connect TaskTemplates Client has not been initialized!'); + } + return connect.core.taskTemplatesClient; + }; + connect.core.taskTemplatesClient = null; + /**-----------------------------------------------------------------------*/ connect.core.getMasterClient = function () { if (!connect.core.masterClient) { diff --git a/src/event.js b/src/event.js index 65825862..3b9790a1 100644 --- a/src/event.js +++ b/src/event.js @@ -44,7 +44,11 @@ "update_connected_ccps", "outer_context_info", "media_device_request", - "media_device_response" + "media_device_response", + "tab_id", + 'authorize_success', + 'authorize_retries_exhausted', + 'cti_authorize_retries_exhausted', ]); /**--------------------------------------------------------------- diff --git a/src/index.d.ts b/src/index.d.ts index 3f7cc508..d947ec5a 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -89,6 +89,11 @@ declare namespace connect { */ initCCP(container: HTMLElement, options: InitCCPOptions): void; + /** + * Subscribes a callback function to be called when the agent authorization api succeeds. + */ + onAuthorizeSuccess(f: Function): void; + /** * Subscribes a callback function to be called when the connect.EventType.IFRAME_RETRIES_EXHAUSTED event is triggered. * @@ -96,6 +101,25 @@ declare namespace connect { */ onIframeRetriesExhausted(f: Function): void; + /** + * Subscribes a callback function to be called when multiple authorization-type CTI API failures have happened. + * After this event occurs, streams will not try to re-authenticate the user when more CTI API authorization-type (401) failures happen. + * Note that CTI APIs are the agent, contact, and connection apis (specifically, those listed under the `connect.ClientMethods` enum). + * Therefore, it may be prudent to indicate to the agent that there is a problem related to authorization. + * + * @param f The callback function. + */ + onCTIAuthorizeRetriesExhausted(f: Function): void; + + /** + * Subscribes a callback function to be called when multiple agent authorization api failures have happened. + * After this event occurs, streams will not try to redirect the user to login when more agent authorization api failures happen. + * Therefore, it may be prudent to indicate to the agent that there is a problem related to authorization. + * + * @param f The callback function. + */ + onAuthorizeRetriesExhausted(f: Function): void; + /** * Terminates Amazon Connect Streams. Removing any subscription methods that have been called. * The CCP iframe will not be removed though, so you'll have to manually remove it. @@ -190,7 +214,11 @@ declare namespace connect { UPDATE_CONNECTED_CCPS = 'update_connected_ccps', OUTER_CONTEXT_INFO = 'outer_context_info', MEDIA_DEVICE_REQUEST = 'media_device_request', - MEDIA_DEVICE_RESPONSE = 'media_device_response' + MEDIA_DEVICE_RESPONSE = 'media_device_response', + TAB_ID = 'tab_id', + AUTHORIZE_SUCCESS = 'authorize_success', + AUTHORIZE_RETRIES_EXHAUSTED = 'authorize_retries_exhausted', + CTI_AUTHORIZE_RETRIES_EXHAUSTED = 'cti_authorize_retries_exhausted', } const core: Core; diff --git a/src/lib/amazon-connect-websocket-manager.js b/src/lib/amazon-connect-websocket-manager.js index 2bc434de..9b8b3729 100644 --- a/src/lib/amazon-connect-websocket-manager.js +++ b/src/lib/amazon-connect-websocket-manager.js @@ -1,2 +1,2 @@ -!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function k(e){return(k=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function h(e,n){return(h=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,k(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&h(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{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}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={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},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),k=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},h=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"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+h(t.primary)+" | Secondary WebSocket: "+h(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||k(c.connectionGain),o.connState=f;var n=Date.now();k(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),k(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return k(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));k(c.allMessage,o),c.topic.has(o.topic)&&k(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void k(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+h(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),k(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",n)),v("webSocketOnClose before-cleanup"),k(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(k(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); +!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){"use strict";var o=t(1),r="NULL",i="CLIENT_LOGGER",c="DEBUG",s=2e3,a="aws/subscribe",u="aws/unsubscribe",l="aws/heartbeat",f="connected",p="disconnected";function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var b={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(e,n){return b.assertTrue(null!==e&&void 0!==d(e),Object(o.sprintf)("%s must be provided",n||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==d(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},g=new RegExp("^(wss://)\\w*");b.validWSUrl=function(e){return g.test(e)},b.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},b.assertIsObject=function(e,n){if(!b.isObject(e))throw new Error(n+" is not an object!")},b.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},b.isNetworkOnline=function(){return navigator.onLine},b.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var y=b;function m(e){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,n){return!n||"object"!==m(n)&&"function"!=typeof n?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):n}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,n){return(k=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function v(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function w(e,n){for(var t=0;t=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var n=e.prefix||"";return this._logsDestination===c?this.consoleLoggerWrapper:new N(n)}},{key:"updateLoggerConfig",value:function(e){var n=e||{};this._level=n.level||O.DEBUG,this._clientLogger=n.logger||null,this._logsDestination=r,n.debug&&(this._logsDestination=c),n.logger&&(this._logsDestination=i)}}]),e}(),W=function(){function e(){v(this,e)}return C(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),N=function(e){function n(e){var t;return v(this,n),(t=S(this,h(n).call(this))).prefix=e||"",t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(n,W),C(n,[{key:"debug",value:function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&void 0!==arguments[1]?arguments[1]:s;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}var n,t,o;return n=e,(t=[{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}}])&&F(n.prototype,t),o&&F(n,o),e}();t.d(n,"a",function(){return R});var x=function(){var e=E.getLogger({}),n=y.isNetworkOnline(),t={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},c={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},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},d={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},b={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},g=new L(function(){U()}),m=new Set([a,u,l]),S=setInterval(function(){if(n!==y.isNetworkOnline()){if(!(n=y.isNetworkOnline()))return void J(e.info("Network offline"));var t=O();n&&(!t||w(t,WebSocket.CLOSING)||w(t,WebSocket.CLOSED))&&(J(e.info("Network online, connecting to WebSocket server")),U())}},250),h=function(n,t){n.forEach(function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}})},k=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"}},v=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+k(t.primary)+" | Secondary WebSocket: "+k(t.secondary)))},w=function(e,n){return e&&e.readyState===n},C=function(e){return w(e,WebSocket.OPEN)},T=function(e){return null===e||void 0===e.readyState||w(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},I=function(){return C(O())},W=function(){if(i.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void U();I()?(J(e.debug("Sending heartbeat")),O().send(G(l)),i.pendingResponse=!0):(J(e.warn("Failed to send heartbeat since WebSocket is not open")),v("sendHeartBeat"),U())},N=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},_=function(){b.consecutiveFailedSubscribeAttempts=0,b.consecutiveNoResponseRequest=0,clearInterval(b.responseCheckIntervalId),clearInterval(b.reSubscribeIntervalId)},F=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},x=function(){try{J(e.info("WebSocket connection established!")),v("webSocketOnOpen"),null!==o.connState&&o.connState!==p||h(c.connectionGain),o.connState=f;var n=Date.now();h(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?n-r.noOpenConnectionsTimestamp:null}),F(),N(),O().openTimestamp=Date.now(),0===d.subscribed.size&&C(t.secondary)&&D(t.primary,"[Primary WebSocket] Closing WebSocket"),(d.subscribed.size>0||d.pending.size>0)&&(C(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),d.subscribed.forEach(function(e){d.subscriptionHistory.add(e),d.pending.add(e)}),d.subscribed.clear(),A()),W(),i.intervalHandle=setInterval(W,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout(function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U()},a)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},R=function(n){v("webSocketOnError"),J(e.error("WebSocketManager Error, error_event: ",JSON.stringify(n))),U()},j=function(n){var o=JSON.parse(n.data);switch(o.topic){case a:if(J(e.debug("Subscription Message received from webSocket server",n.data)),b.requestCompleted=!0,b.consecutiveNoResponseRequest=0,"success"===o.content.status)b.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach(function(e){d.subscriptionHistory.delete(e),d.pending.delete(e),d.subscribed.add(e)}),0===d.subscriptionHistory.size?C(t.secondary)&&(J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),D(t.primary,"[Primary WebSocket] Closing WebSocket")):A(),h(c.subscriptionUpdate,o);else{if(clearInterval(b.reSubscribeIntervalId),++b.consecutiveFailedSubscribeAttempts,5===b.consecutiveFailedSubscribeAttempts)return h(c.subscriptionFailure,o),void(b.consecutiveFailedSubscribeAttempts=0);b.reSubscribeIntervalId=setInterval(function(){A()},500)}break;case l:J(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(J(e.debug("Message received for topic "+o.topic)),C(t.primary)&&C(t.secondary)&&0===d.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));h(c.allMessage,o),c.topic.has(o.topic)&&h(c.topic.get(o.topic),o)}else o.message?J(e.warn("WebSocketManager Message Error",o)):J(e.warn("Invalid incoming message",o))}},A=function n(){if(b.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void h(c.subscriptionFailure,y.getSubscriptionResponse(a,!1,Array.from(d.pending)));I()?0!==Array.from(d.pending).length&&(clearInterval(b.responseCheckIntervalId),O().send(G(a,{topics:Array.from(d.pending)})),b.requestCompleted=!1,b.responseCheckIntervalId=setInterval(function(){b.requestCompleted||(++b.consecutiveNoResponseRequest,n())},1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},D=function(n,t){w(n,WebSocket.CONNECTING)||w(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+k(n)))},M=function(e){D(t.primary,"[Primary] WebSocket "+e),D(t.secondary,"[Secondary] WebSocket "+e)},P=function(){r.connectWebSocketRetryCount++;var n=y.addJitter(o.exponentialBackOffTime,.3);Date.now()+n<=s.connConfig.urlConnValidTime?(J(e.debug("Scheduling WebSocket reinitialization, after delay "+n+" ms")),o.exponentialTimeoutHandle=setTimeout(function(){return q()},n),o.exponentialBackOffTime*=2):(J(e.warn("WebSocket URL cannot be used to establish connection")),U())},H=function(n){N(),_(),J(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(S),h(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:n}),F()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(y.isObject(n)&&y.isObject(n.webSocketTransport)&&y.isNonEmptyString(n.webSocketTransport.url)&&y.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){if(y.isNetworkOnline())if(o.websocketInitFailed)J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return N(),J(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then(function(n){return s.promiseCompleted=!0,J(e.debug("Successfully fetched webSocket connection configuration",n)),z(n)?(s.connConfig=n,s.connConfig.urlConnValidTime=Date.now()+85e3,g.connected(),q()):(H("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})},function(n){return s.promiseCompleted=!0,J(e.error("Failed to fetch webSocket connection configuration",n)),y.isNetworkFailure(n)?(J(e.info("Retrying fetching new WebSocket connection configuration")),g.retry()):H("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}});J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else J(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},q=function(){if(o.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!y.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.info("Initializing Websocket Manager")),v("initWebSocket");try{if(z(s.connConfig)){var n=null;return C(t.primary)?(J(e.debug("Primary Socket connection is already open")),w(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),t.secondary=B()),n=t.secondary):(w(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),o.webSocketInitCheckerTimeoutId=setTimeout(function(){C(n)||P()},1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),H("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(s.connConfig.webSocketTransport.url);return n.addEventListener("open",x),n.addEventListener("message",j),n.addEventListener("error",R),n.addEventListener("close",function(i){return function(n,i){J(e.info("Socket connection is closed",JSON.stringify(n))),v("webSocketOnClose before-cleanup"),h(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),T(t.primary)&&(t.primary=null),T(t.secondary)&&(t.secondary=null),o.reconnectWebSocket&&(C(t.primary)||C(t.secondary)?T(t.primary)&&C(t.secondary)&&(J(e.info("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===p?J(e.info("Ignoring connectionLost callback invocation")):(h(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:n.code,reason:n.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=p,U()),v("webSocketOnClose after-cleanup"))}(i,n)}),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(y.assertTrue(y.isFunction(n),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.initFailure.add(e),o.websocketInitFailed&&e(),function(){return c.initFailure.delete(e)}},this.onConnectionOpen=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionOpen.add(e),function(){return c.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionClose.add(e),function(){return c.connectionClose.delete(e)}},this.onConnectionGain=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionGain.add(e),I()&&e(),function(){return c.connectionGain.delete(e)}},this.onConnectionLost=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.connectionLost.add(e),o.connState===p&&e(),function(){return c.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.subscriptionFailure.add(e),function(){return c.subscriptionFailure.delete(e)}},this.onMessage=function(e,n){return y.assertNotNull(e,"topicName"),y.assertTrue(y.isFunction(n),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(n):c.topic.set(e,new Set([n])),function(){return c.topic.get(e).delete(n)}},this.onAllMessage=function(e){return y.assertTrue(y.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){y.assertNotNull(e,"topics"),y.assertIsList(e),e.forEach(function(e){d.subscribed.has(e)||d.pending.add(e)}),b.consecutiveNoResponseRequest=0,A()},this.sendMessage=function(n){if(y.assertIsObject(n,"payload"),void 0===n.topic||m.has(n.topic))J(e.warn("Cannot send message, Invalid topic",n));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}I()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){N(),_(),o.reconnectWebSocket=!1,clearInterval(S),M("User request to close WebSocket")},this.terminateWebSocketManager=H},R={create:function(){return new x},setGlobalConfig:function(e){var n=e.loggerConfig;E.updateLoggerConfig(n)},LogLevel:O,Logger:T}},function(e,n,t){var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,s,a,u,l,f,p,d=1,b=e.length,g="";for(o=0;o=0),s.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,s.width?parseInt(s.width):0);break;case"e":t=s.precision?parseFloat(t).toExponential(s.precision):parseFloat(t).toExponential();break;case"f":t=s.precision?parseFloat(t).toFixed(s.precision):parseFloat(t);break;case"g":t=s.precision?String(Number(t.toPrecision(s.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=s.precision?t.substring(0,s.precision):t;break;case"t":t=String(!!t),t=s.precision?t.substring(0,s.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=s.precision?t.substring(0,s.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=s.precision?t.substring(0,s.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(s.type)?g+=t:(!r.number.test(s.type)||f&&!s.sign?p="":(p=f?"+":"-",t=t.toString().replace(r.sign,"")),u=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",l=s.width-(p+t).length,a=s.width&&l>0?u.repeat(l):"",g+=s.align?p+t+a:"0"===u?p+a+t:a+p+t)}return g}(function(e){if(s[e])return s[e];var n,t=e,o=[],i=0;for(;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],a=n[2],u=[];if(null===(u=r.key.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(a=a.substring(u[0].length));)if(null!==(u=r.key_access.exec(a)))c.push(u[1]);else{if(null===(u=r.index_access.exec(a)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return s[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var s=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()},function(e,n,t){"use strict";t.r(n),function(e){t.d(n,"WebSocketManager",function(){return r});var o=t(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,t(3))},function(e,n){var t;t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t}]); //# sourceMappingURL=amazon-connect-websocket-manager.js.map diff --git a/src/lib/amazon-connect-websocket-manager.js.map b/src/lib/amazon-connect-websocket-manager.js.map index 77d2c800..6157b434 100644 --- a/src/lib/amazon-connect-websocket-manager.js.map +++ b/src/lib/amazon-connect-websocket-manager.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/constants.js","webpack:///./src/utils.js","webpack:///./src/log.js","webpack:///./src/retryProvider.js","webpack:///./src/webSocketManager.js","webpack:///./node_modules/sprintf-js/src/sprintf.js","webpack:///./src/index.js","webpack:///(webpack)/buildin/global.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LOGS_DESTINATION","WEBSOCKET_RETRY_RATE_MS","ROUTE_KEY","CONN_STATE","Utils","premise","message","Error","assertTrue","undefined","_typeof","sprintf","length","Array","isArray","obj","constructor","apply","wsRegex","RegExp","validWSUrl","wsUrl","test","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","arguments","Math","min","sign","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","type","Logger","data","LogLevel","DEBUG","INFO","WARN","ERROR","LogManagerImpl","_classCallCheck","this","updateLoggerConfig","consoleLoggerWrapper","createConsoleLogger","level","logStatement","hasClientLogger","_clientLogger","debug","info","warn","error","_level","options","prefix","_logsDestination","LoggerWrapperImpl","inputConfig","config","logger","LoggerWrapper","_this","_possibleConstructorReturn","_getPrototypeOf","_len","args","_key","_log","_len2","_key2","_len3","_key3","_len4","_key4","LogManager","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","index","arg","_convertToString","isString","isFunction","toString","toStringResult","JSON","stringify","console","RetryProvider","executor","defaultRetry","retryProvider_classCallCheck","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","__webpack_exports__","WebSocketManagerObject","WebSocketManager","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","sendInternalLogToServer","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","now","Date","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","add","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","webSocketOnMessage","parse","topicName","has","from","close","closeWebSocket","retryWebSocketInitialization","waitTime","urlConnValidTime","initWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","then","connected","webSocketConnectionFailed","retry","getNewWebSocket","addEventListener","closeTimestamp","connectionDuration","code","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","setGlobalConfig","loggerConfig","__WEBPACK_AMD_DEFINE_RESULT__","re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key_access","index_access","parse_tree","argv","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","output","keys","param_no","Function","isNaN","TypeError","parseInt","String","fromCharCode","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_format","fmt","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","sprintf_parse","vsprintf","concat","window","global","_webSocketManager__WEBPACK_IMPORTED_MODULE_0__","connect","g","e"],"mappings":"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","file":"amazon-connect-websocket-manager.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","import Utils from \"./utils\";\nimport { LOGS_DESTINATION } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40\n};\n\nclass LogManagerImpl {\n constructor() {\n this.updateLoggerConfig();\n this.consoleLoggerWrapper = createConsoleLogger();\n }\n\n writeToClientLogger(level, logStatement) {\n if (!this.hasClientLogger()) {\n return;\n }\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStatement);\n case LogLevel.INFO:\n return this._clientLogger.info(logStatement);\n case LogLevel.WARN:\n return this._clientLogger.warn(logStatement);\n case LogLevel.ERROR:\n return this._clientLogger.error(logStatement);\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options) {\n var prefix = options.prefix || \"\";\n if (this._logsDestination === LOGS_DESTINATION.DEBUG) {\n return this.consoleLoggerWrapper;\n }\n return new LoggerWrapperImpl(prefix);\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.DEBUG;\n this._clientLogger = config.logger || null;\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(prefix) {\n super();\n this.prefix = prefix || \"\";\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n _shouldLog(level) {\n return LogManager.hasClientLogger() && LogManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return LogManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = this._convertToSingleStatement(args);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args) {\n var logStatement = \"\";\n if (this.prefix) {\n logStatement += this.prefix + \" \";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (toStringResult !== \"[object Object]\") {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = console.debug;\n logger.info = console.info;\n logger.warn = console.warn;\n logger.error = console.error;\n return logger;\n};\n\nconst LogManager = new LogManagerImpl();\n\nexport { LogManager, Logger, LogLevel };\n","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if(!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManager, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nconst WebSocketManager = function() {\n\n const logger = LogManager.getLogger({});\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set()\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig(); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n sendInternalLogToServer(logger.info(\"Network offline\"));\n\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n sendInternalLogToServer(logger.info(\"Network online, connecting to WebSocket server\"));\n\n getWebSocketConnConfig();\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function(callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function(ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function(ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function(ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function(ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function() {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function() {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function() {\n if (heartbeatConfig.pendingResponse) {\n sendInternalLogToServer(logger.warn(\"Heartbeat response not received\"));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig();\n return;\n }\n if (isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.debug(\"Sending heartbeat\"));\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n sendInternalLogToServer(logger.warn(\"Failed to send heartbeat since WebSocket is not open\"));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig();\n }\n };\n\n const resetWebSocketState = function() {\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n };\n\n const resetSubscriptions = function() {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function() {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function() {\n try {\n sendInternalLogToServer(logger.info(\"WebSocket connection established!\"));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function() {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig();\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function(event, ws) {\n sendInternalLogToServer(logger.info(\"Socket connection is closed\", event));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig();\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function(event) {\n printWebSocketState(\"webSocketOnError\");\n sendInternalLogToServer(logger.error(\"WebSocketManager Error, error_event: \", JSON.stringify(event)));\n\n getWebSocketConnConfig();\n };\n\n const webSocketOnMessage = function(event) {\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\", event.data));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach( topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(\"Heartbeat response received\"));\n\n heartbeatConfig.pendingResponse = false;\n break;\n }\n default: {\n if (response.topic) {\n sendInternalLogToServer(logger.debug(\"Message received for topic \" + response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n sendInternalLogToServer(logger.warn(\"WebSocketManager Message Error\", response));\n } else {\n sendInternalLogToServer(logger.warn(\"Invalid incoming message\", response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function() {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function(ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function(reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket reinitialization, after delay \" + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n sendInternalLogToServer(logger.warn(\"WebSocket URL cannot be used to establish connection\"));\n\n getWebSocketConnConfig();\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n sendInternalLogToServer(logger.error(\"WebSocket Initialization failed\"));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(\"Terminating WebSocket Manager\");\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function(payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic\", payload));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function(topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.info(\"Network offline, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n\n return;\n }\n resetWebSocketState();\n sendInternalLogToServer(logger.info(\"Fetching new WebSocket connection configuration\"));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function(response) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.debug(\"Successfully fetched webSocket connection configuration\", response));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n // Mark as a successful connection, and reset number of reconnect attempts\n reconnectionClient.connected();\n return initWebSocket();\n },\n function(reason) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.error(\"Failed to fetch webSocket connection configuration\", reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n sendInternalLogToServer(logger.info(\"Retrying fetching new WebSocket connection configuration\"));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function() {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n sendInternalLogToServer(logger.info(\"Initializing Websocket Manager\"));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n \n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function() {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n \n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function() {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function(transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function(topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n\n this.closeWebSocket = function() {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = () => {\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config.loggerConfig;\n LogManager.updateLoggerConfig(loggerConfig);\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger\n};\n\nexport { WebSocketManagerObject };\n","/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/constants.js","webpack:///./src/utils.js","webpack:///./src/log.js","webpack:///./src/retryProvider.js","webpack:///./src/webSocketManager.js","webpack:///./node_modules/sprintf-js/src/sprintf.js","webpack:///./src/index.js","webpack:///(webpack)/buildin/global.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LOGS_DESTINATION","WEBSOCKET_RETRY_RATE_MS","ROUTE_KEY","CONN_STATE","Utils","premise","message","Error","assertTrue","undefined","_typeof","sprintf","length","Array","isArray","obj","constructor","apply","wsRegex","RegExp","validWSUrl","wsUrl","test","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","arguments","Math","min","sign","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","type","Logger","data","LogLevel","DEBUG","INFO","WARN","ERROR","LogManagerImpl","_classCallCheck","this","updateLoggerConfig","consoleLoggerWrapper","createConsoleLogger","level","logStatement","hasClientLogger","_clientLogger","debug","info","warn","error","_level","options","prefix","_logsDestination","LoggerWrapperImpl","inputConfig","config","logger","LoggerWrapper","_this","_possibleConstructorReturn","_getPrototypeOf","_len","args","_key","_log","_len2","_key2","_len3","_key3","_len4","_key4","LogManager","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","index","arg","_convertToString","isString","isFunction","toString","toStringResult","JSON","stringify","console","RetryProvider","executor","defaultRetry","retryProvider_classCallCheck","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","__webpack_exports__","WebSocketManagerObject","WebSocketManager","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","sendInternalLogToServer","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","now","Date","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","add","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","webSocketOnMessage","parse","topicName","has","from","close","closeWebSocket","retryWebSocketInitialization","waitTime","urlConnValidTime","initWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","then","connected","webSocketConnectionFailed","retry","getNewWebSocket","addEventListener","closeTimestamp","connectionDuration","code","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","setGlobalConfig","loggerConfig","__WEBPACK_AMD_DEFINE_RESULT__","re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key_access","index_access","parse_tree","argv","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","output","keys","param_no","Function","isNaN","TypeError","parseInt","String","fromCharCode","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_format","fmt","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","sprintf_parse","vsprintf","concat","window","global","_webSocketManager__WEBPACK_IMPORTED_MODULE_0__","connect","g","e"],"mappings":"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","file":"amazon-connect-websocket-manager.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","import Utils from \"./utils\";\nimport { LOGS_DESTINATION } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40\n};\n\nclass LogManagerImpl {\n constructor() {\n this.updateLoggerConfig();\n this.consoleLoggerWrapper = createConsoleLogger();\n }\n\n writeToClientLogger(level, logStatement) {\n if (!this.hasClientLogger()) {\n return;\n }\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStatement);\n case LogLevel.INFO:\n return this._clientLogger.info(logStatement);\n case LogLevel.WARN:\n return this._clientLogger.warn(logStatement);\n case LogLevel.ERROR:\n return this._clientLogger.error(logStatement);\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options) {\n var prefix = options.prefix || \"\";\n if (this._logsDestination === LOGS_DESTINATION.DEBUG) {\n return this.consoleLoggerWrapper;\n }\n return new LoggerWrapperImpl(prefix);\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.DEBUG;\n this._clientLogger = config.logger || null;\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(prefix) {\n super();\n this.prefix = prefix || \"\";\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n _shouldLog(level) {\n return LogManager.hasClientLogger() && LogManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return LogManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = this._convertToSingleStatement(args);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args) {\n var logStatement = \"\";\n if (this.prefix) {\n logStatement += this.prefix + \" \";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (toStringResult !== \"[object Object]\") {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = console.debug;\n logger.info = console.info;\n logger.warn = console.warn;\n logger.error = console.error;\n return logger;\n};\n\nconst LogManager = new LogManagerImpl();\n\nexport { LogManager, Logger, LogLevel };\n","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if(!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManager, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nconst WebSocketManager = function() {\n\n const logger = LogManager.getLogger({});\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set()\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig(); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n sendInternalLogToServer(logger.info(\"Network offline\"));\n\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n sendInternalLogToServer(logger.info(\"Network online, connecting to WebSocket server\"));\n\n getWebSocketConnConfig();\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function(callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function(ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function(ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function(ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function(ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function() {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function() {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function() {\n if (heartbeatConfig.pendingResponse) {\n sendInternalLogToServer(logger.warn(\"Heartbeat response not received\"));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig();\n return;\n }\n if (isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.debug(\"Sending heartbeat\"));\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n sendInternalLogToServer(logger.warn(\"Failed to send heartbeat since WebSocket is not open\"));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig();\n }\n };\n\n const resetWebSocketState = function() {\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n };\n\n const resetSubscriptions = function() {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function() {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function() {\n try {\n sendInternalLogToServer(logger.info(\"WebSocket connection established!\"));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function() {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig();\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function(event, ws) {\n sendInternalLogToServer(logger.info(\"Socket connection is closed\", JSON.stringify(event)));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig();\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function(event) {\n printWebSocketState(\"webSocketOnError\");\n sendInternalLogToServer(logger.error(\"WebSocketManager Error, error_event: \", JSON.stringify(event)));\n\n getWebSocketConnConfig();\n };\n\n const webSocketOnMessage = function(event) {\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\", event.data));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach( topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(\"Heartbeat response received\"));\n\n heartbeatConfig.pendingResponse = false;\n break;\n }\n default: {\n if (response.topic) {\n sendInternalLogToServer(logger.debug(\"Message received for topic \" + response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n sendInternalLogToServer(logger.warn(\"WebSocketManager Message Error\", response));\n } else {\n sendInternalLogToServer(logger.warn(\"Invalid incoming message\", response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function() {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n if (Array.from(topicSubscription.pending).length === 0) {\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function(ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function(reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket reinitialization, after delay \" + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n sendInternalLogToServer(logger.warn(\"WebSocket URL cannot be used to establish connection\"));\n\n getWebSocketConnConfig();\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n sendInternalLogToServer(logger.error(\"WebSocket Initialization failed\"));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(\"Terminating WebSocket Manager\");\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function(payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic\", payload));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function(topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.info(\"Network offline, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n\n return;\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n\n return;\n }\n resetWebSocketState();\n sendInternalLogToServer(logger.info(\"Fetching new WebSocket connection configuration\"));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function(response) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.debug(\"Successfully fetched webSocket connection configuration\", response));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n // Mark as a successful connection, and reset number of reconnect attempts\n reconnectionClient.connected();\n return initWebSocket();\n },\n function(reason) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.error(\"Failed to fetch webSocket connection configuration\", reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n sendInternalLogToServer(logger.info(\"Retrying fetching new WebSocket connection configuration\"));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function() {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n sendInternalLogToServer(logger.info(\"Initializing Websocket Manager\"));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n \n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function() {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n \n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function() {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function(transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function(cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function(topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n\n this.closeWebSocket = function() {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = () => {\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config.loggerConfig;\n LogManager.updateLoggerConfig(loggerConfig);\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger\n};\n\nexport { WebSocketManagerObject };\n","/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/src/log.js b/src/log.js index 36f53b4a..07a21f8b 100644 --- a/src/log.js +++ b/src/log.js @@ -181,7 +181,18 @@ var LoggedException = function (e) { this.type = (e instanceof Error) ? e.name : e.code || Object.prototype.toString.call(e); this.message = e.message; - this.stack = e.stack ? e.stack.split('\n') : []; + this.stack = []; + if (e.stack){ + try { + if (Array.isArray(e.stack)) { + this.stack = e.stack; + } else if (typeof e.stack === 'object') { + this.stack = [JSON.stringify(e.stack)]; + } else if (typeof e.stack === 'string') { + this.stack = e.stack.split('\n'); + } + } catch {} + } }; /** @@ -505,7 +516,7 @@ Logger.prototype.scheduleUpstreamLogPush = function (conduit) { if (!connect.upstreamLogPushScheduled) { connect.upstreamLogPushScheduled = true; - /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ + /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to the CTI backend*/ global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); } }; diff --git a/src/softphone.js b/src/softphone.js index b9aaada8..49a940ac 100644 --- a/src/softphone.js +++ b/src/softphone.js @@ -84,7 +84,6 @@ } var gumPromise = fetchUserMedia({ success: function (stream) { - connect.core.setSoftphoneUserMediaStream(stream); publishTelemetryEvent("ConnectivityCheckResult", null, { connectivityCheckType: "MicrophonePermission", diff --git a/src/util.js b/src/util.js index 7543a3f3..f5cd4868 100644 --- a/src/util.js +++ b/src/util.js @@ -505,6 +505,19 @@ bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); }; + connect.addNamespaceToLogs = function(namespace) { + const methods = ['log', 'error', 'warn', 'info', 'debug']; + + methods.forEach((method) => { + const consoleMethod = window.console[method]; + window.console[method] = function () { + const args = Array.from(arguments); + args.unshift(`[${namespace}]`); + consoleMethod.apply(window.console, args); + }; + }); + }; + /** * A wrapper around Window.open() for managing single instance popups. */ @@ -687,4 +700,5 @@ var conduit = connect.core.getUpstream(); return conduit.name === 'ConnectSharedWorkerConduit'; } + })(); diff --git a/src/worker.js b/src/worker.js index cfdd566a..745b54b3 100644 --- a/src/worker.js +++ b/src/worker.js @@ -73,6 +73,17 @@ callbacks.failure(error); } }) + } else if(connect.containsValue(connect.TaskTemplatesClientMethods, method)) { + connect.core.getTaskTemplatesClient()._callImpl(method, params, { + success: function (data) { + self._recordAPILatency(method, request_start); + callbacks.success(data); + }, + failure: function (error) { + self._recordAPILatency(method, request_start, error); + callbacks.failure(error); + } + }) } else { connect.core.getClient()._callImpl(method, params, { success: function (data) { @@ -130,10 +141,15 @@ this.nextToken = null; this.initData = {}; this.portConduitMap = {}; + this.streamMapByTabId = {}; this.masterCoord = new MasterTopicCoordinator(); this.logsBuffer = []; this.suppress = false; this.forceOffline = false; + this.longPollingOptions = { + allowLongPollingShadowMode: false, + allowLongPollingWebsocketOnlyMode: false, + } var webSocketManager = null; @@ -154,6 +170,14 @@ if (data.authToken && data.authToken !== self.initData.authToken) { self.initData = data; connect.core.init(data); + if (data.longPollingOptions) { + if (typeof data.longPollingOptions.allowLongPollingShadowMode == "boolean") { + self.longPollingOptions.allowLongPollingShadowMode = data.longPollingOptions.allowLongPollingShadowMode; + } + if (typeof data.longPollingOptions.allowLongPollingWebsocketOnlyMode == "boolean") { + self.longPollingOptions.allowLongPollingWebsocketOnlyMode = data.longPollingOptions.allowLongPollingWebsocketOnlyMode; + } + } // init only once. if (!webSocketManager) { @@ -282,12 +306,10 @@ connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(self, self.pollForAgentConfiguration)); - portConduit.onDownstream(connect.EventType.CLOSE, function () { - self.multiplexer.removeStream(stream); - delete self.portConduitMap[stream.getId()]; - self.masterCoord.removeMaster(stream.getId()); - self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length }); - }); + portConduit.onDownstream(connect.EventType.TAB_ID, + connect.hitch(self, self.handleTabIdEvent, stream)); + portConduit.onDownstream(connect.EventType.CLOSE, + connect.hitch(self, self.handleCloseEvent, stream)); }; }; @@ -539,7 +561,7 @@ .withException(err) .sendInternalLogToServer(); }, - authFailure: connect.hitch(self, self.handleAuthFail) + authFailure: connect.hitch(self, self.handleAuthFail, {authorize: true}) }); }; @@ -585,6 +607,57 @@ portConduit.sendDownstream(response.event, response); }; + ClientEngine.prototype.handleTabIdEvent = function (stream, data) { + var self = this; + try { + let tabId = data.tabId; + let streamsInThisTab = self.streamMapByTabId[tabId]; + let currentStreamId = stream.getId(); + let tabIds = Object.keys(self.streamMapByTabId); + let streamsTabsAcrossBrowser = tabIds.filter(tabId => self.streamMapByTabId[tabId].length > 0).length; + if (streamsInThisTab && streamsInThisTab.length > 0){ + if (!streamsInThisTab.includes(currentStreamId)) { + self.streamMapByTabId[tabId].push(currentStreamId); + let updateObject = { length: Object.keys(self.portConduitMap).length, tabId, streamsTabsAcrossBrowser }; + updateObject[tabId] = { length: streamsInThisTab.length }; + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + } + } + else { + self.streamMapByTabId[tabId] = [stream.getId()]; + let updateObject = { length: Object.keys(self.portConduitMap).length, tabId, streamsTabsAcrossBrowser: streamsTabsAcrossBrowser + 1 }; + updateObject[tabId] = { length: self.streamMapByTabId[tabId].length }; + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + } + } catch(e) { + connect.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer(); + } + }; + + ClientEngine.prototype.handleCloseEvent = function(stream) { + var self = this; + self.multiplexer.removeStream(stream); + delete self.portConduitMap[stream.getId()]; + self.masterCoord.removeMaster(stream.getId()); + let updateObject = { length: Object.keys(self.portConduitMap).length }; + let tabIds = Object.keys(self.streamMapByTabId); + try { + let tabId = tabIds.find(key => self.streamMapByTabId[key].includes(stream.getId())); + if (tabId) { + let streamIndexInMap = self.streamMapByTabId[tabId].findIndex((value) => stream.getId() === value); + self.streamMapByTabId[tabId].splice(streamIndexInMap, 1); + let tabLength = self.streamMapByTabId[tabId] ? self.streamMapByTabId[tabId].length : 0; + updateObject[tabId] = { length: tabLength }; + updateObject.tabId = tabId; + } + let streamsTabsAcrossBrowser = tabIds.filter(tabId => self.streamMapByTabId[tabId].length > 0).length; + updateObject.streamsTabsAcrossBrowser = streamsTabsAcrossBrowser; + } catch(e) { + connect.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer(); + } + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); + }; + ClientEngine.prototype.updateAgentConfiguration = function (configuration) { if (configuration.permissions && configuration.dialableCountries && @@ -722,9 +795,14 @@ }); }; - ClientEngine.prototype.handleAuthFail = function () { + ClientEngine.prototype.handleAuthFail = function (data) { var self = this; - self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); + if (data) { + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL, data); + } + else { + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); + } }; ClientEngine.prototype.handleAccessDenied = function () { diff --git a/test/unit/agent-app.spec.js b/test/unit/agent-app.spec.js index e2302400..82fbbb10 100644 --- a/test/unit/agent-app.spec.js +++ b/test/unit/agent-app.spec.js @@ -104,6 +104,42 @@ describe('agent-app', function () { expect(connect.core.getEventBus().subscribe.called).to.be.true; }); + it('start CCP with style in ccpParams', function () { + var style = 'width:200px; height:200px;'; + var expectedParams = { + ccpUrl: 'https://www.amazon.com/ccp-v2/', + ccpLoadTimeout: 10000, + loginPopup: true, + loginUrl: 'https://www.amazon.com/login', + softphone: { + allowFramedSoftphone: true, + disableRingtone: false, + }, + style + }; + connect.agentApp.initApp('ccp', 'agent-app-dom', endpoint, { ccpParams: { style } }); + expect(connect.core.initCCP.calledWith(domCon, expectedParams)).to.be.true; + expect(connect.core.getEventBus().subscribe.called).to.be.true; + }); + + it('start CCP with style in agentapp config', function () { + var style = 'width:200px; height:200px;'; + var expectedParams = { + ccpUrl: 'https://www.amazon.com/ccp-v2/', + ccpLoadTimeout: 10000, + loginPopup: true, + loginUrl: 'https://www.amazon.com/login', + softphone: { + allowFramedSoftphone: true, + disableRingtone: false, + }, + style + }; + connect.agentApp.initApp('ccp', 'agent-app-dom', endpoint, { style }); + expect(connect.core.initCCP.calledWith(domCon, expectedParams)).to.be.true; + expect(connect.core.getEventBus().subscribe.called).to.be.true; + }); + it('adds a trailing slash to the url', function () { connect.agentApp.initApp('customer-profiles', 'agent-app-dom', endpoint); expect(connect.agentApp.initAppCommunication.calledWith('customer-profiles', endpoint + '/')).to.be.true; diff --git a/test/unit/agent.spec.js b/test/unit/agent.spec.js new file mode 100644 index 00000000..54226559 --- /dev/null +++ b/test/unit/agent.spec.js @@ -0,0 +1,116 @@ +require("../unit/test-setup.js"); + +describe('Agent APIs', () => { + const sandbox = sinon.createSandbox(); + let agent; + before(() => { + connect.agent.initialized = true; + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ + getAgentData: () => ({}) + }); + agent = new connect.Agent(); + }); + after(() => { + connect.agent.initialized = false; + sandbox.restore(); + }); + describe('setConfiguration', () => { + let mockedClientCall; + before(() => { + mockedClientCall = sinon.stub(); + sinon.stub(connect.core, 'getClient').callsFake(() => ({ + call: mockedClientCall + })); + }); + afterEach(() => { + mockedClientCall.resetHistory(); + }); + after(() => { + connect.core.getClient.restore(); + }); + it('should call UPDATE_AGENT_CONFIGURATION api with a given configuration object', () => { + const configuration = { + agentPreferences: { locale: "en_US" }, + someValue: 'test' + }; + agent.setConfiguration(configuration); + expect(mockedClientCall.firstCall.args[0]).to.equal(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION); + expect(mockedClientCall.firstCall.args[1]).to.deep.equal({ configuration }); + }); + + it('should copy LANGUAGE value to locale if locale is missing and LANGUAGE exists', () => { + const configuration = { + agentPreferences: { LANGUAGE: "en_US" } + }; + const expectedConfiguration = { + agentPreferences: { LANGUAGE: "en_US", locale: "en_US" } + }; + agent.setConfiguration(configuration); + expect(mockedClientCall.firstCall.args[0]).to.equal(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION); + expect(mockedClientCall.firstCall.args[1]).to.deep.equal({ configuration: expectedConfiguration }); + }); + + it('should NOT copy LANGUAGE value to locale if locale already exists', () => { + const configuration = { + agentPreferences: { LANGUAGE: "en_US", locale: "de_DE" } + }; + const expectedConfiguration = { + agentPreferences: { LANGUAGE: "en_US", locale: "de_DE" } + }; + agent.setConfiguration(configuration); + expect(mockedClientCall.firstCall.args[0]).to.equal(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION); + expect(mockedClientCall.firstCall.args[1]).to.deep.equal({ configuration: expectedConfiguration }); + }); + + it('should assert if configuration object is not passed in', () => { + sinon.stub(connect, 'assertNotNull'); + agent.setConfiguration(); + expect(connect.assertNotNull.called).to.be.true; + connect.assertNotNull.restore(); + }); + + it('should invoke failure callback if the provided locale is invalid', () => { + const configuration = { + agentPreferences: { locale: "invalid" } + }; + const callbacks = { + success: sinon.stub(), + failure: sinon.stub() + }; + agent.setConfiguration(configuration, callbacks); + expect(mockedClientCall.called).not.to.be.true; + expect(callbacks.success.called).not.to.be.true; + expect(callbacks.failure.called).to.be.true; + expect(callbacks.failure.firstCall.args[0]).to.equal(connect.AgentErrorStates.INVALID_LOCALE); + }); + + it('should invoke failure callback if the provided LANGUAGE is invalid', () => { + const configuration = { + agentPreferences: { LANGUAGE: "invalid" } + }; + const callbacks = { + success: sinon.stub(), + failure: sinon.stub() + }; + agent.setConfiguration(configuration, callbacks); + expect(mockedClientCall.called).not.to.be.true; + expect(callbacks.success.called).not.to.be.true; + expect(callbacks.failure.called).to.be.true; + expect(callbacks.failure.firstCall.args[0]).to.equal(connect.AgentErrorStates.INVALID_LOCALE); + }); + + it('should NOT invoke failure callback if the provided LANGUAGE is invalid but locale is valid', () => { + const configuration = { + agentPreferences: { locale: "en_US", LANGUAGE: "invalid" } + }; + const callbacks = { + success: sinon.stub(), + failure: sinon.stub() + }; + agent.setConfiguration(configuration, callbacks); + expect(mockedClientCall.called).to.be.true; + expect(callbacks.success.called).not.to.be.true; + expect(callbacks.failure.called).not.to.be.true; + }); + }); +}); \ No newline at end of file diff --git a/test/unit/connections.spec.js b/test/unit/connections.spec.js index 018c9de8..c5d45588 100644 --- a/test/unit/connections.spec.js +++ b/test/unit/connections.spec.js @@ -1,6 +1,7 @@ require("../unit/test-setup.js"); describe('Connections API', function () { + const sandbox = sinon.createSandbox(); describe('#Chat Connection API', function () { @@ -24,7 +25,7 @@ describe('Connections API', function () { before(function () { - connect.core.getAgentDataProvider = sinon.stub().returns({ + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ getContactData: () => { return {} }, _initMediaController: initMediaController, getConnectionData: () => { @@ -40,7 +41,7 @@ describe('Connections API', function () { after(function () { initMediaController.resetHistory(); - connect.core.getAgentDataProvider.resetBehavior(); + sandbox.restore(); }); it('Should create new Chat connection Object given the chat Contact and Connection Id ', function () { @@ -78,7 +79,7 @@ describe('Connections API', function () { before(function () { sinon.stub(connect.core, 'getClient'); - connect.core.getAgentDataProvider = sinon.stub().returns({ + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ getContactData: () => { return {connections:[{state:{type:"connected"}}]} }, _initMediaController: initMediaController, getConnectionData: () => { @@ -95,7 +96,7 @@ describe('Connections API', function () { after(function () { connect.core.getClient.restore(); initMediaController.resetHistory(); - connect.core.getAgentDataProvider.resetBehavior(); + sandbox.restore(); }); it('Should create new Voice connection Object given the Voice Contact and Connection Id with Speaker Authenticator ', function () { @@ -104,7 +105,7 @@ describe('Connections API', function () { assert.equal(voiceConnection.contactId, contactId); assert.equal(voiceConnection.getMediaType(), connect.MediaType.SOFTPHONE); assert.equal(typeof(voiceConnection.getVoiceIdSpeakerId), 'function'); - assert.equal(typeof(voiceConnection.getVoiceIdSpeakerStatus), 'function') + assert.equal(typeof(voiceConnection.getVoiceIdSpeakerStatus), 'function'); }); describe('getVoiceIdSpeakerId', function() { @@ -182,7 +183,7 @@ describe('Connections API', function () { before(function () { - connect.core.getAgentDataProvider = sinon.stub().returns({ + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ getContactData: () => { return { initialContactId: taskMediaInfo.initialContactId } }, @@ -205,7 +206,7 @@ describe('Connections API', function () { }); after(function() { - connect.core.getAgentDataProvider.resetBehavior(); + sandbox.restore(); }); it('Should create new Task connection Object given the task Contact and Connection Id ', function () { diff --git a/test/unit/core.spec.js b/test/unit/core.spec.js index 69b82251..909882a4 100644 --- a/test/unit/core.spec.js +++ b/test/unit/core.spec.js @@ -1,13 +1,13 @@ const { assert, expect } = require("chai"); - require("../unit/test-setup.js"); describe('Core', function () { var sandbox = sinon.createSandbox(); + const defaultRingtoneUrl = "https://d366s8lxuwna4d.cloudfront.net/ringtone-ba0c9bd8a1d12786318965fd908eb2998bdb8f4c.mp3"; + let params; beforeEach(function () { - this.defaultRingtoneUrl = "https://d366s8lxuwna4d.cloudfront.net/ringtone-ba0c9bd8a1d12786318965fd908eb2998bdb8f4c.mp3"; - this.params = { + params = { agentLogin: "abc", authToken: "xyz", authTokenExpiration: "Thu Apr 19 23:30:07 UTC 2018", @@ -17,32 +17,21 @@ describe('Core', function () { region: "us-west-2", sharedWorkerUrl: "/connect/static/connect-shared-worker.js", softphone: { - ringtoneUrl: this.defaultRingtoneUrl + ringtoneUrl: defaultRingtoneUrl }, chat: { - ringtoneUrl: this.defaultRingtoneUrl - } - }; - this.defaultRingtone = { - voice: { ringtoneUrl: this.defaultRingtoneUrl }, - queue_callback: { ringtoneUrl: this.defaultRingtoneUrl } - }; - this.extraRingtone = { - voice: { ringtoneUrl: this.defaultRingtoneUrl }, - queue_callback: { ringtoneUrl: this.defaultRingtoneUrl }, - chat: { ringtoneUrl: this.defaultRingtoneUrl }, - task: { ringtoneUrl: this.defaultRingtoneUrl } + ringtoneUrl: defaultRingtoneUrl + }, + shouldAddNamespaceToLogs: true }; }); describe('#connect.core.initSharedWorker()', function () { jsdom({ url: "http://localhost" }); - var clock + let clock, onAuthFailSpy, onAuthorizeSuccessSpy, hitchSpy; - beforeEach(function () { + before(function () { clock = sinon.useFakeTimers(); - this.containerDiv = { appendChild: sandbox.spy() }; - connect.core.initCCP(this.containerDiv, this.params); sandbox.stub(connect.core, "checkNotInitialized").returns(true); global.SharedWorker = sandbox.stub().returns({ port: { @@ -57,25 +46,28 @@ describe('Core', function () { }); sandbox.stub(connect.Conduit.prototype, 'sendUpstream').returns(null); + sandbox.stub(connect, 'randomId').returns('id'); + onAuthFailSpy = sandbox.stub(connect.core, 'onAuthFail'); + onAuthorizeSuccessSpy = sandbox.stub(connect.core, 'onAuthorizeSuccess'); + hitchSpy = sandbox.spy(connect, "hitch"); + sandbox.spy(connect, 'ifMaster'); }); - afterEach(function () { + after(function () { sandbox.restore(); clock.restore(); }); it("shared worker initialization", function () { - expect(this.params.sharedWorkerUrl).not.to.be.a("0"); - expect(this.params.authToken).not.to.be.a("null"); - expect(this.params.region).not.to.be.a("null"); - connect.core.initSharedWorker(this.params); + expect(params.sharedWorkerUrl).not.to.be.a("0"); + expect(params.authToken).not.to.be.a("null"); + expect(params.region).not.to.be.a("null"); + connect.core.initSharedWorker(params); expect(connect.core.checkNotInitialized.called); - expect(SharedWorker.calledWith(this.params.sharedWorkerUrl, "ConnectSharedWorker")); + expect(SharedWorker.calledWith(params.sharedWorkerUrl, "ConnectSharedWorker")); expect(connect.core.region).not.to.be.a("null"); - }); - it("should update the number of connected CCPs on UPDATE_CONNECTED_CCPS event", function () { - connect.core.initSharedWorker(this.params); - expect(connect.numberOfConnectedCCPs).to.equal(0); - connect.core.getUpstream().upstreamBus.trigger(connect.EventType.UPDATE_CONNECTED_CCPS, { length: 1 }); - expect(connect.numberOfConnectedCCPs).to.equal(1); + sandbox.assert.calledOnce(onAuthFailSpy); + sandbox.assert.calledOnce(onAuthorizeSuccessSpy); + sandbox.assert.calledWith(hitchSpy, sandbox.match.any, connect.core._handleAuthFail, sandbox.match.any, sandbox.match.any); + sandbox.assert.calledWith(hitchSpy, sandbox.match.any, connect.core._handleAuthorizeSuccess); }); it("should set portStreamId on ACK", function () { connect.core.getUpstream().upstreamBus.trigger(connect.EventType.ACKNOWLEDGE, { id: 'portId' }); @@ -105,6 +97,275 @@ describe('Core', function () { assert.lengthOf(logger._logs, originalLoggerLength + newLogs.length); }); }); + describe('onAuthFail', function () { + let getUpstreamSpy, onUpstreamSpy; + before(() => { + onUpstreamSpy = sandbox.fake(); + getUpstreamSpy = sandbox.stub(connect.core, "getUpstream").returns({onUpstream: onUpstreamSpy}); + }); + after(() => { + sandbox.restore(); + }); + it('calls getUpstream and sets the given function to trigger on the auth fail event via onUpstream', () => { + const spy = sandbox.fake(); + connect.core.onAuthFail(spy); + sandbox.assert.calledOnce(getUpstreamSpy); + sandbox.assert.calledOnceWithExactly(onUpstreamSpy, connect.EventType.AUTH_FAIL, spy); + }); + }); + describe('onAuthorizeSuccess', function () { + let getUpstreamSpy, onUpstreamSpy; + before(() => { + onUpstreamSpy = sandbox.fake(); + getUpstreamSpy = sandbox.stub(connect.core, "getUpstream").returns({onUpstream: onUpstreamSpy}); + }); + after(() => { + sandbox.restore(); + }); + it('calls getUpstream and sets the given function to trigger on the auth fail event via onUpstream', () => { + const spy = sandbox.fake(); + connect.core.onAuthorizeSuccess(spy); + sandbox.assert.calledOnce(getUpstreamSpy); + sandbox.assert.calledOnceWithExactly(onUpstreamSpy, connect.EventType.AUTHORIZE_SUCCESS, spy); + }); + }); + describe('_handleAuthorizeSuccess', function () { + jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); + it('resets the authRetryCount to 0', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 5); + connect.core._handleAuthorizeSuccess(); + assert.equal(window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT), 0); + }); + }); + describe('_handleAuthFail', function () { + let handleAuthorizeFailSpy, handleCTIAuthFailSpy; + const loginUrl = 'fakeLoginUrl.com/login'; + const authorizeEndpoint = '/authorize'; + const authFailData = {authorize: true}; + before(() => { + handleAuthorizeFailSpy = sandbox.stub(connect.core, "_handleAuthorizeFail"); + handleCTIAuthFailSpy = sandbox.stub(connect.core, "_handleCTIAuthFail"); + }); + after(() => { + sandbox.restore(); + }); + it('calls _handleAuthorizeFail in the case that the authFailData exists and has an authorize field that evaluates to true', () => { + connect.core._handleAuthFail(loginUrl, authorizeEndpoint, authFailData); + sandbox.assert.calledOnceWithExactly(handleAuthorizeFailSpy, loginUrl); + }); + it('calls _handleCTIAuthFail in the case that the authFailData exists and has an authorize field that evaluates to true', () => { + connect.core._handleAuthFail(loginUrl, authorizeEndpoint, null); + sandbox.assert.calledOnceWithExactly(handleCTIAuthFailSpy, authorizeEndpoint); + }); + }); + describe('_handleAuthorizeFail', function () { + jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); + let clock, calculateRetryDelaySpy, redirectToLoginSpy; + const loginUrl = 'fakeLoginUrl.com/login'; + before(() => { + calculateRetryDelaySpy = sandbox.stub(AWS.util, "calculateRetryDelay").returns(10); + clock = sandbox.useFakeTimers(); + redirectToLoginSpy = sandbox.stub(connect.core, "_redirectToLogin"); + eventBusTriggerSpy = sandbox.stub + sandbox.stub(connect.core, 'getEventBus').returns({ + trigger: sandbox.stub() + }); + }); + afterEach(() => { + clock.reset(); + }); + after(() => { + sandbox.restore(); + }); + it('Does not call redirectToLogin at all if authRetryCount is greater than max auth retry count for the session', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 4); + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + sandbox.assert.notCalled(calculateRetryDelaySpy); + sandbox.assert.notCalled(redirectToLoginSpy); + sandbox.assert.calledOnceWithExactly(connect.core.getEventBus().trigger, connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED); + }); + it('Does not call redirectToLogin at all if timeoutId is not null', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); + connect.core.authorizeTimeoutId = 'randomId'; + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + sandbox.assert.notCalled(calculateRetryDelaySpy); + sandbox.assert.notCalled(redirectToLoginSpy); + }); + it('will call redirectToLogin three times if the timeout has been cleared each time', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); //for clarity + connect.core.authorizeTimeoutId = null; + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + sandbox.assert.calledOnceWithExactly(calculateRetryDelaySpy, 1, {base: 2000}); + sandbox.assert.calledOnceWithExactly(redirectToLoginSpy, loginUrl); + connect.core.authorizeTimeoutId = null; + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + connect.core.authorizeTimeoutId = null; + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + sandbox.assert.calledThrice(calculateRetryDelaySpy); + sandbox.assert.calledThrice(redirectToLoginSpy); + connect.core.authorizeTimeoutId = null; + connect.core._handleAuthorizeFail(loginUrl); + clock.runAll(); + sandbox.assert.calledThrice(calculateRetryDelaySpy); + sandbox.assert.calledThrice(redirectToLoginSpy); + }); + }); + + describe('redirectToLogin', function () { + jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); + let reloadStub, assignStub; + before(() => { + reloadStub = sandbox.stub(location, "reload"); + assignStub = sandbox.stub(location, "assign"); + }); + after(() => { + sandbox.restore(); + }); + it('sets the window.location.href property if there is a loginUrl supplied', () => { + const loginUrl = 'fakeLogin/login'; + connect.core._redirectToLogin(loginUrl); + sandbox.assert.calledOnceWithExactly(assignStub, loginUrl); + }); + it('reloads the location if there is no loginUrl supplied', () => { + connect.core._redirectToLogin(null); + sandbox.assert.calledOnce(reloadStub); + }); + }); + + describe('_handleCTIAuthFail', function () { + let clock, calculateRetryDelaySpy, authorizeSpy, triggerAuthorizeSuccessStub, triggerAuthFailStub; + const authorizeEndpoint = 'fakeLoginUrl.com/authorize'; + before(() => { + calculateRetryDelaySpy = sandbox.stub(AWS.util, "calculateRetryDelay").returns(10); + clock = sandbox.useFakeTimers(); + authorizeSpy = sandbox.stub(connect.core, "authorize").resolves(); + triggerAuthorizeSuccessStub = sandbox.stub(connect.core, "_triggerAuthorizeSuccess"); + triggerAuthFailStub = sandbox.stub(connect.core, "_triggerAuthFail"); + sandbox.stub(connect.core, 'getEventBus').returns({ + trigger: sandbox.stub() + }); + }); + afterEach(() => { + clock.reset(); + }); + after(() => { + sandbox.restore(); + }); + const cycleCTIAuthFail = () => { + connect.core._handleCTIAuthFail(authorizeEndpoint); + clock.runAll(); + clock.runAll(); + } + it('does not do anything if the retry count is not smaller than the max', () => { + connect.core.ctiAuthRetryCount = 11; + connect.core._handleCTIAuthFail(authorizeEndpoint); + sandbox.assert.notCalled(calculateRetryDelaySpy); + sandbox.assert.notCalled(authorizeSpy); + connect.core._triggerAuthorizeSuccess(); + sandbox.assert.calledOnce(triggerAuthorizeSuccessStub); + sandbox.assert.calledOnceWithExactly(connect.core.getEventBus().trigger, connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED); + }); + it('does not do anything if the timeoutId is defined', () => { + connect.core.ctiAuthRetryCount = 0; + connect.core.ctiTimeoutId = "someId"; + connect.core._handleCTIAuthFail(authorizeEndpoint); + sandbox.assert.notCalled(calculateRetryDelaySpy); + sandbox.assert.notCalled(authorizeSpy); + }); + it('calls connect.core.authorize if the maximum number of retries is not exhausted', () => { + connect.core.ctiAuthRetryCount = 0; //for clarity + connect.core.ctiTimeoutId = null; + cycleCTIAuthFail(); + sandbox.assert.calledOnceWithExactly(calculateRetryDelaySpy, connect.core.ctiAuthRetryCount, {base: 500}); + sandbox.assert.calledOnceWithExactly(authorizeSpy, authorizeEndpoint); + sandbox.assert.calledOnce(calculateRetryDelaySpy); + sandbox.assert.calledOnce(triggerAuthorizeSuccessStub); + authorizeSpy.rejects(); + cycleCTIAuthFail(); + sandbox.assert.calledOnce(triggerAuthorizeSuccessStub); + for (let i = 0; i < 8; i++) { + cycleCTIAuthFail(); + }; + sandbox.assert.callCount(authorizeSpy, 10); + sandbox.assert.callCount(calculateRetryDelaySpy, 10); + sandbox.assert.callCount(triggerAuthorizeSuccessStub, 1); + cycleCTIAuthFail(); + sandbox.assert.callCount(authorizeSpy, 10); + sandbox.assert.callCount(calculateRetryDelaySpy, 10); + sandbox.assert.callCount(triggerAuthorizeSuccessStub, 1); + }); + }); + describe('_triggerAuthorizeSuccess / _triggerAuthFail', function () { + let triggerSpy = sandbox.fake(); + before(() => { + sandbox.stub(connect.core, "getUpstream").returns({upstreamBus: { trigger: triggerSpy}}); + }); + after(() => { + sandbox.restore(); + }); + it('calls trigger on the upstreamBus for the upstream conduit for the corresponding events', () => { + connect.core._triggerAuthorizeSuccess(); + sandbox.assert.calledOnceWithExactly(triggerSpy, connect.EventType.AUTHORIZE_SUCCESS); + let data = {authorize: true}; + connect.core._triggerAuthFail(data); + sandbox.assert.calledWith(triggerSpy, connect.EventType.AUTH_FAIL, data); + }); + }); + describe('_getAuthRetryCount', function () { + jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); + it('sets the session storage key to 0 and returns 0 when the key does not exist', () => { + expect(connect.core._getAuthRetryCount()).to.be.equal(0); + }); + it('throws an error if the value of the correct key is NaN but not null', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, "hellllllllo"); + expect(() => connect.core._getAuthRetryCount()).to.throw(); + }); + it('returns the storage field as an int if it is a valid number', () => { + window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, (5).toString()); + expect(connect.core._getAuthRetryCount()).to.be.equal(5); + }); + }); + describe('_incrementAuthRetryCount', function () { + jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); + let getAuthRetryCount; + let count = 0; + before(() => { + getAuthRetryCount = sandbox.stub(connect.core, "_getAuthRetryCount").returns(count); + }); + after(() => { + sandbox.restore(); + }); + it('sets the storage key to count + 1', () => { + connect.core._incrementAuthRetryCount(); + expect(parseInt(window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT))).to.be.equal(count+1); + count++; + getAuthRetryCount.returns(count); + connect.core._incrementAuthRetryCount(); + expect(parseInt(window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT))).to.be.equal(count+1); + }); + }); + describe('onAuthorizeRetriesExhausted / onCTIAuthorizeRetriesExhausted', function () { + let subscribeSpy = sandbox.fake(); + let inputFake = sandbox.fake(); + before(() => { + sandbox.stub(connect.core, "getEventBus").returns({subscribe: subscribeSpy}); + }); + after(() => { + sandbox.restore(); + }) + it('subscribes the input function to AUTHORIZE_RETRIES_EXHAUSTED', () => { + connect.core.onAuthorizeRetriesExhausted(inputFake); + sandbox.assert.calledOnceWithExactly(subscribeSpy, connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED, inputFake); + connect.core.onCTIAuthorizeRetriesExhausted(inputFake); + sandbox.assert.calledTwice(subscribeSpy); + sandbox.assert.calledWithExactly(subscribeSpy, connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED, inputFake); + }); + }); describe('legacy endpoint', function () { jsdom({ url: "https://abc.awsapps.com/connect/ccp-v2" }); @@ -132,7 +393,7 @@ describe('Core', function () { it("uses the legacy endpoint for a legacy url", function () { const href = "https://abc.awsapps.com/connect/ccp-v2"; window.location.href = href; - connect.core.initSharedWorker(this.params); + connect.core.initSharedWorker(params); assert.isTrue(connect.Conduit.prototype.sendUpstream.called); assert.isTrue(connect.Conduit.prototype.sendUpstream.getCalls()[0].lastArg.authorizeEndpoint === "/connect/auth/authorize"); }); @@ -162,12 +423,12 @@ describe('Core', function () { it("uses new endpoint for new url", function () { const href = "https://abc.my.connect.aws/ccp-v2"; - this.params.baseUrl = "https://abc.my.connect.aws"; + params.baseUrl = "https://abc.my.connect.aws"; window.location.href = href; - connect.core.initSharedWorker(this.params); + connect.core.initSharedWorker(params); assert.isTrue(connect.Conduit.prototype.sendUpstream.called); assert.isTrue(connect.Conduit.prototype.sendUpstream.getCalls()[0].lastArg.authorizeEndpoint === "/auth/authorize"); - this.params.baseUrl = "https://abc.my.connect.aws"; + params.baseUrl = "https://abc.my.connect.aws"; }); }); @@ -185,7 +446,7 @@ describe('Core', function () { onUpstream: sandbox.stub() }); - connect.core.getAgentDataProvider = sandbox.stub().returns({ + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ getAgentData: () => { return { configuration: { @@ -199,10 +460,15 @@ describe('Core', function () { }; } }); + + connect.core.eventBus = new connect.EventBus({ logEvents: true }); + connect.agent.initialized = true; }); after(function () { sandbox.restore(); + connect.core.eventBus = null; + connect.agent.initialized = false; }); describe('in Chrome', function() { @@ -215,7 +481,7 @@ describe('Core', function () { connect.getChromeBrowserVersion.restore(); }); it("Softphone manager should get initialized for master tab", function () { - connect.core.initSoftphoneManager(this.params); + connect.core.initSoftphoneManager(params); connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); @@ -235,7 +501,7 @@ describe('Core', function () { connect.getFirefoxBrowserVersion.restore(); }); it("Softphone manager should get initialized for master tab", function () { - connect.core.initSoftphoneManager(this.params); + connect.core.initSoftphoneManager(params); connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); @@ -243,7 +509,7 @@ describe('Core', function () { }); it("should set connect.core.softphoneParams", function () { - expect(connect.core.softphoneParams).to.include({ ringtoneUrl: this.defaultRingtoneUrl }); + expect(connect.core.softphoneParams).to.include({ ringtoneUrl: defaultRingtoneUrl }); }); }); }); @@ -251,14 +517,33 @@ describe('Core', function () { describe('#connect.core.initRingtoneEngines()', function () { jsdom({ url: "http://localhost" }); + before(() => { + connect.agent.initialized = true; + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ + getAgentData: () => ({}) + }); + connect.core.eventBus = new connect.EventBus({ logEvents: true }); + }); + + after(() => { + connect.agent.initialized = false; + sandbox.restore(); + connect.core.eventBus = null; + }); + describe('with default settings', function () { + let defaultRingtone; beforeEach(function () { + defaultRingtone = { + voice: { ringtoneUrl: defaultRingtoneUrl }, + queue_callback: { ringtoneUrl: defaultRingtoneUrl } + }; sandbox.stub(connect, "ifMaster"); sandbox.stub(connect, "VoiceRingtoneEngine"); sandbox.stub(connect, "QueueCallbackRingtoneEngine"); sandbox.stub(connect, "ChatRingtoneEngine"); sandbox.stub(connect, "TaskRingtoneEngine"); - connect.core.initRingtoneEngines({ ringtone: this.defaultRingtone }); + connect.core.initRingtoneEngines({ ringtone: defaultRingtone }); }); afterEach(function () { @@ -269,14 +554,14 @@ describe('Core', function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.VoiceRingtoneEngine.calledWithNew(this.defaultRingtone.voice)); + assert.isTrue(connect.VoiceRingtoneEngine.calledWithNew(defaultRingtone.voice)); }); it("Ringtone init with QueueCallbackRingtoneEngine", function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.QueueCallbackRingtoneEngine.calledWithNew(this.defaultRingtone.queue_callback)); + assert.isTrue(connect.QueueCallbackRingtoneEngine.calledWithNew(defaultRingtone.queue_callback)); }); it("Ringtone no init with ChatRingtoneEngine", function () { @@ -295,16 +580,23 @@ describe('Core', function () { }); describe('with optional chat and task ringtone params', function () { - before(function () { + let extraRingtone; + beforeEach(() => { + extraRingtone = { + voice: { ringtoneUrl: defaultRingtoneUrl }, + queue_callback: { ringtoneUrl: defaultRingtoneUrl }, + chat: { ringtoneUrl: defaultRingtoneUrl }, + task: { ringtoneUrl: defaultRingtoneUrl } + }; sandbox.stub(connect, "ifMaster"); sandbox.stub(connect, "VoiceRingtoneEngine"); sandbox.stub(connect, "QueueCallbackRingtoneEngine"); sandbox.stub(connect, "ChatRingtoneEngine"); sandbox.stub(connect, "TaskRingtoneEngine"); - connect.core.initRingtoneEngines({ ringtone: this.extraRingtone }); + connect.core.initRingtoneEngines({ ringtone: extraRingtone }); }); - after(function () { + afterEach(function () { sandbox.restore(); }); @@ -312,21 +604,21 @@ describe('Core', function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.VoiceRingtoneEngine.calledWithNew(this.extraRingtone.voice)); + assert.isTrue(connect.VoiceRingtoneEngine.calledWithNew(extraRingtone.voice)); }); it("Ringtone init with QueueCallbackRingtoneEngine", function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.QueueCallbackRingtoneEngine.calledWithNew(this.extraRingtone.queue_callback)); + assert.isTrue(connect.QueueCallbackRingtoneEngine.calledWithNew(extraRingtone.queue_callback)); }); it("Ringtone init with ChatRingtoneEngine", function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.ChatRingtoneEngine.calledWithNew(this.extraRingtone.chat)); + assert.isTrue(connect.ChatRingtoneEngine.calledWithNew(extraRingtone.chat)); }); @@ -334,7 +626,7 @@ describe('Core', function () { connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.TaskRingtoneEngine.calledWithNew(this.extraRingtone.task)); + assert.isTrue(connect.TaskRingtoneEngine.calledWithNew(extraRingtone.task)); }); }); }); @@ -342,22 +634,29 @@ describe('Core', function () { describe('#connect.core.initCCP()', function () { jsdom({ url: "http://localhost" }); let clock; + let containerDiv; let clearStub, openStub, closeStub; + const softphoneParams = { ringtoneUrl: "customVoiceRingtone.amazon.com" }; + const chatParams = { ringtoneUrl: "customChatRingtone.amazon.com" }; + const pageOptionsParams = { + enableAudioDeviceSettings: false, + enablePhoneTypeSettings: true + }; + const shouldAddNamespaceToLogs = false; before(function () { clock = sinon.useFakeTimers(); - this.containerDiv = { appendChild: sandbox.spy() }; - this.params = connect.merge({}, this.params, { + containerDiv = { appendChild: sandbox.spy() }; + params = { ccpUrl: "url.com", loginUrl: "loginUrl.com", - softphone: { - ringtoneUrl: "customVoiceRingtone.amazon.com" - }, - chat: { - ringtoneUrl: "customChatRingtone.amazon.com" - }, + softphone: softphoneParams, + chat: chatParams, loginOptions: { autoClose: true }, - }); + pageOptions: pageOptionsParams, + shouldAddNamespaceToLogs: shouldAddNamespaceToLogs + }; + clearStub = sandbox.fake(); closeStub = sandbox.fake(); openStub = sandbox.fake.returns({close: closeStub}); @@ -373,20 +672,27 @@ describe('Core', function () { sandbox.stub(connect.core, "_refreshIframeOnTimeout"); sandbox.stub(connect.core, "getPopupManager").returns({ clear: clearStub, open: openStub}) connect.numberOfConnectedCCPs = 0; - connect.core.initCCP(this.containerDiv, this.params); + connect.agent.initialized = true; + sandbox.stub(connect.core, 'getAgentDataProvider').returns({ + getAgentData: () => ({}) + }); + connect.core.eventBus = new connect.EventBus({ logEvents: true }); + connect.core.initCCP(containerDiv, params); }); after(function () { + connect.agent.initialized = false; + connect.core.eventBus = null; sandbox.restore(); clock.restore(); }); it("CCP initialization", function () { - expect(this.params.ccpUrl).not.to.be.a("null"); - expect(this.containerDiv).not.to.be.a("null"); + expect(params.ccpUrl).not.to.be.a("null"); + expect(containerDiv).not.to.be.a("null"); assert.isTrue(connect.core.checkNotInitialized.called); assert.isTrue(document.createElement.calledOnce); - assert.isTrue(this.containerDiv.appendChild.calledOnce); + assert.isTrue(containerDiv.appendChild.calledOnce); }); it("Replicates logs received upstream while ignoring duplicates", function () { @@ -412,31 +718,33 @@ describe('Core', function () { assert.lengthOf(logger._logs, originalLoggerLength + newLogs.length); }); - it("sends initCCP ringtone params on ACK", function () { - const spy = sinon.spy(connect.core.getUpstream(), "sendUpstream"); - connect.core.getUpstream().upstreamBus.trigger(connect.EventType.ACKNOWLEDGE, { id: 'portId' }); - assert.isTrue(connect.core.getUpstream().sendUpstream.calledWith(connect.EventType.CONFIGURE, { - softphone: this.params.softphone, - chat: this.params.chat, - pageOptions: this.params.pageOptions - })); - spy.restore(); - }); - + // TODO: add more granular test cases, also consider fixing the behavior it("sets up ringtone engines on CONFIGURE with initCCP params", function () { - connect.core.initRingtoneEngines({ ringtone: this.extraRingtone }); - connect.core.getEventBus().trigger(connect.EventType.CONFIGURE, { - softphone: this.params.softphone, - chat: this.params.chat, - pageOptions: this.params.pageOptions - }); + const defaultParamsPassedInByCCP = { + ringtone: { + voice: { disabled: false, ringtoneUrl: defaultRingtoneUrl }, + chat: { disabled: false, ringtoneUrl: defaultRingtoneUrl }, + task: { disabled: false, ringtoneUrl: defaultRingtoneUrl } + } + }; + + connect.core.initRingtoneEngines(defaultParamsPassedInByCCP); + const customParamsPassedInByCRM = { + softphone: { disabled: false, ringtoneUrl: 'custom-softphone.mp3' }, + ringtone: { + chat: { disabled: false, ringtoneUrl: 'custom-chat.mp3' }, + task: { disabled: false, ringtoneUrl: 'custom-task.mp3' }, // customization not working + queue_callback: { disabled: false, ringtoneUrl: 'custom-qcb.mp3' } // customization not working + } + }; + connect.core.getEventBus().trigger(connect.EventType.CONFIGURE, customParamsPassedInByCRM); connect.core.getEventBus().trigger(connect.AgentEvents.INIT, new connect.Agent()); connect.core.getEventBus().trigger(connect.AgentEvents.REFRESH, new connect.Agent()); connect.ifMaster.callArg(1); - assert.isTrue(connect.VoiceRingtoneEngine.calledWithNew(this.params.softphone)); - assert.isTrue(connect.QueueCallbackRingtoneEngine.calledWithNew(this.params.softphone)); - assert.isTrue(connect.ChatRingtoneEngine.calledWithNew(this.params.chat)); + sinon.assert.calledWith(connect.VoiceRingtoneEngine, customParamsPassedInByCRM.softphone); + sinon.assert.calledWith(connect.QueueCallbackRingtoneEngine, customParamsPassedInByCRM.softphone); // not 'custom-qcb.mp3' + sinon.assert.calledWith(connect.ChatRingtoneEngine, customParamsPassedInByCRM.ringtone.chat); }); it("should update the number of connected CCPs on UPDATE_CONNECTED_CCPS event", function () { @@ -447,10 +755,10 @@ describe('Core', function () { it("Multiple calls to initCCP does not append multiple CCP iframes", function() { sandbox.stub(window.document, "getElementsByTagName").returns([{ name: 'Amazon Connect CCP' }]); - connect.core.initCCP(this.containerDiv, this.params); - connect.core.initCCP(this.containerDiv, this.params); - connect.core.initCCP(this.containerDiv, this.params); - assert.isTrue(this.containerDiv.appendChild.calledOnce); + connect.core.initCCP(containerDiv, params); + connect.core.initCCP(containerDiv, params); + connect.core.initCCP(containerDiv, params); + assert.isTrue(containerDiv.appendChild.calledOnce); }) describe("on ACK", function () { @@ -460,11 +768,17 @@ describe('Core', function () { fakeOnInitHandler = sandbox.fake(); connect.core.onInitialized(fakeOnInitHandler); sandbox.stub(connect.WindowIOStream.prototype, 'send').returns(null); + sandbox.spy(connect.core.getUpstream(), "sendUpstream"); + connect.core.getUpstream().upstreamBus.trigger(connect.EventType.ACKNOWLEDGE, { id: 'portId' }); }); + after(() => { + connect.WindowIOStream.prototype.send.restore(); + connect.core.getUpstream().sendUpstream.restore(); + }); + it("should set portStreamId on ACK", function () { - connect.core.getUpstream().upstreamBus.trigger(connect.EventType.ACKNOWLEDGE, { id: 'portId' }); expect(connect.core.portStreamId).to.equal('portId'); connect.core.initialized = true; }); @@ -476,6 +790,15 @@ describe('Core', function () { it("should trigger INIT event on ACK", function () { expect(fakeOnInitHandler.callCount).to.equal(1); }); + + it("sends up CONFIGURE event with config params on ACK", function () { + sinon.assert.calledWith(connect.core.getUpstream().sendUpstream, connect.EventType.CONFIGURE, { + softphone: softphoneParams, + chat: chatParams, + pageOptions: pageOptionsParams, + shouldAddNamespaceToLogs: shouldAddNamespaceToLogs, + }); + }); }); describe("on ACK_TIMEOUT", function () { before(() => { @@ -486,9 +809,9 @@ describe('Core', function () { expect(clearStub.calledOnce).to.be.true; expect(clearStub.calledWith(connect.MasterTopics.LOGIN_POPUP)).to.be.true; expect(openStub.calledOnce).to.be.true; - expect(openStub.calledWith(this.params.loginUrl, connect.MasterTopics.LOGIN_POPUP, this.params.loginOptions)); + expect(openStub.calledWith(params.loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions)); }); - describe(" on ACK", function () { + describe("on ACK", function () { it("resets the iframe refresh timeout, calls popupManager.clear, calls loginWindow.close", () => { connect.core.getUpstream().upstreamBus.trigger(connect.EventType.ACKNOWLEDGE, { id: 'portId' }); expect(connect.core.iframeRefreshTimeout === null).to.be.true; @@ -530,24 +853,12 @@ describe('Core', function () { beforeEach(() => { clock = sinon.useFakeTimers(); }); - before(() => { - this.containerDiv = { appendChild: sandbox.spy() }; - this.params = connect.merge({}, this.params, { - ccpUrl: "url.com", - loginUrl: "loginUrl.com", - softphone: { - ringtoneUrl: "customVoiceRingtone.amazon.com" - }, - chat: { - ringtoneUrl: "customChatRingtone.amazon.com" - } - }); - }); afterEach(() => { clock.restore(); }); after(() => { sandbox.restore(); + connect.core.upstream = null; }) it("should teardown and stand up a new iframe 6 times, and then clean itself up and stop trying.", () => { let setTimeoutSpy = sandbox.spy(global, "setTimeout"); @@ -559,9 +870,9 @@ describe('Core', function () { let sendIframeStyleDataUpstreamAfterReasonableWaitTimeSpy = sandbox.stub(connect.core, "_sendIframeStyleDataUpstreamAfterReasonableWaitTime"); let triggerSpy = sandbox.fake(); sandbox.stub(connect.core, "getEventBus").returns({trigger: triggerSpy}); + connect.core.upstream = { upstream: {} }; - connect.core._refreshIframeOnTimeout(this.params, {}); - + connect.core._refreshIframeOnTimeout(params, {}); expect(setTimeoutSpy.calledOnce).to.be.true; expect(setTimeoutSpy.calledWith(sinon.match.any, sinon.match.number.and(sinon.match((timeout) => timeout <= 7000 && timeout >= 5000)))).to.be.true; expect(connect.core.iframeRefreshAttempt).not.to.equal(0); @@ -669,6 +980,15 @@ describe('Core', function () { sandbox.assert.calledWith(global.document.createElement, 'iframe'); expect(returnedIframe).to.be.deep.equal(expectedIframe); }); + it('creates CCP with style attribute in ccpParams', function() { + const style = "width:200px; height:200px;"; + const initCCPParams = { ...params, style }; + const expected = { ...expectedIframe, style }; + const returnedIframe = connect.core._createCCPIframe(containerDiv, initCCPParams); + expect(appendChildSpy.calledOnce).to.be.true; + sandbox.assert.calledWith(appendChildSpy, expected); + expect(returnedIframe).to.be.deep.equal(expected); + }); }); describe('_sendIframeStyleDataUpstreamAfterReasonableWaitTime', function () { @@ -688,7 +1008,6 @@ describe('Core', function () { sandbox.assert.calledOnceWithMatch(setTimeoutSpy, sandbox.match.func, 10000); }); it('sends an iframe style upstream with the expected data once the setTimeout executes its callback', function () { - // let sendUpstream = () => {}; let sendUpstreamSpy = sandbox.spy(); let conduit = { "sendUpstream": sendUpstreamSpy }; connect.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(iframe, conduit); @@ -704,6 +1023,34 @@ describe('Core', function () { }); }); + describe('_setTabId', function () { + jsdom({ url: "http://localhost" }); + let sendUpstream; + before(() => { + connect.core.upstream = { sendUpstream: () => {} }; + window.sessionStorage.setItem(connect.SessionStorageKeys.TAB_ID, null); + sendUpstream = sandbox.stub(connect.core.upstream, "sendUpstream"); + }) + beforeEach(() => { + sandbox.reset(); + connect.core.tabId = null; + }); + after(() => { + sandbox.restore(); + connect.core.upstream = null; + }); + it('create a new tabId if session storage does not contain a valid one', function () { + connect.core._setTabId(); + sandbox.assert.calledOnceWithMatch(sendUpstream, connect.EventType.TAB_ID, {tabId: sinon.match.string}); + }); + it('reuses the tabId if session storage has a valid one', function () { + let oldTabId = window.sessionStorage.getItem(connect.SessionStorageKeys.TAB_ID); + connect.core._setTabId(); + assert.isTrue(window.sessionStorage.getItem(connect.SessionStorageKeys.TAB_ID) === oldTabId); + sandbox.assert.calledOnceWithMatch(sendUpstream, connect.EventType.TAB_ID, {tabId: sinon.match.string}); + }); + }); + describe('verifyDomainAccess', function () { @@ -877,7 +1224,7 @@ describe('Core', function () { }); sandbox.stub(connect, "isFramed").returns(true); sandbox.stub(connect, "isCCP").returns(true); - connect.core.initPageOptions(this.params); + connect.core.initPageOptions(params); connect.isFramed.restore(); connect.isCCP.restore(); sandbox.stub(connect, "isFramed").returns(false); @@ -907,4 +1254,36 @@ describe('Core', function () { }); }); + describe('Task Templates Client initialization', function () { + before(() => { + AWS.Endpoint = function Endpoint(endpoint) { + this.host = endpoint; + } + sandbox.stub(connect, 'getUrlWithProtocol').callsFake(endpoint => `https://${endpoint}`); + }); + after(() => { + sandbox.restore(); + }); + it('initTaskTemplatesClient should throw an error if endpoint is not added to params', () => { + expect( function () { + connect.core.initTaskTemplatesClient(params); + } ).to.throw( Error ); + }); + it('TaskTemplatesClient constructor should build Task Templates API endpoint based on endpoint param if taskTemplatesEndpoint is not provided', () => { + params.endpoint = 'xyz.com'; + connect.core.initTaskTemplatesClient(params); + expect(connect.core.taskTemplatesClient.endpointUrl).to.equal("https://xyz.com/task-templates/api/ccp"); + }); + it('TaskTemplatesClient constructor should add "/connect" prefix to Task Templates API endpoint if endpoint param looks like a CF domain', () => { + params.endpoint = 'xyz.awsapps.com'; + connect.core.initTaskTemplatesClient(params); + expect(connect.core.taskTemplatesClient.endpointUrl).to.equal("https://xyz.awsapps.com/connect/task-templates/api/ccp"); + }); + it('TaskTemplatesClient constructor should build Task Templates API endpoint based on taskTemplatesEndpoint param if it is provided', () => { + params.endpoint = 'xyz.com'; + params.taskTemplatesEndpoint = 'abc.com/task-templates/api/ccp'; + connect.core.initTaskTemplatesClient(params); + expect(connect.core.taskTemplatesClient.endpointUrl).to.equal("https://abc.com/task-templates/api/ccp"); + }); + }); }); diff --git a/test/unit/softphone.spec.js b/test/unit/softphone.spec.js index 1a7a9271..8b87e12c 100644 --- a/test/unit/softphone.spec.js +++ b/test/unit/softphone.spec.js @@ -178,47 +178,4 @@ describe('SoftphoneManager', function () { }); }); }); - - describe('#SoftphoneManager successfully sets the softphoneUserMediaStreams', function () { - var bus, contact, contactId; - - before(function () { - bus = new connect.EventBus(); - contactId = "1234567890"; - contact = new connect.Contact(contactId); - }); - - beforeEach(function () { - sandbox.stub(connect.core, "getEventBus").returns(bus); - sandbox.stub(connect.core, "getUpstream").returns({ - sendUpstream: sandbox.stub() - }); - sandbox.stub(contact, "isSoftphoneCall").returns(true); - sandbox.stub(contact, "isInbound").returns(true); - sandbox.stub(connect, 'RTCSession').returns({ - connect: sandbox.stub() - }); - sandbox.stub(connect, 'getFirefoxBrowserVersion').returns(84); - sandbox.stub(connect.Agent.prototype, 'getContacts').returns([]); - }); - - afterEach(function () { - sandbox.restore(); - }); - - it('Successfully sets the softphoneUserMediaStreams in Chrome', async function () { - sandbox.stub(connect, 'isChromeBrowser').returns(false); - sandbox.stub(connect, 'isFirefoxBrowser').returns(true); - await new connect.SoftphoneManager({}); - - assert.isNotNull(connect.core.getSoftphoneUserMediaStream()); - }); - it('Successfully sets the softphoneUserMediaStreams in Firefox', async function () { - sandbox.stub(connect, 'isChromeBrowser').returns(true); - sandbox.stub(connect, 'isFirefoxBrowser').returns(false); - await new connect.SoftphoneManager({}); - - assert.isNotNull(connect.core.getSoftphoneUserMediaStream()); - }); - }); }); diff --git a/test/unit/voiceid.spec.js b/test/unit/voiceid.spec.js index bda128a6..a880b185 100644 --- a/test/unit/voiceid.spec.js +++ b/test/unit/voiceid.spec.js @@ -973,6 +973,32 @@ describe('VoiceId', () => { expect(error.type).to.equal(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT); expect(voiceId.describeSession.callCount).to.equal(connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES - 1); }); + + it('should invoke a callback when sufficient audio has been collected', async () => { + const enrollmentStatus = connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS; + const streamingStatus = connect.VoiceIdStreamingStatus.ONGOING; + const response = { + Session: { + "EnrollmentRequestDetails": { + Status: enrollmentStatus + }, + "StreamingStatus": streamingStatus + } + }; + const voiceId = new connect.VoiceId(contactId); + voiceId.describeSession = sinon.stub().callsFake(() => Promise.resolve(response)); + + const callback = sinon.stub(); + let error; + voiceId.checkEnrollmentStatus(callback).then(() => {}).catch((err) => { error = err }); + await clock.nextAsync(); + + expect(error).to.be.a('undefined'); + sinon.assert.calledOnce(callback); + + await clock.nextAsync(); + sinon.assert.calledOnce(callback); + }); }); describe('enrollSpeaker', () => { diff --git a/test/unit/worker.spec.js b/test/unit/worker.spec.js index 1afbd9a2..e99c8cc7 100644 --- a/test/unit/worker.spec.js +++ b/test/unit/worker.spec.js @@ -165,10 +165,82 @@ describe('Worker', function () { assert.isTrue(portConduit.sendDownstream.calledWith(expected.event, expected)); }); }); + describe('handleTabIdEvent', function() { + let stream, stream2, stream3; + let fakeConduit = {sendDownstream: sandbox.fake()}; + before(() => { + sandbox.reset(); + stream = { getId: () => "fakeStream"}; + stream2 = { getId: () => "fakeStream2"}; + stream3 = { getId: () => "fakeStream3"}; + }); + it('does not emit an event when there is a bad streamMapByTabId', function() { + connect.worker.clientEngine.streamMapByTabId = null; + connect.worker.clientEngine.handleTabIdEvent(stream, { tabId: 'tabId1' }); // should not throw an exception + sinon.assert.notCalled(connect.worker.clientEngine.conduit.sendDownstream); + }); + it('emits an update connected ccps event with the right data object when a new tabId is communicated by a stream', function () { + connect.worker.clientEngine.streamMapByTabId = {}; + connect.worker.clientEngine.portConduitMap = {"fakeStream": fakeConduit}; + connect.worker.clientEngine.handleTabIdEvent(stream, { tabId: 'tabId1' }); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId1'], ["fakeStream"]); + sinon.assert.calledWith(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 1, tabId: 'tabId1', streamsTabsAcrossBrowser: 1, 'tabId1': { length: 1}}); + + connect.worker.clientEngine.portConduitMap = {"fakeStream": fakeConduit, "fakeStream2": fakeConduit}; + connect.worker.clientEngine.handleTabIdEvent(stream2, { tabId: 'tabId1' }); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId1'], ["fakeStream", "fakeStream2"]); + sinon.assert.calledWith(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 2, tabId: 'tabId1', streamsTabsAcrossBrowser: 1, 'tabId1': { length: 2}}); + + connect.worker.clientEngine.portConduitMap = {"fakeStream": fakeConduit, "fakeStream2": fakeConduit, "fakeStream3": fakeConduit}; + connect.worker.clientEngine.handleTabIdEvent(stream3, { tabId: 'tabId2'}); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId2'], ["fakeStream3"]); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId1'], ["fakeStream", "fakeStream2"]); + sinon.assert.calledWith(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 3, tabId: 'tabId2', streamsTabsAcrossBrowser: 2, "tabId2": { length: 1}}); + + connect.worker.clientEngine.handleTabIdEvent(stream3, { tabId: 'tabId2'}); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId2'], ["fakeStream3"]); + assert.deepEqual(connect.worker.clientEngine.streamMapByTabId['tabId1'], ["fakeStream", "fakeStream2"]); + + sinon.assert.calledThrice(connect.worker.clientEngine.conduit.sendDownstream); + connect.worker.clientEngine.portConduitMap = {}; + }); + }); + describe('handleCloseEvent', function () { + let stream, stream2, stream3; + let fakeConduit = {sendDownstream: sandbox.fake()}; + before(() => { + stream = { getId: () => "fakeStream" }; + stream2 = { getId: () => "fakeStream2" }; + sandbox.reset(); + }); + after(() => { + connect.worker.clientEngine.portConduitMap = {}; + connect.worker.clientEngine.streamMapByTabId = {}; + }) + it('emits a data object with the UPDATE_CONNECTED_CCPS event to notify CCP of the change in connected ccps, without tab-specific info if the table does not contain this tab id', function() { + connect.worker.clientEngine.portConduitMap = {"fakeStream": fakeConduit}; + connect.worker.clientEngine.streamMapByTabId = {}; + connect.worker.clientEngine.handleCloseEvent(stream); + sinon.assert.calledOnceWithExactly(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 0, streamsTabsAcrossBrowser: 0}); + }); + it('removes the stream from this tab\'s list and emits a data object with the UPDATE_CONNECTED_CCPS event to notify CCP of that change', function() { + let streamHandleCloseEvent = connect.hitch(connect.worker.clientEngine, connect.worker.clientEngine.handleCloseEvent, stream); + connect.worker.clientEngine.portConduitMap = {"fakeStream1": fakeConduit, "fakeStream": fakeConduit, "fakeStream2": fakeConduit}; + connect.worker.clientEngine.streamMapByTabId = {'tabId1': ["fakeStream", "fakeStream2"]}; + streamHandleCloseEvent(); + assert.isTrue(connect.worker.clientEngine.streamMapByTabId['tabId1'].length === 1); + sinon.assert.calledTwice(connect.worker.clientEngine.conduit.sendDownstream); + sinon.assert.calledWith(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 2, 'tabId1': { length: 1 }, tabId: 'tabId1', streamsTabsAcrossBrowser: 1}); + let stream2HandleCloseEvent = connect.hitch(connect.worker.clientEngine, connect.worker.clientEngine.handleCloseEvent, stream2); + stream2HandleCloseEvent(); + sinon.assert.calledWith(connect.worker.clientEngine.conduit.sendDownstream, connect.EventType.UPDATE_CONNECTED_CCPS, {length: 1, 'tabId1': { length: 0 }, tabId: 'tabId1', streamsTabsAcrossBrowser: 0}); + }); + }); describe('global.onconnect()', function () { var dummyEvent; beforeEach(function() { + sandbox.reset(); dummyEvent = { ports: [ {